LogicGoInfotechSpaces commited on
Commit
5d513bc
Β·
verified Β·
1 Parent(s): ddd2551

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -60
app.py CHANGED
@@ -974,7 +974,7 @@ def _verify_bearer_token(credentials: Optional[HTTPAuthorizationCredentials] = D
974
  def sync_log_media_click(user_id_str: str, category_id_str: str):
975
  """
976
  Synchronously logs a click event to the media_clicks collection.
977
- This function should be run using asyncio.to_thread().
978
  """
979
 
980
  if _media_clicks_col is None:
@@ -985,16 +985,11 @@ def sync_log_media_click(user_id_str: str, category_id_str: str):
985
  category_oid = ObjectId(category_id_str.strip())
986
  now = datetime.utcnow()
987
 
988
- # Normalize dates (UTC midnight)
989
  today_date = datetime(now.year, now.month, now.day)
990
- yesterday_date = today_date - timedelta(days=1)
991
-
992
- logger.info(
993
- f"Attempting background write for User:{user_id_str}, Category:{category_id_str}"
994
- )
995
 
996
  # --------------------------------------------------
997
- # 1. AI EDIT USAGE TRACKING (GLOBAL PER USER)
998
  # --------------------------------------------------
999
  _media_clicks_col.update_one(
1000
  {"userId": user_oid},
@@ -1014,57 +1009,56 @@ def sync_log_media_click(user_id_str: str, category_id_str: str):
1014
  upsert=True
1015
  )
1016
 
1017
- # Fetch current daily count entries
1018
- # Fetch current daily count entries
 
1019
  doc = _media_clicks_col.find_one(
1020
  {"userId": user_oid},
1021
  {"ai_edit_daily_count": 1}
1022
  )
 
1023
  daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
1024
-
1025
- daily_updates = []
1026
-
1027
- if not daily_entries:
1028
- # First ever usage β†’ only today
1029
- daily_updates.append({"date": today_date, "count": 1})
1030
- else:
1031
- # Build existing dates map for quick lookup
1032
- existing_dates = {entry["date"].date(): entry["count"] for entry in daily_entries}
1033
-
1034
- # Find last recorded date
1035
- last_date_in_db = max(entry["date"].date() for entry in daily_entries)
1036
-
1037
- # Fill missing days between last date and today-1 with 0
1038
- next_day = last_date_in_db + timedelta(days=1)
1039
- while next_day < today_date:
1040
- if next_day not in existing_dates:
1041
- daily_updates.append({"date": next_day, "count": 0})
1042
- next_day += timedelta(days=1)
1043
-
1044
- # Add today if not already present
1045
- if today_date not in existing_dates:
1046
- daily_updates.append({"date": today_date, "count": 1})
1047
-
1048
- # Push updates if any
1049
- if daily_updates:
1050
- _media_clicks_col.update_one(
1051
- {"userId": user_oid},
1052
- {"$push": {"ai_edit_daily_count": {"$each": daily_updates}}}
1053
- )
1054
-
1055
- # Fetch again, sort oldest β†’ newest, and trim to last 32 entries
1056
- doc = _media_clicks_col.find_one({"userId": user_oid}, {"ai_edit_daily_count": 1})
1057
- daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
1058
- daily_entries.sort(key=lambda x: x["date"])
1059
- if len(daily_entries) > 32:
1060
- daily_entries = daily_entries[-32:]
1061
- _media_clicks_col.update_one(
1062
- {"userId": user_oid},
1063
- {"$set": {"ai_edit_daily_count": daily_entries}}
1064
- )
1065
 
1066
  # --------------------------------------------------
1067
- # 2. CATEGORY CLICK LOGIC
1068
  # --------------------------------------------------
1069
  update_result = _media_clicks_col.update_one(
1070
  {
@@ -1083,7 +1077,7 @@ def sync_log_media_click(user_id_str: str, category_id_str: str):
1083
  )
1084
 
1085
  # --------------------------------------------------
1086
- # 3. IF CATEGORY DOES NOT EXIST β†’ PUSH NEW
1087
  # --------------------------------------------------
1088
  if update_result.matched_count == 0:
1089
  _media_clicks_col.update_one(
@@ -1123,6 +1117,10 @@ def sync_log_media_click(user_id_str: str, category_id_str: str):
1123
  # category_oid = ObjectId(category_id_str.strip())
1124
  # now = datetime.utcnow()
1125
 
 
 
 
 
1126
  # logger.info(
1127
  # f"Attempting background write for User:{user_id_str}, Category:{category_id_str}"
1128
  # )
@@ -1133,20 +1131,70 @@ def sync_log_media_click(user_id_str: str, category_id_str: str):
1133
  # _media_clicks_col.update_one(
1134
  # {"userId": user_oid},
1135
  # {
 
 
 
 
1136
  # "$set": {
1137
  # "ai_edit_last_date": now,
1138
  # "updatedAt": now
1139
  # },
1140
  # "$inc": {
1141
  # "ai_edit_complete": 1
1142
- # },
1143
- # "$setOnInsert": {
1144
- # "createdAt": now
1145
  # }
1146
  # },
1147
  # upsert=True
1148
  # )
1149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1150
  # # --------------------------------------------------
1151
  # # 2. CATEGORY CLICK LOGIC
1152
  # # --------------------------------------------------
@@ -1173,9 +1221,7 @@ def sync_log_media_click(user_id_str: str, category_id_str: str):
1173
  # _media_clicks_col.update_one(
1174
  # {"userId": user_oid},
1175
  # {
1176
- # "$set": {
1177
- # "updatedAt": now
1178
- # },
1179
  # "$push": {
1180
  # "categories": {
1181
  # "categoryId": category_oid,
@@ -1193,7 +1239,6 @@ def sync_log_media_click(user_id_str: str, category_id_str: str):
1193
 
1194
  # except Exception as media_err:
1195
  # logger.error(f"MEDIA_CLICK LOGGING ERROR: {media_err}")
1196
- # # swallow error – do not affect main flow
1197
  # pass
1198
 
1199
 
 
974
  def sync_log_media_click(user_id_str: str, category_id_str: str):
975
  """
976
  Synchronously logs a click event to the media_clicks collection.
977
+ ai_edit_daily_count is STRICTLY binary per day (no duplicate dates).
978
  """
979
 
980
  if _media_clicks_col is None:
 
985
  category_oid = ObjectId(category_id_str.strip())
986
  now = datetime.utcnow()
987
 
988
+ # Normalize today to UTC midnight
989
  today_date = datetime(now.year, now.month, now.day)
 
 
 
 
 
990
 
991
  # --------------------------------------------------
992
+ # 1. Ensure root document exists
993
  # --------------------------------------------------
994
  _media_clicks_col.update_one(
995
  {"userId": user_oid},
 
1009
  upsert=True
1010
  )
1011
 
1012
+ # --------------------------------------------------
1013
+ # 2. FIXED DAILY BINARY TRACKING (NO DUPLICATES)
1014
+ # --------------------------------------------------
1015
  doc = _media_clicks_col.find_one(
1016
  {"userId": user_oid},
1017
  {"ai_edit_daily_count": 1}
1018
  )
1019
+
1020
  daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
1021
+
1022
+ # Convert existing entries into date β†’ count map
1023
+ daily_map = {
1024
+ entry["date"]: entry["count"]
1025
+ for entry in daily_entries
1026
+ }
1027
+
1028
+ # Determine last known date
1029
+ last_date = max(daily_map.keys()) if daily_map else today_date
1030
+
1031
+ # Fill ALL missing days with 0
1032
+ next_day = last_date + timedelta(days=1)
1033
+ while next_day < today_date:
1034
+ daily_map.setdefault(next_day, 0)
1035
+ next_day += timedelta(days=1)
1036
+
1037
+ # Mark today as used (binary = 1)
1038
+ daily_map[today_date] = 1
1039
+
1040
+ # Rebuild sorted list (oldest β†’ newest)
1041
+ final_daily_entries = [
1042
+ {"date": d, "count": daily_map[d]}
1043
+ for d in sorted(daily_map.keys())
1044
+ ]
1045
+
1046
+ # Keep last 32 days only
1047
+ final_daily_entries = final_daily_entries[-32:]
1048
+
1049
+ # ATOMIC replace (no $push)
1050
+ _media_clicks_col.update_one(
1051
+ {"userId": user_oid},
1052
+ {
1053
+ "$set": {
1054
+ "ai_edit_daily_count": final_daily_entries,
1055
+ "updatedAt": now
1056
+ }
1057
+ }
1058
+ )
 
 
 
1059
 
1060
  # --------------------------------------------------
1061
+ # 3. CATEGORY CLICK LOGIC (DATES CAN REPEAT)
1062
  # --------------------------------------------------
1063
  update_result = _media_clicks_col.update_one(
1064
  {
 
1077
  )
1078
 
1079
  # --------------------------------------------------
1080
+ # 4. PUSH CATEGORY IF MISSING (ORDER = TIME)
1081
  # --------------------------------------------------
1082
  if update_result.matched_count == 0:
1083
  _media_clicks_col.update_one(
 
1117
  # category_oid = ObjectId(category_id_str.strip())
1118
  # now = datetime.utcnow()
1119
 
1120
+ # # Normalize dates (UTC midnight)
1121
+ # today_date = datetime(now.year, now.month, now.day)
1122
+ # yesterday_date = today_date - timedelta(days=1)
1123
+
1124
  # logger.info(
1125
  # f"Attempting background write for User:{user_id_str}, Category:{category_id_str}"
1126
  # )
 
1131
  # _media_clicks_col.update_one(
1132
  # {"userId": user_oid},
1133
  # {
1134
+ # "$setOnInsert": {
1135
+ # "createdAt": now,
1136
+ # "ai_edit_daily_count": []
1137
+ # },
1138
  # "$set": {
1139
  # "ai_edit_last_date": now,
1140
  # "updatedAt": now
1141
  # },
1142
  # "$inc": {
1143
  # "ai_edit_complete": 1
 
 
 
1144
  # }
1145
  # },
1146
  # upsert=True
1147
  # )
1148
 
1149
+ # # Fetch current daily count entries
1150
+ # # Fetch current daily count entries
1151
+ # doc = _media_clicks_col.find_one(
1152
+ # {"userId": user_oid},
1153
+ # {"ai_edit_daily_count": 1}
1154
+ # )
1155
+ # daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
1156
+
1157
+ # daily_updates = []
1158
+
1159
+ # if not daily_entries:
1160
+ # # First ever usage β†’ only today
1161
+ # daily_updates.append({"date": today_date, "count": 1})
1162
+ # else:
1163
+ # # Build existing dates map for quick lookup
1164
+ # existing_dates = {entry["date"].date(): entry["count"] for entry in daily_entries}
1165
+
1166
+ # # Find last recorded date
1167
+ # last_date_in_db = max(entry["date"].date() for entry in daily_entries)
1168
+
1169
+ # # Fill missing days between last date and today-1 with 0
1170
+ # next_day = last_date_in_db + timedelta(days=1)
1171
+ # while next_day < today_date:
1172
+ # if next_day not in existing_dates:
1173
+ # daily_updates.append({"date": next_day, "count": 0})
1174
+ # next_day += timedelta(days=1)
1175
+
1176
+ # # Add today if not already present
1177
+ # if today_date not in existing_dates:
1178
+ # daily_updates.append({"date": today_date, "count": 1})
1179
+
1180
+ # # Push updates if any
1181
+ # if daily_updates:
1182
+ # _media_clicks_col.update_one(
1183
+ # {"userId": user_oid},
1184
+ # {"$push": {"ai_edit_daily_count": {"$each": daily_updates}}}
1185
+ # )
1186
+
1187
+ # # Fetch again, sort oldest β†’ newest, and trim to last 32 entries
1188
+ # doc = _media_clicks_col.find_one({"userId": user_oid}, {"ai_edit_daily_count": 1})
1189
+ # daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
1190
+ # daily_entries.sort(key=lambda x: x["date"])
1191
+ # if len(daily_entries) > 32:
1192
+ # daily_entries = daily_entries[-32:]
1193
+ # _media_clicks_col.update_one(
1194
+ # {"userId": user_oid},
1195
+ # {"$set": {"ai_edit_daily_count": daily_entries}}
1196
+ # )
1197
+
1198
  # # --------------------------------------------------
1199
  # # 2. CATEGORY CLICK LOGIC
1200
  # # --------------------------------------------------
 
1221
  # _media_clicks_col.update_one(
1222
  # {"userId": user_oid},
1223
  # {
1224
+ # "$set": {"updatedAt": now},
 
 
1225
  # "$push": {
1226
  # "categories": {
1227
  # "categoryId": category_oid,
 
1239
 
1240
  # except Exception as media_err:
1241
  # logger.error(f"MEDIA_CLICK LOGGING ERROR: {media_err}")
 
1242
  # pass
1243
 
1244