-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchart_data.py
More file actions
358 lines (298 loc) · 12.3 KB
/
chart_data.py
File metadata and controls
358 lines (298 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
"""
Generate chart data (x and y arrays) for user analytics.
Prepares data for API responses to frontend for chart visualization.
"""
from database import SplitDataDB
from datetime import datetime, timedelta
from typing import Dict, List, Optional
import json
class ChartDataGenerator:
"""Generate chart-ready data for user analytics."""
def __init__(self, db: SplitDataDB):
"""
Initialize with database connection.
Args:
db: SplitDataDB instance
"""
self.db = db
def get_user_weekly_expenses(self, user_id: int, weeks: int = 12) -> Dict:
"""
Get user's weekly expense data (total amount per week).
Args:
user_id: User ID
weeks: Number of weeks to look back (default: 12)
Returns:
Dict with 'x' (week labels) and 'y' (amounts) arrays
"""
query = """
SELECT
YEAR(s.created_dt) as year_val,
WEEK(s.created_dt, 1) as week_val,
SUM(ABS(s.amount)) as total_amount
FROM split s
WHERE s.user_id = %s
AND s.created_dt >= DATE_SUB(NOW(), INTERVAL %s WEEK)
GROUP BY YEAR(s.created_dt), WEEK(s.created_dt, 1)
ORDER BY YEAR(s.created_dt) ASC, WEEK(s.created_dt, 1) ASC
"""
results = self.db.execute_query(query, (user_id, weeks))
x_labels = []
y_amounts = []
for row in results:
week_label = f"{row['year_val']}-W{str(row['week_val']).zfill(2)}"
x_labels.append(week_label)
y_amounts.append(float(row['total_amount']))
return {
'x': x_labels,
'y': y_amounts,
'label': f'Weekly Expenses (Last {weeks} weeks)',
'user_id': user_id
}
def get_user_monthly_expenses(self, user_id: int, months: int = 12,
year: Optional[int] = None, month: Optional[int] = None) -> Dict:
"""
Get user's monthly expense data (total amount per month).
Args:
user_id: User ID
months: Number of months to look back (default: 12, ignored if year/month specified)
year: Specific year to query (e.g., 2025)
month: Specific month to query (1-12, e.g., 1 for January)
Returns:
Dict with 'x' (month labels) and 'y' (amounts) arrays
"""
if year is not None and month is not None:
# Query specific month
query = """
SELECT
YEAR(s.created_dt) as year_val,
MONTH(s.created_dt) as month_val,
SUM(ABS(s.amount)) as total_amount
FROM split s
WHERE s.user_id = %s
AND YEAR(s.created_dt) = %s
AND MONTH(s.created_dt) = %s
GROUP BY YEAR(s.created_dt), MONTH(s.created_dt)
ORDER BY YEAR(s.created_dt) ASC, MONTH(s.created_dt) ASC
"""
results = self.db.execute_query(query, (user_id, year, month))
label = f'Monthly Expenses ({year}-{str(month).zfill(2)})'
else:
# Query last N months (original behavior)
query = """
SELECT
YEAR(s.created_dt) as year_val,
MONTH(s.created_dt) as month_val,
SUM(ABS(s.amount)) as total_amount
FROM split s
WHERE s.user_id = %s
AND s.created_dt >= DATE_SUB(NOW(), INTERVAL %s MONTH)
GROUP BY YEAR(s.created_dt), MONTH(s.created_dt)
ORDER BY YEAR(s.created_dt) ASC, MONTH(s.created_dt) ASC
"""
results = self.db.execute_query(query, (user_id, months))
label = f'Monthly Expenses (Last {months} months)'
x_labels = []
y_amounts = []
for row in results:
month_label = f"{row['year_val']}-{str(row['month_val']).zfill(2)}"
x_labels.append(month_label)
y_amounts.append(float(row['total_amount']))
return {
'x': x_labels,
'y': y_amounts,
'label': label,
'user_id': user_id
}
def get_user_paid_vs_owed(self, user_id: int) -> Dict:
"""
Get user's total paid vs total owed amounts.
Args:
user_id: User ID
Returns:
Dict with paid and owed amounts, plus breakdown by category
"""
query = """
SELECT
SUM(CASE WHEN s.amount > 0 THEN s.amount ELSE 0 END) as total_paid,
SUM(CASE WHEN s.amount < 0 THEN ABS(s.amount) ELSE 0 END) as total_owed,
SUM(s.amount) as net_balance
FROM split s
WHERE s.user_id = %s
"""
results = self.db.execute_query(query, (user_id,))
if results:
row = results[0]
return {
'paid': float(row['total_paid'] or 0),
'owed': float(row['total_owed'] or 0),
'net_balance': float(row['net_balance'] or 0),
'user_id': user_id
}
return {
'paid': 0.0,
'owed': 0.0,
'net_balance': 0.0,
'user_id': user_id
}
def get_user_expenses_by_category(self, user_id: int, months: int = 12) -> Dict:
"""
Get user's expenses grouped by category/tag.
Args:
user_id: User ID
months: Number of months to look back (default: 12)
Returns:
Dict with 'x' (categories) and 'y' (amounts) arrays
"""
query = """
SELECT
COALESCE(e.tag, 'other') as category,
SUM(ABS(s.amount)) as total_amount
FROM split s
JOIN expense e ON s.expense_id = e.id
WHERE s.user_id = %s
AND s.created_dt >= DATE_SUB(NOW(), INTERVAL %s MONTH)
GROUP BY category
ORDER BY total_amount DESC
"""
results = self.db.execute_query(query, (user_id, months))
x_categories = []
y_amounts = []
for row in results:
x_categories.append(row['category'])
y_amounts.append(float(row['total_amount']))
return {
'x': x_categories,
'y': y_amounts,
'label': f'Expenses by Category (Last {months} months)',
'user_id': user_id
}
def get_user_settlement_status(self, user_id: int) -> Dict:
"""
Get user's settlement status breakdown.
Args:
user_id: User ID
Returns:
Dict with paid, unpaid, and pending amounts
"""
query = """
SELECT
SUM(CASE WHEN s.amount > 0 THEN s.amount ELSE 0 END) as total_paid,
SUM(CASE WHEN s.amount < 0 AND s.paid_or_not = TRUE THEN ABS(s.amount) ELSE 0 END) as paid_debt,
SUM(CASE WHEN s.amount < 0 AND s.paid_or_not = FALSE THEN ABS(s.amount) ELSE 0 END) as unpaid_debt,
SUM(CASE WHEN s.amount < 0 AND s.paid_or_not IS NULL THEN ABS(s.amount) ELSE 0 END) as pending_debt
FROM split s
WHERE s.user_id = %s
"""
results = self.db.execute_query(query, (user_id,))
if results:
row = results[0]
return {
'paid': float(row['total_paid'] or 0),
'paid_debt': float(row['paid_debt'] or 0),
'unpaid_debt': float(row['unpaid_debt'] or 0),
'pending_debt': float(row['pending_debt'] or 0),
'user_id': user_id
}
return {
'paid': 0.0,
'paid_debt': 0.0,
'unpaid_debt': 0.0,
'pending_debt': 0.0,
'user_id': user_id
}
def get_user_all_chart_data(self, user_id: int, weeks: int = 12, months: int = 12) -> Dict:
"""
Get all chart data for a user in one call.
Perfect for API responses.
Args:
user_id: User ID
weeks: Number of weeks for weekly data (default: 12)
months: Number of months for monthly data (default: 12)
Returns:
Dict containing all chart data ready for JSON serialization
"""
return {
'user_id': user_id,
'weekly_expenses': self.get_user_weekly_expenses(user_id, weeks),
'monthly_expenses': self.get_user_monthly_expenses(user_id, months),
'paid_vs_owed': self.get_user_paid_vs_owed(user_id),
'expenses_by_category': self.get_user_expenses_by_category(user_id, months),
'settlement_status': self.get_user_settlement_status(user_id),
'generated_at': datetime.now().isoformat()
}
def get_user_chart_data_json(self, user_id: int, weeks: int = 12, months: int = 12) -> str:
"""
Get all chart data as JSON string (ready for API response).
Args:
user_id: User ID
weeks: Number of weeks for weekly data (default: 12)
months: Number of months for monthly data (default: 12)
Returns:
JSON string ready to send to frontend
"""
data = self.get_user_all_chart_data(user_id, weeks, months)
return json.dumps(data, indent=2, default=str)
def main():
"""Example usage and testing."""
db = SplitDataDB()
try:
if not db.connect():
print("Failed to connect to database")
return
generator = ChartDataGenerator(db)
# Test with user_id = 1
user_id = 1
print("="*60)
print(f"CHART DATA FOR USER {user_id}")
print("="*60)
# Weekly expenses
print("\n1. Weekly Expenses:")
print("-" * 60)
weekly_data = generator.get_user_weekly_expenses(user_id, weeks=12)
print(f"X-axis (Weeks): {weekly_data['x'][:5]}...") # Show first 5
print(f"Y-axis (Amounts): {weekly_data['y'][:5]}...") # Show first 5
print(f"Total data points: {len(weekly_data['x'])}")
# Monthly expenses
print("\n2. Monthly Expenses:")
print("-" * 60)
monthly_data = generator.get_user_monthly_expenses(user_id, months=12)
print(f"X-axis (Months): {monthly_data['x']}")
print(f"Y-axis (Amounts): {monthly_data['y']}")
# Paid vs Owed
print("\n3. Paid vs Owed:")
print("-" * 60)
paid_owed = generator.get_user_paid_vs_owed(user_id)
print(f"Total Paid: ${paid_owed['paid']:.2f}")
print(f"Total Owed: ${paid_owed['owed']:.2f}")
print(f"Net Balance: ${paid_owed['net_balance']:.2f}")
# Expenses by category
print("\n4. Expenses by Category:")
print("-" * 60)
category_data = generator.get_user_expenses_by_category(user_id, months=12)
print(f"X-axis (Categories): {category_data['x']}")
print(f"Y-axis (Amounts): {category_data['y']}")
# Settlement status
print("\n5. Settlement Status:")
print("-" * 60)
settlement = generator.get_user_settlement_status(user_id)
print(f"Paid: ${settlement['paid']:.2f}")
print(f"Paid Debt: ${settlement['paid_debt']:.2f}")
print(f"Unpaid Debt: ${settlement['unpaid_debt']:.2f}")
print(f"Pending Debt: ${settlement['pending_debt']:.2f}")
# All data as JSON (API-ready)
print("\n6. All Data as JSON (API-ready):")
print("-" * 60)
json_data = generator.get_user_chart_data_json(user_id, weeks=12, months=12)
print(json_data[:500] + "...") # Show first 500 chars
# Save to file for testing
with open(f'user_{user_id}_chart_data.json', 'w') as f:
f.write(json_data)
print(f"\n✓ Saved full JSON to user_{user_id}_chart_data.json")
except Exception as e:
print(f"Error: {e}")
import traceback
traceback.print_exc()
finally:
db.disconnect()
if __name__ == "__main__":
main()