rairo commited on
Commit
8f3deea
·
verified ·
1 Parent(s): aea75ce

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +18 -11
main.py CHANGED
@@ -289,12 +289,12 @@ def validate_and_save_transaction(uid, user_data, data, file_hash, image_bytes,
289
  @app.route('/api/user/spending-overview', methods=['GET'])
290
  def get_spending_overview():
291
  try:
292
- # Get UID from auth token.
293
  auth_header = request.headers.get('Authorization', '')
294
  token = auth_header.split(' ')[1] if len(auth_header.split(' ')) > 1 else ''
295
  uid = verify_token(token)
296
 
297
- # Get transactions for this user.
298
  transactions_ref = db.reference('transactions')
299
  transactions = transactions_ref.order_by_child('uid').equal_to(uid).get()
300
 
@@ -304,7 +304,7 @@ def get_spending_overview():
304
  'recent_transactions': []
305
  })
306
 
307
- # Create DataFrame from the transactions.
308
  df = pd.DataFrame.from_dict(transactions, orient='index')
309
  if df.empty:
310
  return jsonify({
@@ -312,7 +312,7 @@ def get_spending_overview():
312
  'recent_transactions': []
313
  })
314
 
315
- # Drop rows missing essential fields (image_url is optional).
316
  df.dropna(subset=['uid', 'total', 'items', 'date', 'receipt_number', 'timestamp', 'hash', 'manual_entry'], inplace=True)
317
  if df.empty:
318
  return jsonify({
@@ -320,7 +320,7 @@ def get_spending_overview():
320
  'recent_transactions': []
321
  })
322
 
323
- # Parse the date column without a fixed format (allows "Fri, 12 Jun 2020 00:00:00 GMT").
324
  df['date'] = pd.to_datetime(df['date'], errors='coerce')
325
  df.dropna(subset=['date'], inplace=True)
326
  if df.empty:
@@ -329,24 +329,31 @@ def get_spending_overview():
329
  'recent_transactions': []
330
  })
331
 
332
- # Calculate daily spending.
333
- daily_spending = df.groupby(df['date'].dt.date)['total'].sum().reset_index()
334
- # Replace any NaN with None.
 
 
 
 
 
 
 
335
  daily_spending = daily_spending.replace({np.nan: None})
336
 
337
- # Get the 10 most recent transactions.
338
  recent_transactions = df.sort_values(by='timestamp', ascending=False).head(10)
339
- # Replace any NaN values (e.g. for image_url) with None.
340
  recent_transactions = recent_transactions.replace({np.nan: None})
341
 
342
  return jsonify({
343
  'daily_spending': daily_spending.to_dict(orient='records'),
344
- 'recent_transactions': recent_transactions.to_dict(orient='records')
345
  })
346
  except Exception as e:
347
  return jsonify({'error': str(e)}), 500
348
 
349
 
 
350
  # ========================================
351
  # Modified verify_admin function (now checks database is_admin flag)
352
  # ========================================
 
289
  @app.route('/api/user/spending-overview', methods=['GET'])
290
  def get_spending_overview():
291
  try:
292
+ # Extract the token and verify it.
293
  auth_header = request.headers.get('Authorization', '')
294
  token = auth_header.split(' ')[1] if len(auth_header.split(' ')) > 1 else ''
295
  uid = verify_token(token)
296
 
297
+ # Get transactions for the user.
298
  transactions_ref = db.reference('transactions')
299
  transactions = transactions_ref.order_by_child('uid').equal_to(uid).get()
300
 
 
304
  'recent_transactions': []
305
  })
306
 
307
+ # Create a DataFrame from the transactions.
308
  df = pd.DataFrame.from_dict(transactions, orient='index')
309
  if df.empty:
310
  return jsonify({
 
312
  'recent_transactions': []
313
  })
314
 
315
+ # Drop rows missing essential fields.
316
  df.dropna(subset=['uid', 'total', 'items', 'date', 'receipt_number', 'timestamp', 'hash', 'manual_entry'], inplace=True)
317
  if df.empty:
318
  return jsonify({
 
320
  'recent_transactions': []
321
  })
322
 
323
+ # Parse the date column without a fixed format and drop invalid dates.
324
  df['date'] = pd.to_datetime(df['date'], errors='coerce')
325
  df.dropna(subset=['date'], inplace=True)
326
  if df.empty:
 
329
  'recent_transactions': []
330
  })
331
 
332
+ # Convert the date column to ISO formatted strings (e.g. "2025-01-02T00:00:00").
333
+ df['date'] = df['date'].apply(lambda d: d.isoformat())
334
+
335
+ # For daily spending, group by just the date part (YYYY-MM-DD).
336
+ # Extract the date part from the ISO string.
337
+ df['date_only'] = df['date'].apply(lambda d: d.split("T")[0])
338
+ daily_spending = df.groupby('date_only')['total'].sum().reset_index()
339
+ # Rename the column to "date" and ensure it's a string.
340
+ daily_spending.rename(columns={'date_only': 'date'}, inplace=True)
341
+ daily_spending['date'] = daily_spending['date'].astype(str)
342
  daily_spending = daily_spending.replace({np.nan: None})
343
 
344
+ # Sort the transactions by timestamp (assuming it's in a sortable string format).
345
  recent_transactions = df.sort_values(by='timestamp', ascending=False).head(10)
 
346
  recent_transactions = recent_transactions.replace({np.nan: None})
347
 
348
  return jsonify({
349
  'daily_spending': daily_spending.to_dict(orient='records'),
350
+ 'recent_transactions': recent_transactions.drop(columns=['date_only']).to_dict(orient='records')
351
  })
352
  except Exception as e:
353
  return jsonify({'error': str(e)}), 500
354
 
355
 
356
+
357
  # ========================================
358
  # Modified verify_admin function (now checks database is_admin flag)
359
  # ========================================