73 lines
2.5 KiB
Python
73 lines
2.5 KiB
Python
import logging
|
|
from queries.connection import connection
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def get_all_yearly_analytics(end_date:str = 'now'):
|
|
try:
|
|
return connection().query('''
|
|
WITH RECURSIVE timeseries(d) AS (
|
|
VALUES(date(:end_date,'start of year', '-4 years'))
|
|
UNION ALL
|
|
SELECT date(d, '+1 year') as d
|
|
FROM timeseries
|
|
WHERE d < date(:end_date, '-1 year')
|
|
),
|
|
years AS (
|
|
SELECT strftime('%Y',d) as y
|
|
FROM timeseries
|
|
),
|
|
stats AS (
|
|
SELECT
|
|
strftime('%Y', timestamp) as y,
|
|
counter_id,
|
|
sum(increment) as count
|
|
FROM entries
|
|
group by counter_id, strftime('%Y', timestamp)
|
|
)
|
|
select
|
|
y.y as "year",
|
|
case
|
|
when counter_id is null then json_object()
|
|
else json_group_object(name, count)
|
|
end as counters
|
|
FROM years y
|
|
left outer join stats t on y.y = t.y
|
|
left join counters c on t.counter_id = c.id
|
|
GROUP by y.y
|
|
''', params={"end_date": end_date}, ttl=0)
|
|
except Exception as e:
|
|
logger.error(e)
|
|
return None
|
|
|
|
def get_yearly_analytics(counter_id:int, end_date:str = 'now'):
|
|
try:
|
|
return connection().query('''
|
|
WITH RECURSIVE timeseries(d) AS (
|
|
VALUES( date(:end_date, 'start of year', '-4 years'))
|
|
UNION ALL
|
|
SELECT date(d, '+1 year')
|
|
FROM timeseries
|
|
WHERE d < date(:end_date, '-1 year')
|
|
),
|
|
years AS (
|
|
SELECT strftime('%Y',d) as y
|
|
FROM timeseries
|
|
),
|
|
stats AS (
|
|
SELECT
|
|
strftime('%Y', timestamp) as y,
|
|
sum(increment) as count
|
|
FROM entries
|
|
where counter_id = :id
|
|
group by strftime('%Y', timestamp)
|
|
)
|
|
SELECT
|
|
m.y as "year",
|
|
coalesce(s.count, 0) as count
|
|
FROM years as m
|
|
LEFT JOIN stats as s on s.y = m.y
|
|
''', params={'id': counter_id, "end_date": end_date}, ttl=0)
|
|
except Exception as e:
|
|
logger.error(e)
|
|
return None |