This commit is contained in:
@@ -29,7 +29,10 @@ if "counter_id" in st.query_params.keys():
|
||||
|
||||
with st.container(horizontal_alignment="right", vertical_alignment="bottom", horizontal=True):
|
||||
st.header('Counter: ' + df['name'])
|
||||
selection = st.segmented_control("Time Range", options, selection_mode="single", required=True, default=counter_type.name, label_visibility="hidden")
|
||||
selected = counter_type.name
|
||||
if selected == CounterType.SIMPLE.name:
|
||||
selected = CounterType.DAILY.name
|
||||
selection = st.segmented_control("Time Range", options, selection_mode="single", required=True, default=selected, label_visibility="hidden")
|
||||
|
||||
match getattr(CounterType, selection):
|
||||
case CounterType.DAILY:
|
||||
|
||||
@@ -5,7 +5,7 @@ from sqlalchemy.sql import text
|
||||
from streamlit.connections import BaseConnection
|
||||
|
||||
def connection() -> BaseConnection:
|
||||
_connection = st.connection("sql", url=getenv('DATABASE_URL'))
|
||||
_connection = st.connection("sql", url=getenv('DATABASE_URL'), ttl=0, autocommit=True)
|
||||
with _connection.session as configured_session:
|
||||
configured_session.execute(text('PRAGMA foreign_keys=ON'))
|
||||
return _connection
|
||||
|
||||
@@ -7,48 +7,73 @@ from enums import CounterType
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def create_counter(title:str, counter_type:CounterType, counter_color) -> None:
|
||||
logger.info("Adding counter %s", counter_type)
|
||||
user_id = int(st.session_state.user_id)
|
||||
logger.info("Adding counter %s for user %d", counter_type, user_id)
|
||||
with connection().session as session:
|
||||
try:
|
||||
query = text('INSERT INTO counters (name, type, color) VALUES (:title, :type, :color)')
|
||||
session.execute(query, {'title': title, 'type': counter_type, 'color': counter_color})
|
||||
session.commit()
|
||||
query = text('INSERT INTO counters (user_id, name, type, color) VALUES (:user, :title, :type, :color)')
|
||||
session.execute(query, {
|
||||
'user': user_id,
|
||||
'title': title,
|
||||
'type': counter_type,
|
||||
'color': counter_color
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
session.rollback()
|
||||
|
||||
def get_counters():
|
||||
user_id = int(st.session_state.user_id)
|
||||
try:
|
||||
return connection().query('SELECT id, name, type, color FROM counters', ttl=0)
|
||||
return connection().query("""
|
||||
SELECT id, name, type, color
|
||||
FROM counters
|
||||
WHERE user_id = :user
|
||||
""", params={'user': user_id })
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return st.dataframe()
|
||||
|
||||
def increment_counter(counter_id:int) -> None:
|
||||
logger.info("Incrementing counter %s", counter_id)
|
||||
user_id = int(st.session_state.user_id)
|
||||
logger.info("Incrementing counter %d for user %d", counter_id, user_id)
|
||||
with connection().session as session:
|
||||
try:
|
||||
query = text('INSERT INTO entries (counter_id) VALUES (:id)')
|
||||
session.execute(query, {'id': counter_id})
|
||||
session.commit()
|
||||
query = text('INSERT INTO entries (counter_id, user_id) VALUES (:id, :user)')
|
||||
session.execute(query, {
|
||||
'id': counter_id,
|
||||
'user': user_id
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
session.rollback()
|
||||
|
||||
def remove_counter(counter_id:int) -> None:
|
||||
logger.info("Removing counter %s", counter_id)
|
||||
user_id = int(st.session_state.user_id)
|
||||
logger.info("Removing counter %d from user %d", counter_id, user_id)
|
||||
with connection().session as session:
|
||||
try:
|
||||
query = text('DELETE FROM counters WHERE id = :id')
|
||||
session.execute(query, {'id': counter_id})
|
||||
session.commit()
|
||||
query = text('DELETE FROM counters WHERE id = :id AND user_id = :user')
|
||||
session.execute(query, {
|
||||
'id': counter_id,
|
||||
'user': user_id
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
session.rollback()
|
||||
|
||||
def get_counter(counter_id:int):
|
||||
user_id = int(st.session_state.user_id)
|
||||
try:
|
||||
return connection().query('SELECT * FROM counters WHERE id = :id', params={'id': counter_id}, ttl=0).iloc[0]
|
||||
counters = connection().query("""
|
||||
SELECT * FROM counters
|
||||
WHERE id = :id AND user_id = :user
|
||||
""", params={ 'id': counter_id, 'user': user_id}
|
||||
)
|
||||
if counters.empty:
|
||||
return None
|
||||
|
||||
return counters.iloc[0]
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import logging
|
||||
from queries.connection import connection
|
||||
import streamlit as st
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def get_all_daily_analytics(end_date:str = 'now'):
|
||||
user_id = int(st.session_state.user_id)
|
||||
try:
|
||||
return connection().query('''
|
||||
WITH RECURSIVE timeseries(d) AS (
|
||||
@@ -19,6 +21,7 @@ def get_all_daily_analytics(end_date:str = 'now'):
|
||||
counter_id,
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
WHERE user_id = :user_id
|
||||
group by counter_id, date(timestamp)
|
||||
)
|
||||
select
|
||||
@@ -31,13 +34,14 @@ def get_all_daily_analytics(end_date:str = 'now'):
|
||||
left outer join stats t on s.d = t.d
|
||||
left join counters c on t.counter_id = c.id
|
||||
GROUP by s.d
|
||||
''', params={"end_date": end_date}, ttl=0)
|
||||
''', params={"end_date": end_date, "user_id": user_id })
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
|
||||
|
||||
def get_daily_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 (
|
||||
@@ -53,6 +57,7 @@ def get_daily_analytics(counter_id:int, end_date:str = 'now'):
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
where counter_id = :id
|
||||
and user_id = :user_id
|
||||
group by date(timestamp)
|
||||
)
|
||||
SELECT
|
||||
@@ -60,7 +65,7 @@ def get_daily_analytics(counter_id:int, end_date:str = 'now'):
|
||||
coalesce(s.count, 0) as count
|
||||
FROM timeseries as t
|
||||
LEFT JOIN stats as s on s.d = t.d
|
||||
''', params={'id': counter_id, "end_date": end_date}, ttl=0)
|
||||
''', params={'id': counter_id, "end_date": end_date, "user_id": user_id})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
@@ -1,9 +1,11 @@
|
||||
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 (
|
||||
@@ -26,6 +28,7 @@ def get_all_monthly_analytics(end_date:str = 'now'):
|
||||
counter_id,
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
WHERE user_id = :user_id
|
||||
group by counter_id, strftime('%m', timestamp), strftime('%Y', timestamp)
|
||||
)
|
||||
select
|
||||
@@ -38,12 +41,13 @@ def get_all_monthly_analytics(end_date:str = 'now'):
|
||||
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}, ttl=0)
|
||||
''', 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 (
|
||||
@@ -66,6 +70,7 @@ def get_monthly_analytics(counter_id:int, end_date:str = 'now'):
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
where counter_id = :id
|
||||
and user_id = :user_id
|
||||
group by strftime('%m', timestamp), strftime('%Y', timestamp)
|
||||
)
|
||||
SELECT
|
||||
@@ -73,7 +78,7 @@ def get_monthly_analytics(counter_id:int, end_date:str = 'now'):
|
||||
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}, ttl=0)
|
||||
''', params={'id': counter_id, "end_date": end_date, "user_id": user_id})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
67
app/queries/user.py
Normal file
67
app/queries/user.py
Normal file
@@ -0,0 +1,67 @@
|
||||
import logging
|
||||
|
||||
import streamlit as st
|
||||
from sqlalchemy.sql import text
|
||||
from streamlit.user_info import UserInfoProxy
|
||||
|
||||
from queries.connection import connection
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def find_user_by_oidc_id(oidc_user_id):
|
||||
return connection().query('SELECT * FROM users WHERE oidc_user_id = :id', params={'id': oidc_user_id})
|
||||
|
||||
|
||||
def find_user_by_email(email):
|
||||
return connection().query('SELECT * FROM users WHERE email = :email', params={'email': email})
|
||||
|
||||
|
||||
def find_default_user():
|
||||
return find_user_by_email('default')
|
||||
|
||||
|
||||
def update_default_user(email, name, oidc_user_id):
|
||||
with connection().session as session:
|
||||
try:
|
||||
query = text("UPDATE users SET email = :email, name = :name, oidc_user_id = :user_id WHERE email = 'default'")
|
||||
session.execute(query, {'email': email, 'name': name, 'user_id': oidc_user_id})
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
raise e
|
||||
|
||||
|
||||
def create_user(email, name, oidc_user_id):
|
||||
with connection().session as session:
|
||||
try:
|
||||
logger.info("Creating new user %s", email)
|
||||
query = text('INSERT INTO users (email, name, oidc_user_id) VALUES (:email, :name, :user_id)')
|
||||
session.execute(query, {'email': email, 'name': name, 'user_id': oidc_user_id})
|
||||
return connection().query('SELECT * FROM users WHERE oidc_user_id = :id', params={'id': oidc_user_id})
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
raise e
|
||||
|
||||
|
||||
def set_user_in_session(user: UserInfoProxy):
|
||||
email = user.email
|
||||
user_id = user.sub
|
||||
if hasattr(user, 'name'):
|
||||
name = user.name
|
||||
else:
|
||||
name = None
|
||||
|
||||
user_entity = find_user_by_oidc_id(user_id)
|
||||
if user_entity.empty:
|
||||
user_entity = find_user_by_email(email)
|
||||
if user_entity.empty:
|
||||
user_entity = find_default_user()
|
||||
if user_entity.empty:
|
||||
user_entity = create_user(email, name, user_id)
|
||||
else:
|
||||
update_default_user(email, name, user_id)
|
||||
user_entity = find_user_by_oidc_id(user_id)
|
||||
|
||||
st.session_state.user_id = user_entity["id"][0]
|
||||
st.session_state.user_name = user_entity["name"][0]
|
||||
st.session_state.user_email = user_entity["email"][0]
|
||||
st.session_state.user_external_id = user_entity["oidc_user_id"][0]
|
||||
@@ -1,9 +1,11 @@
|
||||
import logging
|
||||
import streamlit as st
|
||||
from queries.connection import connection
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def get_all_weekly_analytics(end_date:str = 'now'):
|
||||
user_id = int(st.session_state.user_id)
|
||||
try:
|
||||
return connection().query('''
|
||||
WITH RECURSIVE timeseries(d) AS (
|
||||
@@ -23,6 +25,7 @@ def get_all_weekly_analytics(end_date:str = 'now'):
|
||||
counter_id,
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
WHERE user_id = :user_id
|
||||
group by counter_id, strftime('%W', timestamp)
|
||||
)
|
||||
select
|
||||
@@ -35,12 +38,13 @@ def get_all_weekly_analytics(end_date:str = 'now'):
|
||||
left outer join stats t on s.w = t.w
|
||||
left join counters c on t.counter_id = c.id
|
||||
GROUP by s.w
|
||||
''', params={"end_date": end_date}, ttl=0)
|
||||
''', params={"end_date": end_date, "user_id": user_id})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
|
||||
def get_weekly_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 (
|
||||
@@ -60,6 +64,7 @@ def get_weekly_analytics(counter_id:int, end_date:str = 'now'):
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
where counter_id = :id
|
||||
and user_id = :user_id
|
||||
group by strftime('%W', timestamp)
|
||||
)
|
||||
SELECT
|
||||
@@ -67,7 +72,7 @@ def get_weekly_analytics(counter_id:int, end_date:str = 'now'):
|
||||
coalesce(s.count, 0) as count
|
||||
FROM weeks as w
|
||||
LEFT JOIN stats as s on s.w = w.w
|
||||
''', params={'id': counter_id, "end_date": end_date}, ttl=0)
|
||||
''', params={'id': counter_id, "end_date": end_date, "user_id": user_id})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
@@ -1,9 +1,11 @@
|
||||
import logging
|
||||
import streamlit as st
|
||||
from queries.connection import connection
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def get_all_yearly_analytics(end_date:str = 'now'):
|
||||
user_id = int(st.session_state.user_id)
|
||||
try:
|
||||
return connection().query('''
|
||||
WITH RECURSIVE timeseries(d) AS (
|
||||
@@ -23,6 +25,7 @@ def get_all_yearly_analytics(end_date:str = 'now'):
|
||||
counter_id,
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
WHERE user_id = :user_id
|
||||
group by counter_id, strftime('%Y', timestamp)
|
||||
)
|
||||
select
|
||||
@@ -35,12 +38,13 @@ def get_all_yearly_analytics(end_date:str = 'now'):
|
||||
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)
|
||||
''', params={"end_date": end_date, "user_id": user_id})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
|
||||
def get_yearly_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 (
|
||||
@@ -60,6 +64,7 @@ def get_yearly_analytics(counter_id:int, end_date:str = 'now'):
|
||||
sum(increment) as count
|
||||
FROM entries
|
||||
where counter_id = :id
|
||||
and user_id = :user_id
|
||||
group by strftime('%Y', timestamp)
|
||||
)
|
||||
SELECT
|
||||
@@ -67,7 +72,7 @@ def get_yearly_analytics(counter_id:int, end_date:str = 'now'):
|
||||
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)
|
||||
''', params={'id': counter_id, "end_date": end_date, "user_id":user_id})
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
return None
|
||||
@@ -1,21 +1,37 @@
|
||||
import streamlit as st
|
||||
import logging
|
||||
from streamlit import dialog
|
||||
import queries.user as user_queries
|
||||
|
||||
from logger import init_logger
|
||||
from styles import init_styles
|
||||
|
||||
init_logger()
|
||||
init_styles()
|
||||
|
||||
if hasattr(st, 'user') and hasattr(st.user, 'is_logged_in'):
|
||||
if not st.user.is_logged_in:
|
||||
with st.container(width="stretch", height="stretch", horizontal_alignment="center"):
|
||||
st.title("Daily Counter", width="stretch", text_alignment="center")
|
||||
st.text("Please log in to use this app", width="stretch", text_alignment="center")
|
||||
st.space()
|
||||
if st.button("Log in"):
|
||||
st.login()
|
||||
is_login_enabled = hasattr(st, 'user')
|
||||
is_logged_in = is_login_enabled and hasattr(st.user, 'is_logged_in') and st.user.is_logged_in
|
||||
|
||||
if is_logged_in:
|
||||
user_queries.set_user_in_session(st.user)
|
||||
else:
|
||||
st.session_state.user_id = 1 # default user
|
||||
|
||||
if is_login_enabled and not is_logged_in:
|
||||
with st.container(width="stretch", height="stretch", horizontal_alignment="center"):
|
||||
st.title("Daily Counter", width="stretch", text_alignment="center")
|
||||
st.text("Please log in to use this app", width="stretch", text_alignment="center")
|
||||
st.space()
|
||||
if st.button("Log in"):
|
||||
st.login()
|
||||
|
||||
else:
|
||||
counters = st.Page("pages/counters.py", title="Counters", icon=":material/update:")
|
||||
stats = st.Page("pages/stats.py", title="Statistics", icon=":material/chart_data:")
|
||||
pg = st.navigation(position="top", pages=[counters, stats])
|
||||
pg.run()
|
||||
logoutPage = st.Page(st.logout, title="Logout", icon=":material/logout:")
|
||||
|
||||
pages = [counters, stats]
|
||||
if is_login_enabled:
|
||||
pages = pages + [logoutPage]
|
||||
|
||||
pg = st.navigation(position="top", pages=pages)
|
||||
pg.run()
|
||||
|
||||
Reference in New Issue
Block a user