habulaj commited on
Commit
b5c0590
·
verified ·
1 Parent(s): 2e7841b

Update routes/stylist.py

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