MJ-Prod commited on
Commit
c21f683
·
1 Parent(s): e800f23
Files changed (1) hide show
  1. plaid_client.py +95 -0
plaid_client.py CHANGED
@@ -211,6 +211,101 @@ def get_chart_data(access_token: str) -> dict:
211
  end_date = date.today()
212
  start_date = end_date - timedelta(days=30)
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  # Get transactions
215
  request = TransactionsGetRequest(
216
  access_token=access_token,
 
211
  end_date = date.today()
212
  start_date = end_date - timedelta(days=30)
213
 
214
+ # Get balances (usually ready immediately)
215
+ try:
216
+ balance_req = AccountsBalanceGetRequest(access_token=access_token)
217
+ balance_resp = plaid_client.accounts_balance_get(balance_req)
218
+ accounts = []
219
+ for account in balance_resp['accounts']:
220
+ current = account['balances']['current']
221
+ if current is None:
222
+ continue
223
+ accounts.append({
224
+ "name": account['name'],
225
+ "type": str(account['subtype']),
226
+ "balance": round(current, 2),
227
+ })
228
+ except Exception as e:
229
+ print(f"Balance error in chart_data: {e}", flush=True)
230
+ accounts = []
231
+
232
+ # Get transactions (may not be ready yet)
233
+ category_chart = []
234
+ weekly_data = []
235
+ income_total = 0.0
236
+ expense_total = 0.0
237
+
238
+ try:
239
+ request = TransactionsGetRequest(
240
+ access_token=access_token,
241
+ start_date=start_date,
242
+ end_date=end_date,
243
+ options=TransactionsGetRequestOptions(
244
+ count=200,
245
+ include_personal_finance_category=True
246
+ )
247
+ )
248
+ response = plaid_client.transactions_get(request)
249
+ transactions = response['transactions']
250
+
251
+ category_totals: dict[str, float] = {}
252
+ daily_spending: dict[str, float] = {}
253
+ daily_income: dict[str, float] = {}
254
+
255
+ for txn in transactions:
256
+ amount = txn['amount']
257
+ txn_date = str(txn['date'])
258
+ category = txn.get('personal_finance_category', {}).get('primary', 'OTHER')
259
+
260
+ if amount < 0:
261
+ income_total += abs(amount)
262
+ daily_income[txn_date] = daily_income.get(txn_date, 0) + abs(amount)
263
+ continue
264
+
265
+ if category in ['TRANSFER_IN', 'TRANSFER_OUT']:
266
+ continue
267
+
268
+ name_lower = txn['name'].lower()
269
+ if category == 'LOAN_PAYMENTS' and any(w in name_lower for w in ['payroll', 'salary', 'direct dep', 'employer', 'wages']):
270
+ income_total += amount
271
+ daily_income[txn_date] = daily_income.get(txn_date, 0) + amount
272
+ continue
273
+
274
+ expense_total += amount
275
+ readable = category.replace("_", " ").title()
276
+ category_totals[readable] = category_totals.get(readable, 0) + amount
277
+ daily_spending[txn_date] = daily_spending.get(txn_date, 0) + amount
278
+
279
+ category_chart = [
280
+ {"name": cat, "value": round(total, 2)}
281
+ for cat, total in sorted(category_totals.items(), key=lambda x: -x[1])
282
+ ]
283
+
284
+ for i in range(4):
285
+ week_end = end_date - timedelta(weeks=i)
286
+ week_start_d = week_end - timedelta(days=6)
287
+ week_label = f"{week_start_d.strftime('%b %d')} - {week_end.strftime('%b %d')}"
288
+ week_spending = sum(v for k, v in daily_spending.items() if str(week_start_d) <= k <= str(week_end))
289
+ week_income = sum(v for k, v in daily_income.items() if str(week_start_d) <= k <= str(week_end))
290
+ weekly_data.append({"week": week_label, "spending": round(week_spending, 2), "income": round(week_income, 2)})
291
+ weekly_data.reverse()
292
+
293
+ except Exception as e:
294
+ print(f"Transaction error in chart_data: {e}", flush=True)
295
+
296
+ return {
297
+ "category_chart": category_chart,
298
+ "weekly_chart": weekly_data,
299
+ "income_vs_expenses": {
300
+ "income": round(income_total, 2),
301
+ "expenses": round(expense_total, 2),
302
+ },
303
+ "accounts": accounts,
304
+ }
305
+ """Returns structured JSON for frontend charts."""
306
+ end_date = date.today()
307
+ start_date = end_date - timedelta(days=30)
308
+
309
  # Get transactions
310
  request = TransactionsGetRequest(
311
  access_token=access_token,