suhailshafi007 commited on
Commit
31af2d0
·
1 Parent(s): e7e5cf6

feat: progress architecture, apple harvest reconciliation, and lifetime apples

Browse files
Files changed (1) hide show
  1. app/auth.py +117 -70
app/auth.py CHANGED
@@ -720,30 +720,37 @@ async def get_profile(uid: str, current_user: dict = Depends(get_current_user)):
720
  enabled = user.get("progress_tracking_enabled", pt.get("enabled"))
721
  started_at = user.get("progress_tracking_started_at", pt.get("started_at"))
722
  started_date = user.get("progress_tracking_started_date", pt.get("started_date"))
 
723
 
724
- if responded is None:
725
- first_dp = await daily_progress_collection.find({"uid": uid}).sort("date", 1).limit(1).to_list(1)
 
 
726
  if first_dp:
727
- earliest_d = first_dp[0]["date"]
728
- enabled = True
729
- responded = True
730
- started_date = earliest_d
731
- await users_collection.update_one(
732
- {"uid": uid},
733
- {
734
- "$set": {
735
- "progress_tracking_enabled": True,
736
- "progress_tracking_prompt_responded": True,
737
- "progress_tracking_started_date": earliest_d,
738
- "progress_tracking.enabled": True,
739
- "progress_tracking.prompt_responded": True,
740
- "progress_tracking.started_date": earliest_d,
741
- }
 
 
 
742
  }
743
- )
744
- else:
745
- enabled = False
746
- responded = False
 
747
 
748
  user["progress_tracking_enabled"] = bool(enabled)
749
  user["progress_tracking_prompt_responded"] = bool(responded)
@@ -2305,9 +2312,19 @@ async def _recalculate_nimaz_stats_for_user(uid: str, today_str: Optional[str] =
2305
  if not today_str:
2306
  today_str = datetime.datetime.utcnow().date().isoformat()
2307
 
 
 
 
 
 
 
 
 
 
 
2308
  try:
2309
  docs = await daily_progress_collection.find(
2310
- {"uid": uid},
2311
  {"_id": 0, "date": 1, "prayers": 1, "quran_secs": 1, "hadith_secs": 1, "tasbeeh_count": 1, "is_full": 1, "is_golden": 1}
2312
  ).to_list(length=5000)
2313
  except Exception:
@@ -2318,12 +2335,18 @@ async def _recalculate_nimaz_stats_for_user(uid: str, today_str: Optional[str] =
2318
  total_quran_days = 0
2319
  total_golden_days = 0
2320
  total_full_days = 0
 
2321
  last_active_date = ""
2322
 
2323
  for doc in docs:
2324
  d_str = doc.get("date")
2325
  if not d_str:
2326
  continue
 
 
 
 
 
2327
  if not last_active_date or d_str > last_active_date:
2328
  last_active_date = d_str
2329
 
@@ -2380,7 +2403,7 @@ async def _recalculate_nimaz_stats_for_user(uid: str, today_str: Optional[str] =
2380
  "missed": missed_counts,
2381
  "total_prayed": total_prayed,
2382
  "total_missed": total_missed,
2383
- "total_days": len(docs),
2384
  "total_full_days": total_full_days,
2385
  "total_golden_days": total_golden_days,
2386
  "total_quran_days": total_quran_days,
@@ -3306,7 +3329,7 @@ async def get_progress_monthly(
3306
  user_doc = None
3307
  try:
3308
  user_doc = await users_collection.find_one(
3309
- {"uid": uid},
3310
  {"progress_tracking": 1, "progress_tracking_enabled": 1, "progress_tracking_started_date": 1, "created_at": 1}
3311
  )
3312
  except Exception:
@@ -3363,14 +3386,14 @@ async def get_progress_monthly(
3363
  dates_range = [f"{target_year:04d}-{target_month:02d}-{d:02d}" for d in range(1, num_days + 1)]
3364
 
3365
  docs = await daily_progress_collection.find(
3366
- {"uid": uid, "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0}
3367
  ).sort("date", 1).to_list(length=100)
3368
 
3369
  # Fetch tasbeeh daily rollups for the date range to guarantee all deeds are included
3370
  tasbeeh_by_date = {}
3371
  try:
3372
  tasbeeh_dailies = await tasbeeh_daily_collection.find(
3373
- {"uid": uid, "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0, "date": 1, "total_count": 1}
3374
  ).to_list(length=35)
3375
  for td in tasbeeh_dailies:
3376
  td_date = td.get("date")
@@ -3381,7 +3404,7 @@ async def get_progress_monthly(
3381
 
3382
  if not tasbeeh_by_date:
3383
  tasbeeh_sessions = await tasbeeh_collection.find(
3384
- {"uid": uid, "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0, "date": 1, "count": 1}
3385
  ).to_list(length=1000)
3386
  for ts in tasbeeh_sessions:
3387
  ts_date = ts.get("date")
@@ -3404,33 +3427,44 @@ async def get_progress_monthly(
3404
  h_secs = int(item.get("hadith_secs", 0) or 0)
3405
  t_count = max(int(item.get("tasbeeh_count", 0) or 0), tasbeeh_by_date.get(d, 0))
3406
  is_golden = is_full and (q_secs >= PROGRESS_GOAL_SECONDS) and (h_secs >= PROGRESS_GOAL_SECONDS or t_count >= PROGRESS_TASBEEH_GOAL)
 
3407
 
3408
- if is_full:
3409
- full_days += 1
3410
- if is_golden:
3411
- golden_days += 1
 
3412
 
3413
- for p in prayers:
3414
- if p in prayer_counts:
3415
- prayer_counts[p] += 1
3416
 
3417
  days_list.append({
3418
  "date": d,
3419
- "prayers": prayers,
3420
- "completed_count": len(prayers),
3421
- "is_full": is_full,
3422
- "is_golden": is_golden,
3423
- "quran_secs": q_secs,
3424
- "hadith_secs": h_secs,
3425
- "tasbeeh_count": t_count,
 
3426
  })
3427
 
3428
- # Elapsed days calculation (so future unelapsed days don't falsely register as missed)
3429
  is_current_month = (target_year == today.year and target_month == today.month)
 
 
 
 
 
 
 
 
3430
  if is_current_month:
3431
- elapsed_days = min(num_days, today.day)
3432
  elif target_year < today.year or (target_year == today.year and target_month < today.month):
3433
- elapsed_days = num_days
3434
  else:
3435
  elapsed_days = 0
3436
 
@@ -3446,7 +3480,11 @@ async def get_progress_monthly(
3446
  today_item = docs_by_date.get(today_str, {})
3447
  today_raw = today_item.get("prayers", []) or []
3448
  today_norm = set(_normalize_progress_prayer_name(x) for x in today_raw if _normalize_progress_prayer_name(x))
3449
- past_days_count = max(0, min(num_days, today.day - 1)) if is_current_month else elapsed_days
 
 
 
 
3450
 
3451
  missed_today_count = 0
3452
  for p in PROGRESS_PRAYERS:
@@ -3573,13 +3611,15 @@ async def get_progress_tracking_status(request: Request, user: dict = Depends(ge
3573
  """Retrieves whether the user has enabled progress tracking, consent response state, and recording start date."""
3574
  uid = user["uid"]
3575
  u = await users_collection.find_one(
3576
- {"uid": uid},
3577
  {
3578
  "progress_tracking": 1,
3579
  "progress_tracking_enabled": 1,
3580
  "progress_tracking_prompt_responded": 1,
3581
  "progress_tracking_started_at": 1,
3582
  "progress_tracking_started_date": 1,
 
 
3583
  "created_at": 1,
3584
  }
3585
  )
@@ -3591,30 +3631,37 @@ async def get_progress_tracking_status(request: Request, user: dict = Depends(ge
3591
  enabled = u.get("progress_tracking_enabled", pt.get("enabled"))
3592
  started_at = u.get("progress_tracking_started_at", pt.get("started_at"))
3593
  started_date = u.get("progress_tracking_started_date", pt.get("started_date"))
 
3594
 
3595
- if responded is None:
3596
- first_dp = await daily_progress_collection.find({"uid": uid}).sort("date", 1).limit(1).to_list(1)
 
 
3597
  if first_dp:
3598
- earliest_d = first_dp[0]["date"]
3599
- enabled = True
3600
- responded = True
3601
- started_date = earliest_d
3602
- await users_collection.update_one(
3603
- {"uid": uid},
3604
- {
3605
- "$set": {
3606
- "progress_tracking_enabled": True,
3607
- "progress_tracking_prompt_responded": True,
3608
- "progress_tracking_started_date": earliest_d,
3609
- "progress_tracking.enabled": True,
3610
- "progress_tracking.prompt_responded": True,
3611
- "progress_tracking.started_date": earliest_d,
3612
- }
 
 
 
3613
  }
3614
- )
3615
- else:
3616
- enabled = False
3617
- responded = False
 
3618
 
3619
  return {
3620
  "enabled": bool(enabled),
@@ -3635,12 +3682,12 @@ async def update_progress_tracking_status(payload: TrackingStatusReq, request: R
3635
  today_str = _progress_local_date(payload.tz).isoformat()
3636
 
3637
  if act in ("enable", "yes", "true"):
3638
- u = await users_collection.find_one({"uid": uid}, {"progress_tracking_started_date": 1, "progress_tracking.started_date": 1})
3639
  existing_start = (u or {}).get("progress_tracking_started_date") or ((u or {}).get("progress_tracking") or {}).get("started_date")
3640
  start_date = existing_start or today_str
3641
 
3642
  await users_collection.update_one(
3643
- {"uid": uid},
3644
  {
3645
  "$set": {
3646
  "progress_tracking_enabled": True,
@@ -3664,7 +3711,7 @@ async def update_progress_tracking_status(payload: TrackingStatusReq, request: R
3664
  }
3665
  elif act in ("later", "false"):
3666
  await users_collection.update_one(
3667
- {"uid": uid},
3668
  {
3669
  "$set": {
3670
  "progress_tracking_enabled": False,
 
720
  enabled = user.get("progress_tracking_enabled", pt.get("enabled"))
721
  started_at = user.get("progress_tracking_started_at", pt.get("started_at"))
722
  started_date = user.get("progress_tracking_started_date", pt.get("started_date"))
723
+ lifetime_apples = int(user.get("lifetime_apples", 0) or (user.get("metrics") or {}).get("lifetime_apples", 0) or 0)
724
 
725
+ # Auto-heal: If user is already tracking (enabled is True, started_date set, apples collected, or has records)
726
+ is_already_tracking = bool(enabled) or bool(started_date) or (lifetime_apples > 0)
727
+ if not is_already_tracking:
728
+ first_dp = await daily_progress_collection.find({"$or": [{"uid": uid}, {"_id": uid}]}).sort("date", 1).limit(1).to_list(1)
729
  if first_dp:
730
+ is_already_tracking = True
731
+ started_date = started_date or first_dp[0].get("date")
732
+
733
+ if is_already_tracking:
734
+ enabled = True
735
+ responded = True
736
+ if not started_date:
737
+ started_date = datetime.datetime.utcnow().date().isoformat()
738
+ await users_collection.update_one(
739
+ {"$or": [{"uid": uid}, {"_id": uid}]},
740
+ {
741
+ "$set": {
742
+ "progress_tracking_enabled": True,
743
+ "progress_tracking_prompt_responded": True,
744
+ "progress_tracking_started_date": started_date,
745
+ "progress_tracking.enabled": True,
746
+ "progress_tracking.prompt_responded": True,
747
+ "progress_tracking.started_date": started_date,
748
  }
749
+ }
750
+ )
751
+ elif responded is None:
752
+ enabled = False
753
+ responded = False
754
 
755
  user["progress_tracking_enabled"] = bool(enabled)
756
  user["progress_tracking_prompt_responded"] = bool(responded)
 
2312
  if not today_str:
2313
  today_str = datetime.datetime.utcnow().date().isoformat()
2314
 
2315
+ user_doc = None
2316
+ try:
2317
+ user_doc = await users_collection.find_one(
2318
+ {"$or": [{"uid": uid}, {"_id": uid}]},
2319
+ {"progress_tracking_started_date": 1, "progress_tracking.started_date": 1}
2320
+ )
2321
+ except Exception:
2322
+ user_doc = None
2323
+ started_date = (user_doc or {}).get("progress_tracking_started_date") or ((user_doc or {}).get("progress_tracking") or {}).get("started_date")
2324
+
2325
  try:
2326
  docs = await daily_progress_collection.find(
2327
+ {"$or": [{"uid": uid}, {"_id": uid}]},
2328
  {"_id": 0, "date": 1, "prayers": 1, "quran_secs": 1, "hadith_secs": 1, "tasbeeh_count": 1, "is_full": 1, "is_golden": 1}
2329
  ).to_list(length=5000)
2330
  except Exception:
 
2335
  total_quran_days = 0
2336
  total_golden_days = 0
2337
  total_full_days = 0
2338
+ valid_days_count = 0
2339
  last_active_date = ""
2340
 
2341
  for doc in docs:
2342
  d_str = doc.get("date")
2343
  if not d_str:
2344
  continue
2345
+ # Strictly ignore any days prior to the start of progress tracking
2346
+ if started_date and d_str < started_date:
2347
+ continue
2348
+
2349
+ valid_days_count += 1
2350
  if not last_active_date or d_str > last_active_date:
2351
  last_active_date = d_str
2352
 
 
2403
  "missed": missed_counts,
2404
  "total_prayed": total_prayed,
2405
  "total_missed": total_missed,
2406
+ "total_days": valid_days_count,
2407
  "total_full_days": total_full_days,
2408
  "total_golden_days": total_golden_days,
2409
  "total_quran_days": total_quran_days,
 
3329
  user_doc = None
3330
  try:
3331
  user_doc = await users_collection.find_one(
3332
+ {"$or": [{"uid": uid}, {"_id": uid}]},
3333
  {"progress_tracking": 1, "progress_tracking_enabled": 1, "progress_tracking_started_date": 1, "created_at": 1}
3334
  )
3335
  except Exception:
 
3386
  dates_range = [f"{target_year:04d}-{target_month:02d}-{d:02d}" for d in range(1, num_days + 1)]
3387
 
3388
  docs = await daily_progress_collection.find(
3389
+ {"$or": [{"uid": uid}, {"_id": uid}], "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0}
3390
  ).sort("date", 1).to_list(length=100)
3391
 
3392
  # Fetch tasbeeh daily rollups for the date range to guarantee all deeds are included
3393
  tasbeeh_by_date = {}
3394
  try:
3395
  tasbeeh_dailies = await tasbeeh_daily_collection.find(
3396
+ {"$or": [{"uid": uid}, {"_id": uid}], "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0, "date": 1, "total_count": 1}
3397
  ).to_list(length=35)
3398
  for td in tasbeeh_dailies:
3399
  td_date = td.get("date")
 
3404
 
3405
  if not tasbeeh_by_date:
3406
  tasbeeh_sessions = await tasbeeh_collection.find(
3407
+ {"$or": [{"uid": uid}, {"_id": uid}], "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0, "date": 1, "count": 1}
3408
  ).to_list(length=1000)
3409
  for ts in tasbeeh_sessions:
3410
  ts_date = ts.get("date")
 
3427
  h_secs = int(item.get("hadith_secs", 0) or 0)
3428
  t_count = max(int(item.get("tasbeeh_count", 0) or 0), tasbeeh_by_date.get(d, 0))
3429
  is_golden = is_full and (q_secs >= PROGRESS_GOAL_SECONDS) and (h_secs >= PROGRESS_GOAL_SECONDS or t_count >= PROGRESS_TASBEEH_GOAL)
3430
+ is_untracked = bool(started_date_str and d < started_date_str)
3431
 
3432
+ if not is_untracked:
3433
+ if is_full:
3434
+ full_days += 1
3435
+ if is_golden:
3436
+ golden_days += 1
3437
 
3438
+ for p in prayers:
3439
+ if p in prayer_counts:
3440
+ prayer_counts[p] += 1
3441
 
3442
  days_list.append({
3443
  "date": d,
3444
+ "prayers": prayers if not is_untracked else [],
3445
+ "completed_count": len(prayers) if not is_untracked else 0,
3446
+ "is_full": is_full if not is_untracked else False,
3447
+ "is_golden": is_golden if not is_untracked else False,
3448
+ "is_untracked": is_untracked,
3449
+ "quran_secs": q_secs if not is_untracked else 0,
3450
+ "hadith_secs": h_secs if not is_untracked else 0,
3451
+ "tasbeeh_count": t_count if not is_untracked else 0,
3452
  })
3453
 
3454
+ # Elapsed days calculation (so future unelapsed days & pre-start days don't falsely register as missed)
3455
  is_current_month = (target_year == today.year and target_month == today.month)
3456
+ is_earliest_month = (target_year == earliest_year and target_month == earliest_month)
3457
+ start_day = 1
3458
+ if is_earliest_month and started_date_str:
3459
+ try:
3460
+ start_day = int(started_date_str[8:10])
3461
+ except Exception:
3462
+ start_day = 1
3463
+
3464
  if is_current_month:
3465
+ elapsed_days = max(1, min(num_days, today.day) - start_day + 1) if is_earliest_month else min(num_days, today.day)
3466
  elif target_year < today.year or (target_year == today.year and target_month < today.month):
3467
+ elapsed_days = max(1, num_days - start_day + 1) if is_earliest_month else num_days
3468
  else:
3469
  elapsed_days = 0
3470
 
 
3480
  today_item = docs_by_date.get(today_str, {})
3481
  today_raw = today_item.get("prayers", []) or []
3482
  today_norm = set(_normalize_progress_prayer_name(x) for x in today_raw if _normalize_progress_prayer_name(x))
3483
+
3484
+ if is_current_month:
3485
+ past_days_count = max(0, min(num_days, today.day - 1) - start_day + 1) if is_earliest_month else max(0, min(num_days, today.day - 1))
3486
+ else:
3487
+ past_days_count = elapsed_days
3488
 
3489
  missed_today_count = 0
3490
  for p in PROGRESS_PRAYERS:
 
3611
  """Retrieves whether the user has enabled progress tracking, consent response state, and recording start date."""
3612
  uid = user["uid"]
3613
  u = await users_collection.find_one(
3614
+ {"$or": [{"uid": uid}, {"_id": uid}]},
3615
  {
3616
  "progress_tracking": 1,
3617
  "progress_tracking_enabled": 1,
3618
  "progress_tracking_prompt_responded": 1,
3619
  "progress_tracking_started_at": 1,
3620
  "progress_tracking_started_date": 1,
3621
+ "lifetime_apples": 1,
3622
+ "metrics.lifetime_apples": 1,
3623
  "created_at": 1,
3624
  }
3625
  )
 
3631
  enabled = u.get("progress_tracking_enabled", pt.get("enabled"))
3632
  started_at = u.get("progress_tracking_started_at", pt.get("started_at"))
3633
  started_date = u.get("progress_tracking_started_date", pt.get("started_date"))
3634
+ lifetime_apples = int(u.get("lifetime_apples", 0) or (u.get("metrics") or {}).get("lifetime_apples", 0) or 0)
3635
 
3636
+ # Auto-heal: If user is already tracking (enabled is True, started_date set, apples collected, or has records)
3637
+ is_already_tracking = bool(enabled) or bool(started_date) or (lifetime_apples > 0)
3638
+ if not is_already_tracking:
3639
+ first_dp = await daily_progress_collection.find({"$or": [{"uid": uid}, {"_id": uid}]}).sort("date", 1).limit(1).to_list(1)
3640
  if first_dp:
3641
+ is_already_tracking = True
3642
+ started_date = started_date or first_dp[0].get("date")
3643
+
3644
+ if is_already_tracking:
3645
+ enabled = True
3646
+ responded = True
3647
+ if not started_date:
3648
+ started_date = datetime.datetime.utcnow().date().isoformat()
3649
+ await users_collection.update_one(
3650
+ {"$or": [{"uid": uid}, {"_id": uid}]},
3651
+ {
3652
+ "$set": {
3653
+ "progress_tracking_enabled": True,
3654
+ "progress_tracking_prompt_responded": True,
3655
+ "progress_tracking_started_date": started_date,
3656
+ "progress_tracking.enabled": True,
3657
+ "progress_tracking.prompt_responded": True,
3658
+ "progress_tracking.started_date": started_date,
3659
  }
3660
+ }
3661
+ )
3662
+ elif responded is None:
3663
+ enabled = False
3664
+ responded = False
3665
 
3666
  return {
3667
  "enabled": bool(enabled),
 
3682
  today_str = _progress_local_date(payload.tz).isoformat()
3683
 
3684
  if act in ("enable", "yes", "true"):
3685
+ u = await users_collection.find_one({"$or": [{"uid": uid}, {"_id": uid}]}, {"progress_tracking_started_date": 1, "progress_tracking.started_date": 1})
3686
  existing_start = (u or {}).get("progress_tracking_started_date") or ((u or {}).get("progress_tracking") or {}).get("started_date")
3687
  start_date = existing_start or today_str
3688
 
3689
  await users_collection.update_one(
3690
+ {"$or": [{"uid": uid}, {"_id": uid}]},
3691
  {
3692
  "$set": {
3693
  "progress_tracking_enabled": True,
 
3711
  }
3712
  elif act in ("later", "false"):
3713
  await users_collection.update_one(
3714
+ {"$or": [{"uid": uid}, {"_id": uid}]},
3715
  {
3716
  "$set": {
3717
  "progress_tracking_enabled": False,