58 lines
2.1 KiB
Python
58 lines
2.1 KiB
Python
# pyrefly: ignore [missing-import]
|
|
from config.database import get_connection, release_connection
|
|
|
|
# ============================================
|
|
# REPOSITORY LAYER: Tương tác trực tiếp với bảng alert_config trong PostgreSQL
|
|
# ============================================
|
|
|
|
def insert_default_alert_config_db(device_id):
|
|
"""
|
|
Tạo cấu hình cảnh báo mặc định cho thiết bị mới.
|
|
|
|
Tham số mặc định trong DB/Đặc tả:
|
|
- is_enabled = True
|
|
- fail_threshold = 3 (lỗi 3 lần liên tiếp thì alert)
|
|
- cooldown_minutes = 30 (khoảng thời gian tối thiểu giữa 2 cảnh báo tránh spam)
|
|
- notify_web = True (thông báo hiển thị trên giao diện)
|
|
- notify_email = False (mặc định chưa bật gửi email)
|
|
"""
|
|
conn = get_connection()
|
|
cur = None
|
|
try:
|
|
cur = conn.cursor()
|
|
cur.execute("""
|
|
INSERT INTO alert_config (device_id, is_enabled, fail_threshold, cooldown_minutes, notify_web, notify_email)
|
|
VALUES (%s, %s, %s, %s, %s, %s)
|
|
RETURNING id, device_id, is_enabled, fail_threshold, cooldown_minutes, notify_web, notify_email, created, modified
|
|
""", (
|
|
device_id,
|
|
True, # is_enabled
|
|
3, # fail_threshold
|
|
30, # cooldown_minutes
|
|
True, # notify_web
|
|
False # notify_email
|
|
))
|
|
row = cur.fetchone()
|
|
conn.commit()
|
|
|
|
if row:
|
|
return {
|
|
"id": str(row[0]),
|
|
"device_id": str(row[1]),
|
|
"is_enabled": row[2],
|
|
"fail_threshold": row[3],
|
|
"cooldown_minutes": row[4],
|
|
"notify_web": row[5],
|
|
"notify_email": row[6],
|
|
"created": row[7].isoformat() if row[7] else None,
|
|
"modified": row[8].isoformat() if row[8] else None
|
|
}
|
|
return None
|
|
except Exception:
|
|
conn.rollback()
|
|
raise
|
|
finally:
|
|
if cur:
|
|
cur.close()
|
|
release_connection(conn)
|