Refactor device tiles SQL logic to use get_sql_devices_tiles function for improved maintainability Feature Request - Flapping and Sleeping nuances

Fixes #1567
This commit is contained in:
Jokob @NetAlertX
2026-03-21 21:10:37 +00:00
parent 7569923481
commit fa22523a0b
3 changed files with 51 additions and 37 deletions

View File

@@ -66,6 +66,55 @@ def get_device_condition_by_status(device_status):
return get_device_conditions().get(device_status, "WHERE 1=0")
# -------------------------------------------------------------------------------
def get_sql_devices_tiles():
"""Build the device tiles count SQL using get_device_conditions() to avoid duplicating filter logic."""
conds = get_device_conditions()
def f(key):
"""Strip 'WHERE ' prefix for use inside SELECT subqueries."""
return conds[key][len("WHERE "):]
# UI_MY_DEVICES setting values mapped to their device_conditions keys
my_devices_setting_map = [
("online", "connected"),
("offline", "offline"),
("down", "down"),
("new", "new"),
("archived", "archived"),
]
my_devices_clauses = "\n OR ".join(
f"(instr((SELECT setValue FROM Statuses), '{sk}') > 0 AND {f(ck)})"
for sk, ck in my_devices_setting_map
)
return f"""
WITH Statuses AS (
SELECT setValue
FROM Settings
WHERE setKey = 'UI_MY_DEVICES'
),
MyDevicesFilter AS (
SELECT devMac
FROM Devices
WHERE
{my_devices_clauses}
)
SELECT
(SELECT COUNT(*) FROM Devices WHERE {f('connected')}) AS connected,
(SELECT COUNT(*) FROM Devices WHERE {f('offline')}) AS offline,
(SELECT COUNT(*) FROM Devices WHERE {f('down')}) AS down,
(SELECT COUNT(*) FROM Devices WHERE {f('new')}) AS new,
(SELECT COUNT(*) FROM Devices WHERE {f('archived')}) AS archived,
(SELECT COUNT(*) FROM Devices WHERE {f('favorites')}) AS favorites,
(SELECT COUNT(*) FROM Devices WHERE {f('all')}) AS "all",
(SELECT COUNT(*) FROM Devices) AS "all_devices",
(SELECT COUNT(*) FROM MyDevicesFilter) AS my_devices
FROM Statuses;
"""
# -------------------------------------------------------------------------------
# Creates a JSON-like dictionary from a database row
def row_to_json(names, row):