44from datetime import datetime , timedelta
55
66
7-
8- def _get_percentage_change (value : Union [int , float ], prev_value : Union [int , float ]) -> float :
7+ def _get_percentage_change (
8+ value : Union [int , float ], prev_value : Union [int , float ]
9+ ) -> float :
910 percentage_change = (
1011 round (((value - prev_value ) / prev_value ) * 100 , 2 )
1112 if prev_value != 0
12- else 0
13+ else 0.0
1314 if value == 0
14- else
15- float ("inf" )
15+ else float ("inf" )
1616 )
1717 return percentage_change
1818
19+
1920class Customer (rx .Model , table = True ):
2021 """The customer model."""
2122
@@ -36,7 +37,6 @@ class MonthValues(rx.Base):
3637 num_delivers : int = 0
3738
3839
39-
4040class State (rx .State ):
4141 """The app state."""
4242
@@ -49,77 +49,96 @@ class State(rx.State):
4949 current_month_values : MonthValues = MonthValues ()
5050 previous_month_values : MonthValues = MonthValues ()
5151
52-
5352 def load_entries (self ) -> list [Customer ]:
54- """Get all users from the database."""
55- with rx .session () as session :
56- query = select (Customer )
57- if self .search_value :
58- search_value = f"%{ str (self .search_value ).lower ()} %"
59- query = query .where (
60- or_ (
61- * [
62- getattr (Customer , field ).ilike (search_value )
63- for field in Customer .get_fields ()
64- if field not in ["id" , "payments" ]
65- ],
66- # ensures that payments is cast to a string before applying the ilike operator
67- cast (Customer .payments , String ).ilike (search_value )
68- )
53+ """Get all users from the database."""
54+ with rx .session () as session :
55+ query = select (Customer )
56+ if self .search_value :
57+ search_value = f"%{ str (self .search_value ).lower ()} %"
58+ query = query .where (
59+ or_ (
60+ * [
61+ getattr (Customer , field ).ilike (search_value )
62+ for field in Customer .get_fields ()
63+ if field not in ["id" , "payments" ]
64+ ],
65+ # ensures that payments is cast to a string before applying the ilike operator
66+ cast (Customer .payments , String ).ilike (search_value ),
6967 )
68+ )
69+
70+ if self .sort_value :
71+ sort_column = getattr (Customer , self .sort_value )
72+ if self .sort_value == "payments" :
73+ order = desc (sort_column ) if self .sort_reverse else asc (sort_column )
74+ else :
75+ order = (
76+ desc (func .lower (sort_column ))
77+ if self .sort_reverse
78+ else asc (func .lower (sort_column ))
79+ )
80+ query = query .order_by (order )
7081
71- if self .sort_value :
72- sort_column = getattr (Customer , self .sort_value )
73- if self .sort_value == "payments" :
74- order = desc (sort_column ) if self .sort_reverse else asc (sort_column )
75- else :
76- order = desc (func .lower (sort_column )) if self .sort_reverse else asc (func .lower (sort_column ))
77- query = query .order_by (order )
78-
79- self .users = session .exec (query ).all ()
80-
81- self .get_current_month_values ()
82- self .get_previous_month_values ()
82+ self .users = session .exec (query ).all ()
8383
84+ self .get_current_month_values ()
85+ self .get_previous_month_values ()
8486
8587 def get_current_month_values (self ):
8688 """Calculate current month's values."""
8789 now = datetime .now ()
8890 start_of_month = datetime (now .year , now .month , 1 )
89-
91+
9092 current_month_users = [
91- user for user in self .users if datetime .strptime (user .date , '%Y-%m-%d %H:%M:%S' ) >= start_of_month
93+ user
94+ for user in self .users
95+ if datetime .strptime (user .date , "%Y-%m-%d %H:%M:%S" ) >= start_of_month
9296 ]
9397 num_customers = len (current_month_users )
9498 total_payments = sum (user .payments for user in current_month_users )
95- num_delivers = len ([user for user in current_month_users if user .status == "Delivered" ])
96- self .current_month_values = MonthValues (num_customers = num_customers , total_payments = total_payments , num_delivers = num_delivers )
97-
99+ num_delivers = len (
100+ [user for user in current_month_users if user .status == "Delivered" ]
101+ )
102+ self .current_month_values = MonthValues (
103+ num_customers = num_customers ,
104+ total_payments = total_payments ,
105+ num_delivers = num_delivers ,
106+ )
98107
99108 def get_previous_month_values (self ):
100109 """Calculate previous month's values."""
101110 now = datetime .now ()
102111 first_day_of_current_month = datetime (now .year , now .month , 1 )
103112 last_day_of_last_month = first_day_of_current_month - timedelta (days = 1 )
104- start_of_last_month = datetime (last_day_of_last_month .year , last_day_of_last_month .month , 1 )
105-
113+ start_of_last_month = datetime (
114+ last_day_of_last_month .year , last_day_of_last_month .month , 1
115+ )
116+
106117 previous_month_users = [
107- user for user in self .users
108- if start_of_last_month <= datetime .strptime (user .date , '%Y-%m-%d %H:%M:%S' ) <= last_day_of_last_month
118+ user
119+ for user in self .users
120+ if start_of_last_month
121+ <= datetime .strptime (user .date , "%Y-%m-%d %H:%M:%S" )
122+ <= last_day_of_last_month
109123 ]
110124 # We add some dummy values to simulate growth/decline. Remove them in production.
111125 num_customers = len (previous_month_users ) + 3
112126 total_payments = sum (user .payments for user in previous_month_users ) + 240
113- num_delivers = len ([user for user in previous_month_users if user .status == "Delivered" ]) + 5
114-
115- self .previous_month_values = MonthValues (num_customers = num_customers , total_payments = total_payments , num_delivers = num_delivers )
127+ num_delivers = (
128+ len ([user for user in previous_month_users if user .status == "Delivered" ])
129+ + 5
130+ )
116131
132+ self .previous_month_values = MonthValues (
133+ num_customers = num_customers ,
134+ total_payments = total_payments ,
135+ num_delivers = num_delivers ,
136+ )
117137
118138 def sort_values (self , sort_value : str ):
119139 self .sort_value = sort_value
120140 self .load_entries ()
121141
122-
123142 def toggle_sort (self ):
124143 self .sort_reverse = not self .sort_reverse
125144 self .load_entries ()
@@ -131,7 +150,6 @@ def filter_values(self, search_value):
131150 def get_user (self , user : Customer ):
132151 self .current_user = user
133152
134-
135153 def add_customer_to_db (self , form_data : dict ):
136154 self .current_user = form_data
137155 self .current_user ["date" ] = datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
@@ -144,8 +162,9 @@ def add_customer_to_db(self, form_data: dict):
144162 session .add (Customer (** self .current_user ))
145163 session .commit ()
146164 self .load_entries ()
147- return rx .toast .info (f"User { self .current_user ['name' ]} has been added." , position = "bottom-right" )
148-
165+ return rx .toast .info (
166+ f"User { self .current_user ['name' ]} has been added." , position = "bottom-right"
167+ )
149168
150169 def update_customer_to_db (self , form_data : dict ):
151170 self .current_user .update (form_data )
@@ -159,8 +178,10 @@ def update_customer_to_db(self, form_data: dict):
159178 session .add (customer )
160179 session .commit ()
161180 self .load_entries ()
162- return rx .toast .info (f"User { self .current_user ['name' ]} has been modified." , position = "bottom-right" )
163-
181+ return rx .toast .info (
182+ f"User { self .current_user ['name' ]} has been modified." ,
183+ position = "bottom-right" ,
184+ )
164185
165186 def delete_customer (self , id : int ):
166187 """Delete a customer from the database."""
@@ -169,17 +190,27 @@ def delete_customer(self, id: int):
169190 session .delete (customer )
170191 session .commit ()
171192 self .load_entries ()
172- return rx .toast .info (f"User { customer .name } has been deleted." , position = "bottom-right" )
173-
174-
193+ return rx .toast .info (
194+ f"User { customer .name } has been deleted." , position = "bottom-right"
195+ )
196+
175197 @rx .var (cache = True )
176198 def payments_change (self ) -> float :
177- return _get_percentage_change (self .current_month_values .total_payments , self .previous_month_values .total_payments )
199+ return _get_percentage_change (
200+ self .current_month_values .total_payments ,
201+ self .previous_month_values .total_payments ,
202+ )
178203
179204 @rx .var (cache = True )
180205 def customers_change (self ) -> float :
181- return _get_percentage_change (self .current_month_values .num_customers , self .previous_month_values .num_customers )
206+ return _get_percentage_change (
207+ self .current_month_values .num_customers ,
208+ self .previous_month_values .num_customers ,
209+ )
182210
183211 @rx .var (cache = True )
184212 def delivers_change (self ) -> float :
185- return _get_percentage_change (self .current_month_values .num_delivers , self .previous_month_values .num_delivers )
213+ return _get_percentage_change (
214+ self .current_month_values .num_delivers ,
215+ self .previous_month_values .num_delivers ,
216+ )
0 commit comments