rairo commited on
Commit
f1d5e2e
·
verified ·
1 Parent(s): 1846197

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +23 -28
main.py CHANGED
@@ -192,7 +192,7 @@ def update_user_phone():
192
  def get_user_dashboard():
193
  """
194
  Retrieves and aggregates data for the user's dashboard with correct profit calculation.
195
- **FIXED**: Normalizes the phone number to match the bot's data document ID.
196
  """
197
  uid = verify_token(request.headers.get('Authorization'))
198
  if not uid: return jsonify({'error': 'Invalid or expired token'}), 401
@@ -208,21 +208,21 @@ def get_user_dashboard():
208
  if not phone_number: return jsonify({'error': 'No phone number is associated with your account.'}), 404
209
 
210
  try:
211
- # --- THE FIX IS HERE ---
212
- # Strip the leading '+' from the phone number to match the document ID
213
- # used by the WhatsApp bot (e.g., '+263...' becomes '263...').
214
  bot_data_id = phone_number.lstrip('+')
215
-
216
- # Use the corrected ID to reference the bot's data document
217
  bot_user_ref = db.collection('users').document(bot_data_id)
218
- # --- END OF FIX ---
219
 
 
220
  sales_docs = bot_user_ref.collection('sales').stream()
221
  total_sales_revenue, total_cogs, sales_count = 0, 0, 0
222
  for doc in sales_docs:
223
  details = doc.to_dict().get('details', {})
224
- total_sales_revenue += float(details.get('price', 0))
225
- total_cogs += float(details.get('cost', 0))
 
 
 
 
 
226
  sales_count += 1
227
 
228
  expenses_docs = bot_user_ref.collection('expenses').stream()
@@ -239,6 +239,7 @@ def get_user_dashboard():
239
  'netProfit': round(net_profit, 2),
240
  'salesCount': sales_count,
241
  }
 
242
  return jsonify(dashboard_data), 200
243
 
244
  except Exception as e:
@@ -557,12 +558,11 @@ def admin_remove_member_from_org(org_id, member_uid):
557
  # -----------------------------------------------------------------------------
558
  # 7. ADMIN DASHBOARD ENDPOINT (INCLUDED)
559
  # -----------------------------------------------------------------------------
560
-
561
  @app.route('/api/admin/dashboard/stats', methods=['GET'])
562
  def get_admin_dashboard_stats():
563
  """
564
  Retrieves global statistics for the admin dashboard with correct profit calculation.
565
- **FIXED**: Normalizes phone numbers to match bot's data document IDs.
566
  """
567
  try:
568
  verify_admin_and_get_uid(request.headers.get('Authorization'))
@@ -585,37 +585,35 @@ def get_admin_dashboard_stats():
585
  admin_count += 1
586
 
587
  user_stats = {
588
- 'total': len(all_users_docs),
589
- 'admins': admin_count,
590
- 'approvedForBot': approved_users,
591
- 'pendingApproval': pending_approvals,
592
  }
593
-
594
  org_stats = {'total': len(all_orgs_docs)}
595
 
 
596
  total_sales_revenue, total_cogs, total_expenses, sales_count = 0, 0, 0, 0
597
 
598
  for phone in approved_phone_numbers:
599
  try:
600
- # --- THE FIX IS HERE ---
601
- # Strip the leading '+' before querying for each user's bot data
602
  bot_data_id = phone.lstrip('+')
603
  bot_user_ref = db.collection('users').document(bot_data_id)
604
- # --- END OF FIX ---
605
 
606
  sales_docs = bot_user_ref.collection('sales').stream()
607
  for sale_doc in sales_docs:
608
  details = sale_doc.to_dict().get('details', {})
609
- total_sales_revenue += float(details.get('price', 0))
610
- total_cogs += float(details.get('cost', 0))
 
 
 
 
611
  sales_count += 1
612
 
613
  expenses_docs = bot_user_ref.collection('expenses').stream()
614
  total_expenses += sum(float(doc.to_dict().get('details', {}).get('amount', 0)) for doc in expenses_docs)
615
  except Exception as e:
616
- # Log an error for a specific user but continue the loop
617
  logging.error(f"Admin stats: Could not process data for phone {phone}. Error: {e}")
618
- continue # Move to the next phone number
619
 
620
  gross_profit = total_sales_revenue - total_cogs
621
  net_profit = gross_profit - total_expenses
@@ -627,12 +625,9 @@ def get_admin_dashboard_stats():
627
  'totalNetProfit': round(net_profit, 2),
628
  'totalSalesCount': sales_count,
629
  }
 
630
 
631
- return jsonify({
632
- 'userStats': user_stats,
633
- 'organizationStats': org_stats,
634
- 'systemStats': system_stats
635
- }), 200
636
 
637
  except PermissionError as e:
638
  return jsonify({'error': str(e)}), 403
 
192
  def get_user_dashboard():
193
  """
194
  Retrieves and aggregates data for the user's dashboard with correct profit calculation.
195
+ **FIXED**: Multiplies price and cost by quantity for accurate financial totals.
196
  """
197
  uid = verify_token(request.headers.get('Authorization'))
198
  if not uid: return jsonify({'error': 'Invalid or expired token'}), 401
 
208
  if not phone_number: return jsonify({'error': 'No phone number is associated with your account.'}), 404
209
 
210
  try:
 
 
 
211
  bot_data_id = phone_number.lstrip('+')
 
 
212
  bot_user_ref = db.collection('users').document(bot_data_id)
 
213
 
214
+ # --- THE FIX IS HERE ---
215
  sales_docs = bot_user_ref.collection('sales').stream()
216
  total_sales_revenue, total_cogs, sales_count = 0, 0, 0
217
  for doc in sales_docs:
218
  details = doc.to_dict().get('details', {})
219
+ # Default quantity to 1 if not present
220
+ quantity = int(details.get('quantity', 1))
221
+ price = float(details.get('price', 0))
222
+ cost = float(details.get('cost', 0))
223
+
224
+ total_sales_revenue += price * quantity
225
+ total_cogs += cost * quantity
226
  sales_count += 1
227
 
228
  expenses_docs = bot_user_ref.collection('expenses').stream()
 
239
  'netProfit': round(net_profit, 2),
240
  'salesCount': sales_count,
241
  }
242
+ # --- END OF FIX ---
243
  return jsonify(dashboard_data), 200
244
 
245
  except Exception as e:
 
558
  # -----------------------------------------------------------------------------
559
  # 7. ADMIN DASHBOARD ENDPOINT (INCLUDED)
560
  # -----------------------------------------------------------------------------
 
561
  @app.route('/api/admin/dashboard/stats', methods=['GET'])
562
  def get_admin_dashboard_stats():
563
  """
564
  Retrieves global statistics for the admin dashboard with correct profit calculation.
565
+ **FIXED**: Multiplies price and cost by quantity for accurate financial totals.
566
  """
567
  try:
568
  verify_admin_and_get_uid(request.headers.get('Authorization'))
 
585
  admin_count += 1
586
 
587
  user_stats = {
588
+ 'total': len(all_users_docs), 'admins': admin_count,
589
+ 'approvedForBot': approved_users, 'pendingApproval': pending_approvals,
 
 
590
  }
 
591
  org_stats = {'total': len(all_orgs_docs)}
592
 
593
+ # --- THE FIX IS HERE ---
594
  total_sales_revenue, total_cogs, total_expenses, sales_count = 0, 0, 0, 0
595
 
596
  for phone in approved_phone_numbers:
597
  try:
 
 
598
  bot_data_id = phone.lstrip('+')
599
  bot_user_ref = db.collection('users').document(bot_data_id)
 
600
 
601
  sales_docs = bot_user_ref.collection('sales').stream()
602
  for sale_doc in sales_docs:
603
  details = sale_doc.to_dict().get('details', {})
604
+ quantity = int(details.get('quantity', 1))
605
+ price = float(details.get('price', 0))
606
+ cost = float(details.get('cost', 0))
607
+
608
+ total_sales_revenue += price * quantity
609
+ total_cogs += cost * quantity
610
  sales_count += 1
611
 
612
  expenses_docs = bot_user_ref.collection('expenses').stream()
613
  total_expenses += sum(float(doc.to_dict().get('details', {}).get('amount', 0)) for doc in expenses_docs)
614
  except Exception as e:
 
615
  logging.error(f"Admin stats: Could not process data for phone {phone}. Error: {e}")
616
+ continue
617
 
618
  gross_profit = total_sales_revenue - total_cogs
619
  net_profit = gross_profit - total_expenses
 
625
  'totalNetProfit': round(net_profit, 2),
626
  'totalSalesCount': sales_count,
627
  }
628
+ # --- END OF FIX ---
629
 
630
+ return jsonify({'userStats': user_stats, 'organizationStats': org_stats, 'systemStats': system_stats}), 200
 
 
 
 
631
 
632
  except PermissionError as e:
633
  return jsonify({'error': str(e)}), 403