LogicGoInfotechSpaces commited on
Commit
685f07a
·
verified ·
1 Parent(s): b69a1ee

Update api/main.py

Browse files
Files changed (1) hide show
  1. api/main.py +91 -1
api/main.py CHANGED
@@ -3,7 +3,7 @@ import os
3
  import uuid
4
  import shutil
5
  import re
6
- from datetime import datetime
7
  from typing import Dict, List, Optional
8
 
9
  import numpy as np
@@ -111,6 +111,89 @@ def _admin_logging_status() -> Dict[str, object]:
111
  "collection": admin_media_clicks.name,
112
  }
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  def bearer_auth(authorization: Optional[str] = Header(default=None)) -> None:
115
  if not ENV_TOKEN:
116
  return
@@ -168,9 +251,12 @@ def log_media_click(user_id: Optional[str], category_id: Optional[str]) -> None:
168
  user_obj = _coerce_object_id(user_id)
169
  category_obj = _coerce_category_id(category_id)
170
  now = datetime.utcnow()
 
171
 
172
  doc = admin_media_clicks.find_one({"userId": user_obj})
173
  if doc:
 
 
174
  categories = doc.get("categories") or []
175
  if any(cat.get("categoryId") == category_obj for cat in categories):
176
  # Category exists: increment click_count and ai_edit_complete, update dates
@@ -185,6 +271,7 @@ def log_media_click(user_id: Optional[str], category_id: Optional[str]) -> None:
185
  "categories.$.lastClickedAt": now,
186
  "updatedAt": now,
187
  "ai_edit_last_date": now,
 
188
  },
189
  },
190
  )
@@ -204,11 +291,13 @@ def log_media_click(user_id: Optional[str], category_id: Optional[str]) -> None:
204
  "$set": {
205
  "updatedAt": now,
206
  "ai_edit_last_date": now,
 
207
  },
208
  },
209
  )
210
  else:
211
  # New user: create document with default ai_edit_complete=0, then increment to 1
 
212
  admin_media_clicks.update_one(
213
  {"userId": user_obj},
214
  {
@@ -224,6 +313,7 @@ def log_media_click(user_id: Optional[str], category_id: Optional[str]) -> None:
224
  "createdAt": now,
225
  "updatedAt": now,
226
  "ai_edit_complete": 0, # Default for new users
 
227
  },
228
  "$inc": {"ai_edit_complete": 1}, # Increment to 1 on first use
229
  "$set": {
 
3
  import uuid
4
  import shutil
5
  import re
6
+ from datetime import datetime, timedelta, date
7
  from typing import Dict, List, Optional
8
 
9
  import numpy as np
 
111
  "collection": admin_media_clicks.name,
112
  }
113
 
114
+
115
+ def _build_ai_edit_daily_count(
116
+ existing: Optional[List[Dict[str, object]]],
117
+ today: date,
118
+ ) -> List[Dict[str, object]]:
119
+ """
120
+ Build / extend the ai_edit_daily_count array with the following rules:
121
+
122
+ - Case A (no existing data): return [{date: today, count: 1}]
123
+ - Case B (today already recorded): return list unchanged
124
+ - Case C (gap in days): fill missing days with count=0 and append today with count=1
125
+
126
+ The stored "date" value is a midnight UTC (naive UTC) datetime for the given day.
127
+ """
128
+
129
+ def _to_date_only(value: object) -> date:
130
+ if isinstance(value, datetime):
131
+ return value.date()
132
+ if isinstance(value, date):
133
+ return value
134
+ # Fallback: try parsing ISO string "YYYY-MM-DD" or full datetime
135
+ try:
136
+ text = str(value)
137
+ if len(text) == 10:
138
+ return datetime.strptime(text, "%Y-%m-%d").date()
139
+ return datetime.fromisoformat(text).date()
140
+ except Exception:
141
+ # If parsing fails, just treat as today to avoid crashing
142
+ return today
143
+
144
+ # Case A: first ever use (no array yet)
145
+ if not existing:
146
+ return [
147
+ {
148
+ "date": datetime(today.year, today.month, today.day),
149
+ "count": 1,
150
+ }
151
+ ]
152
+
153
+ # Work on a shallow copy so we don't mutate original in-place
154
+ result: List[Dict[str, object]] = list(existing)
155
+
156
+ last_entry = result[-1] if result else None
157
+ if not last_entry or "date" not in last_entry:
158
+ # If structure is unexpected, re-initialize safely
159
+ return [
160
+ {
161
+ "date": datetime(today.year, today.month, today.day),
162
+ "count": 1,
163
+ }
164
+ ]
165
+
166
+ last_date = _to_date_only(last_entry["date"])
167
+
168
+ # If somehow the last stored date is in the future, do nothing to avoid corrupting history
169
+ if last_date > today:
170
+ return result
171
+
172
+ # Case B: today's date already present as the last entry → unchanged
173
+ if last_date == today:
174
+ return result
175
+
176
+ # Case C: there is a gap, fill missing days with count=0 and append today with count=1
177
+ cursor = last_date + timedelta(days=1)
178
+ while cursor < today:
179
+ result.append(
180
+ {
181
+ "date": datetime(cursor.year, cursor.month, cursor.day),
182
+ "count": 0,
183
+ }
184
+ )
185
+ cursor += timedelta(days=1)
186
+
187
+ # Finally add today's presence indicator
188
+ result.append(
189
+ {
190
+ "date": datetime(today.year, today.month, today.day),
191
+ "count": 1,
192
+ }
193
+ )
194
+
195
+ return result
196
+
197
  def bearer_auth(authorization: Optional[str] = Header(default=None)) -> None:
198
  if not ENV_TOKEN:
199
  return
 
251
  user_obj = _coerce_object_id(user_id)
252
  category_obj = _coerce_category_id(category_id)
253
  now = datetime.utcnow()
254
+ today = now.date()
255
 
256
  doc = admin_media_clicks.find_one({"userId": user_obj})
257
  if doc:
258
+ existing_daily = doc.get("ai_edit_daily_count")
259
+ updated_daily = _build_ai_edit_daily_count(existing_daily, today)
260
  categories = doc.get("categories") or []
261
  if any(cat.get("categoryId") == category_obj for cat in categories):
262
  # Category exists: increment click_count and ai_edit_complete, update dates
 
271
  "categories.$.lastClickedAt": now,
272
  "updatedAt": now,
273
  "ai_edit_last_date": now,
274
+ "ai_edit_daily_count": updated_daily,
275
  },
276
  },
277
  )
 
291
  "$set": {
292
  "updatedAt": now,
293
  "ai_edit_last_date": now,
294
+ "ai_edit_daily_count": updated_daily,
295
  },
296
  },
297
  )
298
  else:
299
  # New user: create document with default ai_edit_complete=0, then increment to 1
300
+ daily_for_new = _build_ai_edit_daily_count(None, today)
301
  admin_media_clicks.update_one(
302
  {"userId": user_obj},
303
  {
 
313
  "createdAt": now,
314
  "updatedAt": now,
315
  "ai_edit_complete": 0, # Default for new users
316
+ "ai_edit_daily_count": daily_for_new,
317
  },
318
  "$inc": {"ai_edit_complete": 1}, # Increment to 1 on first use
319
  "$set": {