36 lines
1.4 KiB
Python
36 lines
1.4 KiB
Python
|
|
from datetime import date, timedelta
|
||
|
|
|
||
|
|
from dashboard_data.card_utils import PERSIAN_WEEKDAYS, safe_number
|
||
|
|
|
||
|
|
|
||
|
|
def build_sensor_comparison_chart(sensor_id: str, context: dict | None = None, ai_bundle: dict | None = None) -> dict:
|
||
|
|
history = (context or {}).get("history", [])
|
||
|
|
current_sensor = (context or {}).get("sensor")
|
||
|
|
current_value = round(safe_number(getattr(current_sensor, "soil_moisture", None), 0))
|
||
|
|
|
||
|
|
recent = list(reversed(history[:7]))
|
||
|
|
previous = list(reversed(history[7:14]))
|
||
|
|
this_week = [round(safe_number(item.soil_moisture, current_value)) for item in recent]
|
||
|
|
last_week = [round(safe_number(item.soil_moisture, current_value - 5)) for item in previous]
|
||
|
|
|
||
|
|
while len(this_week) < 7:
|
||
|
|
this_week.append(current_value)
|
||
|
|
while len(last_week) < 7:
|
||
|
|
last_week.append(max(0, current_value - 5))
|
||
|
|
|
||
|
|
categories = [PERSIAN_WEEKDAYS[(date.today() - timedelta(days=offset)).weekday()] for offset in range(6, -1, -1)]
|
||
|
|
avg_this = sum(this_week) / len(this_week)
|
||
|
|
avg_last = sum(last_week) / len(last_week)
|
||
|
|
delta = round(((avg_this - avg_last) / avg_last) * 100) if avg_last else 0
|
||
|
|
|
||
|
|
return {
|
||
|
|
"currentValue": current_value,
|
||
|
|
"vsLastWeek": f"{'+' if delta >= 0 else ''}{delta}%",
|
||
|
|
"vsLastWeekValue": delta,
|
||
|
|
"categories": categories,
|
||
|
|
"series": [
|
||
|
|
{"name": "امروز", "data": this_week},
|
||
|
|
{"name": "هفته قبل", "data": last_week},
|
||
|
|
],
|
||
|
|
}
|