habulaj commited on
Commit
5a06dce
·
verified ·
1 Parent(s): b5c0590

Update routes/stylist.py

Browse files
Files changed (1) hide show
  1. routes/stylist.py +80 -8
routes/stylist.py CHANGED
@@ -58,7 +58,7 @@ def get_account_balance(account_id: str) -> Dict[str, Any]:
58
  logger.error(f"❌ Error getting account balance: {str(e)}")
59
  return {"available_balance": 0, "pending_balance": 0, "currency": "BRL"}
60
 
61
- def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
62
  ny_timezone = pytz.timezone('America/New_York')
63
  now_ny = datetime.now(ny_timezone)
64
  monthly_data = {}
@@ -92,8 +92,8 @@ def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
92
  month_key = f"{transfer_date.year}-{transfer_date.month}"
93
  if month_key in monthly_data:
94
  monthly_data[month_key]["amount"] += transfer.amount
95
- if now_ny - transfer_date <= relativedelta(months=6):
96
- total_revenue_last_6_months += transfer.amount
97
 
98
  result = list(monthly_data.values())
99
  result.sort(key=lambda x: (now_ny.month - x["month"]) % 12)
@@ -115,10 +115,81 @@ def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
115
  "formatted": f"{round(growth_percentage, 1)}%"
116
  }
117
 
118
- return result, total_revenue_last_6_months
 
 
 
119
  except Exception as e:
120
  logger.error(f"❌ Error getting monthly revenue: {str(e)}")
121
- return list(monthly_data.values()), total_revenue_last_6_months
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
  @router.get("/dashboard")
124
  def get_dashboard(user_token: str = Header(None, alias="User-key"), page: int = Query(0, ge=0)):
@@ -129,13 +200,14 @@ def get_dashboard(user_token: str = Header(None, alias="User-key"), page: int =
129
  user_data = response.json()[0]
130
  stripe_id = user_data.get("stripe_id")
131
 
132
- monthly_revenue, total_revenue_last_6_months = get_monthly_revenue(stripe_id)
 
133
 
134
  return {
135
  "stripe_id": stripe_id,
136
  "available_balance": get_account_balance(stripe_id),
137
- "monthly_revenue": monthly_revenue,
138
- "total_revenue_last_6_months": total_revenue_last_6_months,
139
  "total_followers": get_total_followers(user_id),
140
  "total_subscribers": get_total_subscribers(user_id),
141
  **get_active_subscribers(user_id, page)
 
58
  logger.error(f"❌ Error getting account balance: {str(e)}")
59
  return {"available_balance": 0, "pending_balance": 0, "currency": "BRL"}
60
 
61
+ def get_monthly_revenue(account_id: str) -> Dict[str, Any]:
62
  ny_timezone = pytz.timezone('America/New_York')
63
  now_ny = datetime.now(ny_timezone)
64
  monthly_data = {}
 
92
  month_key = f"{transfer_date.year}-{transfer_date.month}"
93
  if month_key in monthly_data:
94
  monthly_data[month_key]["amount"] += transfer.amount
95
+ # Adiciona ao total dos últimos 6 meses
96
+ total_revenue_last_6_months += transfer.amount
97
 
98
  result = list(monthly_data.values())
99
  result.sort(key=lambda x: (now_ny.month - x["month"]) % 12)
 
115
  "formatted": f"{round(growth_percentage, 1)}%"
116
  }
117
 
118
+ return {
119
+ "monthly_data": result,
120
+ "total_last_6_months": total_revenue_last_6_months
121
+ }
122
  except Exception as e:
123
  logger.error(f"❌ Error getting monthly revenue: {str(e)}")
124
+ return {
125
+ "monthly_data": list(monthly_data.values()),
126
+ "total_last_6_months": 0
127
+ }
128
+
129
+ def format_subscription_date(created_at_str: str) -> str:
130
+ """Format the subscription date to the requested format: e.g. '13th January 2025'"""
131
+ try:
132
+ created_at = datetime.fromisoformat(created_at_str.replace('Z', '+00:00'))
133
+
134
+ # Add suffix to day
135
+ day = created_at.day
136
+ if 4 <= day <= 20 or 24 <= day <= 30:
137
+ suffix = "th"
138
+ else:
139
+ suffix = {1: "st", 2: "nd", 3: "rd"}.get(day % 10, "th")
140
+
141
+ # Format the date
142
+ return f"{day}{suffix} {created_at.strftime('%B %Y')}"
143
+ except Exception as e:
144
+ logger.error(f"❌ Error formatting subscription date: {str(e)}")
145
+ return "Unknown date"
146
+
147
+ def get_active_subscribers(user_id: str, page: int) -> Dict[str, Any]:
148
+ limit = 30
149
+ offset = page * limit
150
+
151
+ # Ordenar por created_at em ordem decrescente (mais recente primeiro)
152
+ url = f"{SUPABASE_URL}/rest/v1/Subscriptions?stylist_id=eq.{user_id}&active=eq.true&order=created_at.desc&limit={limit}&offset={offset}"
153
+
154
+ response = requests.get(url, headers=SUPABASE_HEADERS)
155
+ if response.status_code == 200:
156
+ subscribers = response.json()
157
+ subscriber_list = []
158
+ for sub in subscribers:
159
+ customer_id = sub.get("customer_id")
160
+ user_data_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{customer_id}"
161
+ user_response = requests.get(user_data_url, headers=SUPABASE_HEADERS)
162
+ if user_response.status_code == 200 and user_response.json():
163
+ user_info = user_response.json()[0]
164
+ subscription_date = format_subscription_date(sub.get("created_at", ""))
165
+ subscriber_list.append({
166
+ "id": user_info.get("id"),
167
+ "name": user_info.get("name"),
168
+ "avatar": user_info.get("avatar"),
169
+ "blurhash": user_info.get("blurhash"),
170
+ "subscription_date": subscription_date
171
+ })
172
+
173
+ has_next_page = len(subscribers) == limit
174
+ return {"subscribers": subscriber_list, "has_next_page": has_next_page}
175
+
176
+ return {"subscribers": [], "has_next_page": False}
177
+
178
+ def get_total_followers(user_id: str) -> int:
179
+ url = f"{SUPABASE_URL}/rest/v1/followers?following_id=eq.{user_id}"
180
+ response = requests.get(url, headers=SUPABASE_HEADERS)
181
+ if response.status_code == 200:
182
+ followers = response.json()
183
+ return len(followers)
184
+ return 0
185
+
186
+ def get_total_subscribers(user_id: str) -> int:
187
+ url = f"{SUPABASE_URL}/rest/v1/Subscriptions?stylist_id=eq.{user_id}&active=eq.true"
188
+ response = requests.get(url, headers=SUPABASE_HEADERS)
189
+ if response.status_code == 200:
190
+ subscribers = response.json()
191
+ return len(subscribers)
192
+ return 0
193
 
194
  @router.get("/dashboard")
195
  def get_dashboard(user_token: str = Header(None, alias="User-key"), page: int = Query(0, ge=0)):
 
200
  user_data = response.json()[0]
201
  stripe_id = user_data.get("stripe_id")
202
 
203
+ # Obter dados de receita mensal e total dos últimos 6 meses
204
+ revenue_data = get_monthly_revenue(stripe_id)
205
 
206
  return {
207
  "stripe_id": stripe_id,
208
  "available_balance": get_account_balance(stripe_id),
209
+ "monthly_revenue": revenue_data["monthly_data"],
210
+ "total_revenue_last_6_months": revenue_data["total_last_6_months"],
211
  "total_followers": get_total_followers(user_id),
212
  "total_subscribers": get_total_subscribers(user_id),
213
  **get_active_subscribers(user_id, page)