From 48c5183c12837dd5582c98ad89c47362d477ed9e Mon Sep 17 00:00:00 2001 From: QuangMinh_123 Date: Fri, 29 May 2026 11:34:03 +0700 Subject: [PATCH] FixServiceDevies --- backend/modules/alert/repository.py | 57 ++++++++++++++++++++++++++++ backend/modules/alert/service.py | 12 ++++++ backend/modules/device/repository.py | 27 ++----------- backend/modules/device/service.py | 15 ++++++-- 4 files changed, 84 insertions(+), 27 deletions(-) create mode 100644 backend/modules/alert/repository.py create mode 100644 backend/modules/alert/service.py diff --git a/backend/modules/alert/repository.py b/backend/modules/alert/repository.py new file mode 100644 index 0000000..59c3008 --- /dev/null +++ b/backend/modules/alert/repository.py @@ -0,0 +1,57 @@ +# 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) diff --git a/backend/modules/alert/service.py b/backend/modules/alert/service.py new file mode 100644 index 0000000..7db49cb --- /dev/null +++ b/backend/modules/alert/service.py @@ -0,0 +1,12 @@ +# pyrefly: ignore [missing-import] +from modules.alert.repository import insert_default_alert_config_db + +# ============================================ +# SERVICE LAYER: Xử lý nghiệp vụ cho Module Alert +# ============================================ + +def create_default_alert_config_service(device_id): + """ + Tạo cấu hình cảnh báo mặc định cho thiết bị mới. + """ + return insert_default_alert_config_db(device_id) diff --git a/backend/modules/device/repository.py b/backend/modules/device/repository.py index 12adaba..271eeae 100644 --- a/backend/modules/device/repository.py +++ b/backend/modules/device/repository.py @@ -1,5 +1,4 @@ from config.database import get_connection, release_connection -from modules.monitor_config.repository import insert_default_monitor_config_db def _row_to_dict(row): """ @@ -135,9 +134,7 @@ def find_device_by_ip(ip_address): def insert_device(data): """ - Tạo mới một thiết bị và cấu hình mặc định (MonitorConfig & AlertConfig) - trong cùng một database transaction. - Trả về: tuple (device_dict, monitor_config_dict) + Tạo mới một thiết bị mạng (chỉ ghi nhận vào bảng device). """ conn = get_connection() cur = None @@ -165,23 +162,7 @@ def insert_device(data): device_row = cur.fetchone() device_id = device_row[0] - # 2. Thêm cấu hình giám sát mặc định (MonitorConfig) bằng repository chuyên biệt - monitor_config = insert_default_monitor_config_db(device_id, cursor=cur) - - # 3. Thêm cấu hình cảnh báo mặc định (AlertConfig) cho thiết bị vừa tạo - 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) - """, ( - device_id, - True, # is_enabled - 3, # fail_threshold (số lần fail liên tiếp trước khi alert) - 30, # cooldown_minutes (thời gian tránh spam alert) - True, # notify_web (hiển thị thông báo trên web) - False # notify_email (mặc định tắt gửi email) - )) - - # 4. Lấy lại thiết bị kèm thông tin DeviceType đã JOIN để trả về đầy đủ dữ liệu + # 2. Lấy lại thiết bị kèm thông tin DeviceType đã JOIN để trả về đầy đủ dữ liệu cur.execute(""" SELECT d.id, d.device_type_id, d.name, d.description, d.ip_address, d.port, @@ -193,10 +174,10 @@ def insert_device(data): """, (device_id,)) full_row = cur.fetchone() - # Commit toàn bộ transaction + # Commit transaction conn.commit() - return _row_to_dict(full_row), monitor_config + return _row_to_dict(full_row) except Exception: conn.rollback() diff --git a/backend/modules/device/service.py b/backend/modules/device/service.py index 953ac79..81ac491 100644 --- a/backend/modules/device/service.py +++ b/backend/modules/device/service.py @@ -19,6 +19,8 @@ from scheduler.scheduler import ( remove_device_monitoring_job, reschedule_device_monitoring_job ) +from modules.monitor_config.service import create_default_monitor_config_service +from modules.alert.service import create_default_alert_config_service def get_devices_service(): @@ -62,11 +64,16 @@ def create_device_service(data): if existing_ip: raise DeviceIPAlreadyExistsException(data["ip_address"]) - # 4. Insert DB (trả về thiết bị và cấu hình giám sát mặc định vừa tạo) - new_device, monitor_config = insert_device(data) + # 4. Insert DB (Chỉ lưu vào bảng device) + new_device = insert_device(data) - # 5. Kích hoạt Job giám sát trên Background Scheduler - # Truyền kèm cấu hình giám sát mặc định thay vì None để Scheduler lập lịch + # 5. Tạo cấu hình giám sát mặc định (thuộc module monitor_config) + monitor_config = create_default_monitor_config_service(new_device["id"]) + + # 6. Tạo cấu hình cảnh báo mặc định (thuộc module alert) + create_default_alert_config_service(new_device["id"]) + + # 7. Kích hoạt Job giám sát trên Background Scheduler add_device_monitoring_job(new_device["id"], monitor_config) return new_device