2026-05-10 12:36:38 +02:00
|
|
|
from datetime import datetime
|
2026-05-10 13:17:58 +02:00
|
|
|
from dateutil.relativedelta import relativedelta
|
2026-05-10 12:36:38 +02:00
|
|
|
|
|
|
|
|
import psycopg2
|
|
|
|
|
from psycopg2.extensions import connection
|
|
|
|
|
|
|
|
|
|
from domain.entities import ConsumptionPoint
|
|
|
|
|
from domain.exceptions import DatabaseError
|
|
|
|
|
from domain.value_objects import Granularity
|
|
|
|
|
from ports.reading_query_repository import ReadingQueryRepository
|
|
|
|
|
|
|
|
|
|
|
2026-05-10 13:17:58 +02:00
|
|
|
_GRANULARITY_DELTA = {
|
|
|
|
|
"hour": relativedelta(hours=1),
|
|
|
|
|
"day": relativedelta(days=1),
|
|
|
|
|
"week": relativedelta(weeks=1),
|
|
|
|
|
"month": relativedelta(months=1),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2026-05-10 12:36:38 +02:00
|
|
|
class PgReadingQueryRepository(ReadingQueryRepository):
|
|
|
|
|
def __init__(self, conn: connection) -> None:
|
|
|
|
|
self._conn = conn
|
|
|
|
|
|
|
|
|
|
def get_consumption(
|
|
|
|
|
self,
|
|
|
|
|
dev_eui: str,
|
|
|
|
|
start: datetime,
|
|
|
|
|
end: datetime,
|
|
|
|
|
granularity: Granularity,
|
|
|
|
|
) -> list[ConsumptionPoint]:
|
2026-05-10 13:17:58 +02:00
|
|
|
if start == end:
|
|
|
|
|
end = start + _GRANULARITY_DELTA[granularity]
|
|
|
|
|
adjusted_start = start - _GRANULARITY_DELTA[granularity]
|
2026-05-10 12:36:38 +02:00
|
|
|
date_trunc = granularity
|
|
|
|
|
query = """
|
2026-05-10 13:17:58 +02:00
|
|
|
WITH periods AS (
|
|
|
|
|
SELECT
|
|
|
|
|
DATE_TRUNC(%s, r.date) AS period,
|
|
|
|
|
MAX(r.pulses) AS pulse_end
|
|
|
|
|
FROM reading r
|
|
|
|
|
JOIN device d ON d.device_id = r.device_id
|
|
|
|
|
WHERE d.device_eui = %s
|
|
|
|
|
AND r.date >= %s
|
|
|
|
|
AND r.date < %s
|
|
|
|
|
GROUP BY period
|
|
|
|
|
)
|
2026-05-10 12:36:38 +02:00
|
|
|
SELECT
|
2026-05-10 13:17:58 +02:00
|
|
|
period,
|
|
|
|
|
LAG(pulse_end) OVER (ORDER BY period) AS pulse_start,
|
|
|
|
|
pulse_end,
|
|
|
|
|
pulse_end - LAG(pulse_end) OVER (ORDER BY period) AS delta_pulses
|
|
|
|
|
FROM periods
|
2026-05-10 12:36:38 +02:00
|
|
|
ORDER BY period ASC
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
with self._conn.cursor() as cur:
|
2026-05-10 13:17:58 +02:00
|
|
|
cur.execute(query, (date_trunc, dev_eui, adjusted_start, end))
|
2026-05-10 12:36:38 +02:00
|
|
|
rows = cur.fetchall()
|
|
|
|
|
except psycopg2.DatabaseError as e:
|
|
|
|
|
raise DatabaseError(f"Erreur requête consumption : {e}") from e
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
ConsumptionPoint(
|
|
|
|
|
period=row[0],
|
|
|
|
|
pulse_count_start=row[1],
|
|
|
|
|
pulse_count_end=row[2],
|
|
|
|
|
delta_pulses=row[3],
|
|
|
|
|
delta_m3=round(row[3] * 0.010, 3),
|
|
|
|
|
)
|
|
|
|
|
for row in rows
|
2026-05-10 13:17:58 +02:00
|
|
|
if row[1] is not None
|
2026-05-10 12:36:38 +02:00
|
|
|
]
|