Files
daily-counter/app/queries/monthly_stats.py
John Ahlroos bd9ff7191a
Some checks failed
Run Tests / run-tests (push) Failing after 58s
Add user specific profiles
2026-04-28 21:04:52 +02:00

84 lines
3.0 KiB
Python

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