habulaj commited on
Commit
49851a0
·
verified ·
1 Parent(s): 66ac2af

Update routes/stylist.py

Browse files
Files changed (1) hide show
  1. routes/stylist.py +23 -46
routes/stylist.py CHANGED
@@ -47,8 +47,6 @@ def verify_token(user_token: str) -> str:
47
  def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
48
  ny_timezone = pytz.timezone('America/New_York')
49
  now_ny = datetime.now(ny_timezone)
50
- current_month = now_ny.month
51
- current_year = now_ny.year
52
  monthly_data = {}
53
 
54
  for i in range(6):
@@ -57,16 +55,17 @@ def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
57
  month_name = target_date.strftime('%b')
58
  year = target_date.year
59
  month_key = f"{year}-{month_num}"
60
- is_current = (month_num == current_month and year == current_year)
61
  monthly_data[month_key] = {
62
  "month": month_num,
63
  "name": month_name,
64
- "current": is_current,
65
  "amount": 0,
66
  "growth": {"status": "", "percentage": 0, "formatted": "0.0%"}
67
  }
68
- start_date = now_ny - relativedelta(months=6)
 
69
  start_timestamp = int(start_date.timestamp())
 
70
  try:
71
  transfers = stripe.Transfer.list(
72
  destination=account_id,
@@ -75,25 +74,30 @@ def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
75
  )
76
  for transfer in transfers.data:
77
  transfer_date = datetime.fromtimestamp(transfer.created, ny_timezone)
78
- month_num = transfer_date.month
79
- year = transfer_date.year
80
- month_key = f"{year}-{month_num}"
81
  if month_key in monthly_data:
82
  monthly_data[month_key]["amount"] += transfer.amount
 
83
  result = list(monthly_data.values())
84
- result.sort(key=lambda x: (current_month - x["month"]) % 12)
85
- for i in range(1, len(result)):
86
- prev_amount = result[i - 1]["amount"]
87
- current_amount = result[i]["amount"]
88
- if prev_amount > 0:
89
- growth_percentage = ((current_amount - prev_amount) / prev_amount) * 100
 
 
 
 
90
  else:
91
  growth_percentage = 100 if current_amount > 0 else 0
92
- result[i]["growth"] = {
 
93
  "status": "up" if growth_percentage > 0 else "down",
94
  "percentage": round(growth_percentage, 1),
95
  "formatted": f"{round(growth_percentage, 1)}%"
96
  }
 
97
  return result
98
  except Exception as e:
99
  logger.error(f"❌ Error getting monthly revenue: {str(e)}")
@@ -102,29 +106,16 @@ def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
102
  def get_account_balance(account_id: str) -> Dict[str, Any]:
103
  try:
104
  balance = stripe.Balance.retrieve(stripe_account=account_id)
105
- available_balance = 0
106
- pending_balance = 0
107
- currency = "BRL"
108
- for balance_item in balance.available:
109
- if balance_item.currency.upper() == "BRL":
110
- available_balance = balance_item.amount
111
- break
112
- for balance_item in balance.pending:
113
- if balance_item.currency.upper() == "BRL":
114
- pending_balance = balance_item.amount
115
- break
116
  return {
117
  "available_balance": available_balance,
118
  "pending_balance": pending_balance,
119
- "currency": currency
120
  }
121
  except Exception as e:
122
  logger.error(f"❌ Error getting account balance: {str(e)}")
123
- return {
124
- "available_balance": 0,
125
- "pending_balance": 0,
126
- "currency": "BRL"
127
- }
128
 
129
  def get_active_subscribers(user_id: str) -> List[Dict[str, Any]]:
130
  url = f"{SUPABASE_URL}/rest/v1/Subscriptions?stylist_id=eq.{user_id}&active=eq.true&limit=30"
@@ -153,24 +144,12 @@ def get_dashboard(user_token: str = Header(None, alias="User-key")):
153
  if not user_token:
154
  raise HTTPException(status_code=401, detail="Missing User-key header")
155
  user_id = verify_token(user_token)
156
- logger.info(f"🔹 User verified. user_id: {user_id}")
157
  user_data_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
158
  response = requests.get(user_data_url, headers=SUPABASE_HEADERS)
159
  if response.status_code != 200 or not response.json():
160
  raise HTTPException(status_code=404, detail="User not found")
161
  user_data = response.json()[0]
162
  stripe_id = user_data.get("stripe_id")
163
- if not stripe_id:
164
- return {
165
- "stripe_id": None,
166
- "available_balance": 0,
167
- "pending_balance": 0,
168
- "currency": "BRL",
169
- "monthly_revenue": [],
170
- "total_followers": 0,
171
- "total_subscribers": 0,
172
- "subscribers": []
173
- }
174
  return {
175
  "stripe_id": stripe_id,
176
  "available_balance": get_account_balance(stripe_id)["available_balance"],
@@ -179,8 +158,6 @@ def get_dashboard(user_token: str = Header(None, alias="User-key")):
179
  "monthly_revenue": get_monthly_revenue(stripe_id),
180
  "subscribers": get_active_subscribers(user_id)
181
  }
182
- except HTTPException as http_err:
183
- raise http_err
184
  except Exception as e:
185
  logger.error(f"❌ Error: {str(e)}")
186
  raise HTTPException(status_code=500, detail=str(e))
 
47
  def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
48
  ny_timezone = pytz.timezone('America/New_York')
49
  now_ny = datetime.now(ny_timezone)
 
 
50
  monthly_data = {}
51
 
52
  for i in range(6):
 
55
  month_name = target_date.strftime('%b')
56
  year = target_date.year
57
  month_key = f"{year}-{month_num}"
 
58
  monthly_data[month_key] = {
59
  "month": month_num,
60
  "name": month_name,
61
+ "current": (month_num == now_ny.month and year == now_ny.year),
62
  "amount": 0,
63
  "growth": {"status": "", "percentage": 0, "formatted": "0.0%"}
64
  }
65
+
66
+ start_date = now_ny - relativedelta(months=12)
67
  start_timestamp = int(start_date.timestamp())
68
+
69
  try:
70
  transfers = stripe.Transfer.list(
71
  destination=account_id,
 
74
  )
75
  for transfer in transfers.data:
76
  transfer_date = datetime.fromtimestamp(transfer.created, ny_timezone)
77
+ month_key = f"{transfer_date.year}-{transfer_date.month}"
 
 
78
  if month_key in monthly_data:
79
  monthly_data[month_key]["amount"] += transfer.amount
80
+
81
  result = list(monthly_data.values())
82
+ result.sort(key=lambda x: (now_ny.month - x["month"]) % 12)
83
+
84
+ for i in range(len(result)):
85
+ current_month_data = result[i]
86
+ prev_year_month_key = f"{now_ny.year - 1}-{current_month_data['month']}"
87
+ previous_amount = monthly_data.get(prev_year_month_key, {}).get("amount", 0)
88
+ current_amount = current_month_data["amount"]
89
+
90
+ if previous_amount > 0:
91
+ growth_percentage = ((current_amount - previous_amount) / previous_amount) * 100
92
  else:
93
  growth_percentage = 100 if current_amount > 0 else 0
94
+
95
+ current_month_data["growth"] = {
96
  "status": "up" if growth_percentage > 0 else "down",
97
  "percentage": round(growth_percentage, 1),
98
  "formatted": f"{round(growth_percentage, 1)}%"
99
  }
100
+
101
  return result
102
  except Exception as e:
103
  logger.error(f"❌ Error getting monthly revenue: {str(e)}")
 
106
  def get_account_balance(account_id: str) -> Dict[str, Any]:
107
  try:
108
  balance = stripe.Balance.retrieve(stripe_account=account_id)
109
+ available_balance = next((b.amount for b in balance.available if b.currency.upper() == "BRL"), 0)
110
+ pending_balance = next((b.amount for b in balance.pending if b.currency.upper() == "BRL"), 0)
 
 
 
 
 
 
 
 
 
111
  return {
112
  "available_balance": available_balance,
113
  "pending_balance": pending_balance,
114
+ "currency": "BRL"
115
  }
116
  except Exception as e:
117
  logger.error(f"❌ Error getting account balance: {str(e)}")
118
+ return {"available_balance": 0, "pending_balance": 0, "currency": "BRL"}
 
 
 
 
119
 
120
  def get_active_subscribers(user_id: str) -> List[Dict[str, Any]]:
121
  url = f"{SUPABASE_URL}/rest/v1/Subscriptions?stylist_id=eq.{user_id}&active=eq.true&limit=30"
 
144
  if not user_token:
145
  raise HTTPException(status_code=401, detail="Missing User-key header")
146
  user_id = verify_token(user_token)
 
147
  user_data_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
148
  response = requests.get(user_data_url, headers=SUPABASE_HEADERS)
149
  if response.status_code != 200 or not response.json():
150
  raise HTTPException(status_code=404, detail="User not found")
151
  user_data = response.json()[0]
152
  stripe_id = user_data.get("stripe_id")
 
 
 
 
 
 
 
 
 
 
 
153
  return {
154
  "stripe_id": stripe_id,
155
  "available_balance": get_account_balance(stripe_id)["available_balance"],
 
158
  "monthly_revenue": get_monthly_revenue(stripe_id),
159
  "subscribers": get_active_subscribers(user_id)
160
  }
 
 
161
  except Exception as e:
162
  logger.error(f"❌ Error: {str(e)}")
163
  raise HTTPException(status_code=500, detail=str(e))