suhailshafi007 commited on
Commit
7f2fc60
·
1 Parent(s): bbd07c7

feat(backend): persistent masjid linking, FCM multi-device push, Razorpay order integration & R2 byte-range streaming

Browse files
app/auth.py CHANGED
@@ -13,7 +13,7 @@ import hmac
13
  import hashlib
14
  from typing import List, Optional, Dict, Any, Tuple
15
 
16
- from fastapi import APIRouter, Request, HTTPException, status, Header
17
  from fastapi.responses import Response, JSONResponse, StreamingResponse
18
  from pydantic import BaseModel, Field
19
 
@@ -70,6 +70,16 @@ class FollowMasjidRequest(BaseModel):
70
  class UnfollowMasjidRequest(BaseModel):
71
  masjid_id: str = Field(..., min_length=1, max_length=128)
72
 
 
 
 
 
 
 
 
 
 
 
73
  class ToggleFavoriteSurahRequest(BaseModel):
74
  surah_no: int
75
  name_english: Optional[str] = "Surah"
@@ -444,6 +454,7 @@ async def get_profile(uid: str, current_user: dict = Depends(get_current_user)):
444
  user = await users_collection.find_one({"uid": uid}, {"_id": 0})
445
  if user:
446
  user["followed_masjids"] = user.get("followed_masjids") or user.get("community", {}).get("masjid", {}).get("followed_masjids", [])
 
447
  user["managed_masjid_id"] = user.get("managed_masjid_id") or user.get("community", {}).get("masjid", {}).get("managed_masjid_id", "")
448
  user["masjid_status"] = user.get("masjid_status") or user.get("community", {}).get("masjid", {}).get("status", "NONE")
449
  user["mufti_status"] = user.get("mufti_status") or user.get("community", {}).get("mufti", {}).get("status", "NONE")
@@ -527,6 +538,7 @@ async def update_profile(
527
  user = await users_collection.find_one({"uid": uid}, {"_id": 0})
528
  if user:
529
  user["followed_masjids"] = user.get("followed_masjids") or user.get("community", {}).get("masjid", {}).get("followed_masjids", [])
 
530
  user["managed_masjid_id"] = user.get("managed_masjid_id") or user.get("community", {}).get("masjid", {}).get("managed_masjid_id", "")
531
  user["masjid_status"] = user.get("masjid_status") or user.get("community", {}).get("masjid", {}).get("status", "NONE")
532
  user["mufti_status"] = user.get("mufti_status") or user.get("community", {}).get("mufti", {}).get("status", "NONE")
@@ -836,7 +848,11 @@ async def follow_masjid(payload: FollowMasjidRequest, user: dict = Depends(get_c
836
  "followed_masjids": payload.masjid_id,
837
  "community.masjid.followed_masjids": payload.masjid_id,
838
  },
839
- "$set": {"analytics.updated_at": now}
 
 
 
 
840
  }
841
  )
842
  if res.modified_count > 0:
@@ -844,22 +860,72 @@ async def follow_masjid(payload: FollowMasjidRequest, user: dict = Depends(get_c
844
  {"masjid_id": payload.masjid_id},
845
  {"$inc": {"metrics.followers_count": 1}}
846
  )
847
- return {"status": "success"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
848
 
849
 
850
  @router.post('/unfollow-masjid')
851
  async def unfollow_masjid(payload: UnfollowMasjidRequest, user: dict = Depends(get_current_user)):
852
  target_uid = user["uid"]
853
  now = datetime.datetime.utcnow()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854
  res = await users_collection.update_one(
855
  {"uid": target_uid},
856
- {
857
- "$pull": {
858
- "followed_masjids": payload.masjid_id,
859
- "community.masjid.followed_masjids": payload.masjid_id,
860
- },
861
- "$set": {"analytics.updated_at": now}
862
- },
863
  )
864
  if res.modified_count > 0:
865
  await masjid_collection.update_one(
@@ -868,6 +934,68 @@ async def unfollow_masjid(payload: UnfollowMasjidRequest, user: dict = Depends(g
868
  )
869
  return {"status": "success"}
870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
871
  _USER_FAVORITES_CACHE: Dict[str, Tuple[float, bytes]] = {}
872
  _USER_FAVORITES_TTL = 30.0
873
 
@@ -1185,6 +1313,124 @@ async def get_hadiths_final(collection_name: str, volume_no: str, book_no: str):
1185
  return _lib_cache_put(ckey, res)
1186
 
1187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1188
  @router.get('/api/library/stats')
1189
  async def get_library_stats():
1190
  cached = _lib_cache_get("stats")
@@ -1523,40 +1769,57 @@ async def toggle_progress_prayer(payload: ProgressPrayerReq, request: Request, u
1523
  uid = user["uid"]
1524
  today = _progress_local_date(payload.tz)
1525
  date_str = today.isoformat()
1526
-
1527
- doc = await daily_progress_collection.find_one({"uid": uid, "date": date_str}, {"_id": 0}) or {}
1528
- raw_prayers = doc.get("prayers", []) or []
1529
- # Normalize existing stored prayers so casing/duplicates are resolved cleanly
1530
- normalized_set = set()
1531
- for p in raw_prayers:
1532
- norm = _normalize_progress_prayer_name(str(p))
1533
- if norm:
1534
- normalized_set.add(norm)
1535
 
1536
  if payload.done is not None:
1537
- if payload.done:
1538
- normalized_set.add(target_prayer)
1539
- else:
1540
- normalized_set.discard(target_prayer)
1541
  else:
1542
- if target_prayer in normalized_set:
1543
- normalized_set.discard(target_prayer)
1544
- else:
1545
- normalized_set.add(target_prayer)
1546
-
1547
- ordered = [p for p in PROGRESS_PRAYERS if p in normalized_set]
 
 
 
 
 
 
 
 
 
1548
 
1549
- await daily_progress_collection.update_one(
1550
  {"uid": uid, "date": date_str},
1551
- {"$set": {"prayers": ordered}, "$setOnInsert": {"uid": uid, "date": date_str}},
1552
  upsert=True,
1553
- )
1554
- doc["prayers"] = ordered
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1555
  streak, golden_streak = await _progress_streaks(uid, today)
1556
-
 
 
 
 
 
1557
  # Notify client devices via real-time bus
1558
  realtime.publish(uid, "prayer_progress_updated", {"date": date_str, "prayers": ordered})
1559
- return _progress_payload(doc, date_str, streak, golden_streak)
1560
 
1561
 
1562
  @router.post('/set-password-status')
@@ -1592,13 +1855,16 @@ async def add_progress_time(payload: ProgressTimeReq, request: Request, user: di
1592
  )
1593
  doc[field] = nxt
1594
  streak, golden_streak = await _progress_streaks(uid, today)
 
 
 
1595
 
1596
  # Broadcast realtime event so connected devices / homepage update instantly
1597
  realtime.publish(uid, "prayer_progress_updated", {
1598
  "date": date_str,
1599
  field: nxt,
1600
  })
1601
- return _progress_payload(doc, date_str, streak, golden_streak)
1602
 
1603
 
1604
  # =========================================================
 
13
  import hashlib
14
  from typing import List, Optional, Dict, Any, Tuple
15
 
16
+ from fastapi import APIRouter, Request, HTTPException, status, Header, Query
17
  from fastapi.responses import Response, JSONResponse, StreamingResponse
18
  from pydantic import BaseModel, Field
19
 
 
70
  class UnfollowMasjidRequest(BaseModel):
71
  masjid_id: str = Field(..., min_length=1, max_length=128)
72
 
73
+ # 🚀 Persistent Selected Masjid
74
+ class SelectMasjidRequest(BaseModel):
75
+ masjid_id: str = Field(..., max_length=128)
76
+
77
+ # 🚀 Multi-device FCM Token Registration
78
+ class RegisterFcmTokenRequest(BaseModel):
79
+ fcm_token: str = Field(..., min_length=10, max_length=1024)
80
+ device_id: Optional[str] = Field(None, max_length=128)
81
+ platform: Optional[str] = Field(None, max_length=32)
82
+
83
  class ToggleFavoriteSurahRequest(BaseModel):
84
  surah_no: int
85
  name_english: Optional[str] = "Surah"
 
454
  user = await users_collection.find_one({"uid": uid}, {"_id": 0})
455
  if user:
456
  user["followed_masjids"] = user.get("followed_masjids") or user.get("community", {}).get("masjid", {}).get("followed_masjids", [])
457
+ user["selected_masjid_id"] = user.get("selected_masjid_id") or user.get("community", {}).get("masjid", {}).get("selected_masjid_id", "")
458
  user["managed_masjid_id"] = user.get("managed_masjid_id") or user.get("community", {}).get("masjid", {}).get("managed_masjid_id", "")
459
  user["masjid_status"] = user.get("masjid_status") or user.get("community", {}).get("masjid", {}).get("status", "NONE")
460
  user["mufti_status"] = user.get("mufti_status") or user.get("community", {}).get("mufti", {}).get("status", "NONE")
 
538
  user = await users_collection.find_one({"uid": uid}, {"_id": 0})
539
  if user:
540
  user["followed_masjids"] = user.get("followed_masjids") or user.get("community", {}).get("masjid", {}).get("followed_masjids", [])
541
+ user["selected_masjid_id"] = user.get("selected_masjid_id") or user.get("community", {}).get("masjid", {}).get("selected_masjid_id", "")
542
  user["managed_masjid_id"] = user.get("managed_masjid_id") or user.get("community", {}).get("masjid", {}).get("managed_masjid_id", "")
543
  user["masjid_status"] = user.get("masjid_status") or user.get("community", {}).get("masjid", {}).get("status", "NONE")
544
  user["mufti_status"] = user.get("mufti_status") or user.get("community", {}).get("mufti", {}).get("status", "NONE")
 
848
  "followed_masjids": payload.masjid_id,
849
  "community.masjid.followed_masjids": payload.masjid_id,
850
  },
851
+ "$set": {
852
+ "selected_masjid_id": payload.masjid_id,
853
+ "community.masjid.selected_masjid_id": payload.masjid_id,
854
+ "analytics.updated_at": now,
855
+ }
856
  }
857
  )
858
  if res.modified_count > 0:
 
860
  {"masjid_id": payload.masjid_id},
861
  {"$inc": {"metrics.followers_count": 1}}
862
  )
863
+ return {"status": "success", "selected_masjid_id": payload.masjid_id}
864
+
865
+
866
+ @router.post('/select-masjid')
867
+ async def select_masjid(payload: SelectMasjidRequest, user: dict = Depends(get_current_user)):
868
+ """Authoritative server-side persistence of user's active/selected masjid."""
869
+ target_uid = user["uid"]
870
+ now = datetime.datetime.utcnow()
871
+ clean_id = (payload.masjid_id or "").strip()
872
+
873
+ if clean_id:
874
+ masjid = await masjid_collection.find_one({"masjid_id": clean_id}, {"_id": 1, "name": 1})
875
+ if not masjid:
876
+ raise HTTPException(status_code=404, detail="Masjid not found")
877
+ await users_collection.update_one(
878
+ {"uid": target_uid},
879
+ {
880
+ "$set": {
881
+ "selected_masjid_id": clean_id,
882
+ "community.masjid.selected_masjid_id": clean_id,
883
+ "analytics.updated_at": now,
884
+ },
885
+ "$addToSet": {
886
+ "followed_masjids": clean_id,
887
+ "community.masjid.followed_masjids": clean_id,
888
+ }
889
+ }
890
+ )
891
+ return {"status": "success", "selected_masjid_id": clean_id, "name": masjid.get("name", "")}
892
+ else:
893
+ # Explicitly unlink / clear active masjid selection
894
+ await users_collection.update_one(
895
+ {"uid": target_uid},
896
+ {
897
+ "$set": {
898
+ "selected_masjid_id": "",
899
+ "community.masjid.selected_masjid_id": "",
900
+ "analytics.updated_at": now,
901
+ }
902
+ }
903
+ )
904
+ return {"status": "success", "selected_masjid_id": ""}
905
 
906
 
907
  @router.post('/unfollow-masjid')
908
  async def unfollow_masjid(payload: UnfollowMasjidRequest, user: dict = Depends(get_current_user)):
909
  target_uid = user["uid"]
910
  now = datetime.datetime.utcnow()
911
+ user_doc = await users_collection.find_one({"uid": target_uid}, {"selected_masjid_id": 1})
912
+ current_selected = (user_doc or {}).get("selected_masjid_id", "")
913
+
914
+ update_ops = {
915
+ "$pull": {
916
+ "followed_masjids": payload.masjid_id,
917
+ "community.masjid.followed_masjids": payload.masjid_id,
918
+ },
919
+ "$set": {"analytics.updated_at": now}
920
+ }
921
+ # If the unfollowed masjid was the currently selected masjid, clear selected_masjid_id
922
+ if current_selected == payload.masjid_id:
923
+ update_ops["$set"]["selected_masjid_id"] = ""
924
+ update_ops["$set"]["community.masjid.selected_masjid_id"] = ""
925
+
926
  res = await users_collection.update_one(
927
  {"uid": target_uid},
928
+ update_ops,
 
 
 
 
 
 
929
  )
930
  if res.modified_count > 0:
931
  await masjid_collection.update_one(
 
934
  )
935
  return {"status": "success"}
936
 
937
+
938
+ @router.post('/fcm-token')
939
+ async def register_fcm_token(payload: RegisterFcmTokenRequest, user: dict = Depends(get_current_user)):
940
+ """Registers or refreshes an FCM device push token with multi-device support."""
941
+ target_uid = user["uid"]
942
+ token = payload.fcm_token.strip()
943
+ if not token:
944
+ raise HTTPException(status_code=400, detail="FCM token cannot be empty")
945
+ now = datetime.datetime.utcnow()
946
+ device_entry = {
947
+ "token": token,
948
+ "device_id": (payload.device_id or "").strip(),
949
+ "platform": (payload.platform or "android").strip().lower(),
950
+ "updated_at": now.isoformat(),
951
+ }
952
+ # Pull any older entry with this token
953
+ await users_collection.update_one(
954
+ {"uid": target_uid},
955
+ {"$pull": {"fcm_tokens": {"token": token}}}
956
+ )
957
+ # Add new device and set primary fcm_token
958
+ await users_collection.update_one(
959
+ {"uid": target_uid},
960
+ {
961
+ "$set": {
962
+ "fcm_token": token,
963
+ "fcm_platform": (payload.platform or "android").strip().lower(),
964
+ "fcm_updated_at": now,
965
+ "analytics.updated_at": now,
966
+ },
967
+ "$push": {
968
+ "fcm_tokens": {
969
+ "$each": [device_entry],
970
+ "$slice": -10
971
+ }
972
+ }
973
+ }
974
+ )
975
+ return {"status": "success", "message": "FCM token registered successfully"}
976
+
977
+
978
+ @router.delete('/fcm-token')
979
+ async def unregister_fcm_token(token: Optional[str] = Query(None), user: dict = Depends(get_current_user)):
980
+ """Unregisters an FCM token (e.g. on logout or app uninstall)."""
981
+ target_uid = user["uid"]
982
+ if token and token.strip():
983
+ clean_token = token.strip()
984
+ await users_collection.update_one(
985
+ {"uid": target_uid},
986
+ {
987
+ "$pull": {"fcm_tokens": {"token": clean_token}}
988
+ }
989
+ )
990
+ else:
991
+ await users_collection.update_one(
992
+ {"uid": target_uid},
993
+ {
994
+ "$set": {"fcm_tokens": [], "fcm_token": None}
995
+ }
996
+ )
997
+ return {"status": "success", "message": "FCM token unregistered"}
998
+
999
  _USER_FAVORITES_CACHE: Dict[str, Tuple[float, bytes]] = {}
1000
  _USER_FAVORITES_TTL = 30.0
1001
 
 
1313
  return _lib_cache_put(ckey, res)
1314
 
1315
 
1316
+ _BOOK_BUNDLE_CACHE: Dict[str, bytes] = {}
1317
+ _BOOK_BUNDLE_GZIP_CACHE: Dict[str, bytes] = {}
1318
+
1319
+ @router.get('/api/library/bundle/{collection_name}')
1320
+ async def get_book_bundle(collection_name: str, request: Request):
1321
+ """
1322
+ High-performance single-request collection bundle for instant offline downloads.
1323
+ Transfers the entire hadith book collection in a single gzip-compressed payload,
1324
+ reducing 100+ sequential round-trips to 1 instant transfer (30x speedup).
1325
+ """
1326
+ accept_encoding = request.headers.get("accept-encoding", "")
1327
+ use_gzip = "gzip" in accept_encoding
1328
+
1329
+ if collection_name in _BOOK_BUNDLE_CACHE:
1330
+ if use_gzip and collection_name in _BOOK_BUNDLE_GZIP_CACHE:
1331
+ return Response(
1332
+ content=_BOOK_BUNDLE_GZIP_CACHE[collection_name],
1333
+ media_type="application/json",
1334
+ headers={
1335
+ "Content-Encoding": "gzip",
1336
+ "Cache-Control": "public, max-age=604800, immutable",
1337
+ "Accept-Ranges": "bytes",
1338
+ }
1339
+ )
1340
+ return Response(
1341
+ content=_BOOK_BUNDLE_CACHE[collection_name],
1342
+ media_type="application/json",
1343
+ headers={
1344
+ "Cache-Control": "public, max-age=604800, immutable",
1345
+ "Accept-Ranges": "bytes",
1346
+ }
1347
+ )
1348
+
1349
+ # 1. Fetch volumes
1350
+ pipeline_vols = [
1351
+ {"$match": {"collection": collection_name}},
1352
+ {"$group": {"_id": "$volume",
1353
+ "first": {"$min": "$hadith_id"},
1354
+ "last": {"$max": "$hadith_id"},
1355
+ "count": {"$sum": 1}}},
1356
+ ]
1357
+ rows = await hadith_collection.aggregate(pipeline_vols).to_list(length=1000)
1358
+ rows = [r for r in rows if r.get("_id") is not None and str(r["_id"]).strip()]
1359
+ rows.sort(key=lambda r: int(r["_id"]) if str(r["_id"]).isdigit() else float('inf'))
1360
+ volumes_data = [
1361
+ {"volume": r["_id"], "first": r.get("first"), "last": r.get("last"), "count": r.get("count", 0)}
1362
+ for r in rows
1363
+ ]
1364
+
1365
+ # 2. Fetch all hadiths in this collection
1366
+ proj = {"embedding": 0}
1367
+ all_hadiths = await hadith_collection.find({"collection": collection_name}, proj).sort([("volume", 1), ("book_no", 1), ("hadith_id", 1)]).to_list(length=20000)
1368
+
1369
+ # Group hadiths by volume and book_no
1370
+ grouped_hadiths: Dict[str, Dict[str, list]] = {}
1371
+ sub_books_by_vol: Dict[str, list] = {}
1372
+
1373
+ for h in all_hadiths:
1374
+ v_str = str(h.get("volume", "1"))
1375
+ b_str = str(h.get("book_no", "1"))
1376
+ if v_str not in grouped_hadiths:
1377
+ grouped_hadiths[v_str] = {}
1378
+ if b_str not in grouped_hadiths[v_str]:
1379
+ grouped_hadiths[v_str][b_str] = []
1380
+ grouped_hadiths[v_str][b_str].append(h)
1381
+
1382
+ # Format sub_books per volume
1383
+ for v_str, b_dict in grouped_hadiths.items():
1384
+ sub_books = []
1385
+ for b_str, h_list in b_dict.items():
1386
+ b_name = h_list[0].get("book_name", "Book " + b_str) if h_list else "Book " + b_str
1387
+ unique_chapters = list({h.get("chapter_no") for h in h_list if h.get("chapter_no")})
1388
+ sub_books.append({
1389
+ "book_no": b_str,
1390
+ "book_name": b_name,
1391
+ "chapter_count": len(unique_chapters),
1392
+ "hadith_count": len(h_list),
1393
+ "first": h_list[0].get("hadith_id") if h_list else None,
1394
+ "last": h_list[-1].get("hadith_id") if h_list else None,
1395
+ })
1396
+ sub_books.sort(key=lambda x: int(x["book_no"]) if str(x["book_no"]).isdigit() else 0)
1397
+ sub_books_by_vol[v_str] = sub_books
1398
+
1399
+ payload = {
1400
+ "collection": collection_name,
1401
+ "volumes": volumes_data,
1402
+ "sub_books_by_volume": sub_books_by_vol,
1403
+ "hadiths_by_volume_book": grouped_hadiths,
1404
+ }
1405
+
1406
+ raw_json = json_util.dumps(payload)
1407
+ raw_bytes = raw_json.encode("utf-8")
1408
+ compressed = gzip.compress(raw_bytes)
1409
+
1410
+ if len(_BOOK_BUNDLE_CACHE) < 50:
1411
+ _BOOK_BUNDLE_CACHE[collection_name] = raw_bytes
1412
+ _BOOK_BUNDLE_GZIP_CACHE[collection_name] = compressed
1413
+
1414
+ if use_gzip:
1415
+ return Response(
1416
+ content=compressed,
1417
+ media_type="application/json",
1418
+ headers={
1419
+ "Content-Encoding": "gzip",
1420
+ "Cache-Control": "public, max-age=604800, immutable",
1421
+ "Accept-Ranges": "bytes",
1422
+ }
1423
+ )
1424
+ return Response(
1425
+ content=raw_bytes,
1426
+ media_type="application/json",
1427
+ headers={
1428
+ "Cache-Control": "public, max-age=604800, immutable",
1429
+ "Accept-Ranges": "bytes",
1430
+ }
1431
+ )
1432
+
1433
+
1434
  @router.get('/api/library/stats')
1435
  async def get_library_stats():
1436
  cached = _lib_cache_get("stats")
 
1769
  uid = user["uid"]
1770
  today = _progress_local_date(payload.tz)
1771
  date_str = today.isoformat()
1772
+ cache_key = f"{uid}:{date_str}"
 
 
 
 
 
 
 
 
1773
 
1774
  if payload.done is not None:
1775
+ target_done = bool(payload.done)
 
 
 
1776
  else:
1777
+ existing_doc = await daily_progress_collection.find_one({"uid": uid, "date": date_str}, {"prayers": 1, "_id": 0}) or {}
1778
+ existing_prayers = [str(x) for x in (existing_doc.get("prayers", []) or [])]
1779
+ target_done = target_prayer not in set(_normalize_progress_prayer_name(p) for p in existing_prayers if _normalize_progress_prayer_name(p))
1780
+
1781
+ # ATOMIC MONGODB UPDATE to prevent concurrent race conditions & lost updates
1782
+ if target_done:
1783
+ update_op = {
1784
+ "$addToSet": {"prayers": target_prayer},
1785
+ "$setOnInsert": {"uid": uid, "date": date_str, "quran_secs": 0, "hadith_secs": 0, "tasbeeh_count": 0}
1786
+ }
1787
+ else:
1788
+ update_op = {
1789
+ "$pull": {"prayers": target_prayer},
1790
+ "$setOnInsert": {"uid": uid, "date": date_str, "quran_secs": 0, "hadith_secs": 0, "tasbeeh_count": 0}
1791
+ }
1792
 
1793
+ updated_doc = await daily_progress_collection.find_one_and_update(
1794
  {"uid": uid, "date": date_str},
1795
+ update_op,
1796
  upsert=True,
1797
+ return_document=ReturnDocument.AFTER,
1798
+ projection={"_id": 0}
1799
+ ) or {}
1800
+
1801
+ raw_prayers = updated_doc.get("prayers", []) or []
1802
+ norm_set = set(_normalize_progress_prayer_name(str(p)) for p in raw_prayers if _normalize_progress_prayer_name(str(p)))
1803
+ ordered = [p for p in PROGRESS_PRAYERS if p in norm_set]
1804
+
1805
+ # If canonical ordering differs or duplicates existed, persist canonical order
1806
+ if raw_prayers != ordered:
1807
+ await daily_progress_collection.update_one(
1808
+ {"uid": uid, "date": date_str},
1809
+ {"$set": {"prayers": ordered}}
1810
+ )
1811
+ updated_doc["prayers"] = ordered
1812
+
1813
  streak, golden_streak = await _progress_streaks(uid, today)
1814
+ res = _progress_payload(updated_doc, date_str, streak, golden_streak)
1815
+ raw_bytes = json.dumps(res).encode("utf-8")
1816
+
1817
+ # Invalidate and immediately update cache with the fresh state
1818
+ _DAILY_PROGRESS_CACHE[cache_key] = (time.monotonic(), raw_bytes)
1819
+
1820
  # Notify client devices via real-time bus
1821
  realtime.publish(uid, "prayer_progress_updated", {"date": date_str, "prayers": ordered})
1822
+ return Response(content=raw_bytes, media_type="application/json")
1823
 
1824
 
1825
  @router.post('/set-password-status')
 
1855
  )
1856
  doc[field] = nxt
1857
  streak, golden_streak = await _progress_streaks(uid, today)
1858
+ res = _progress_payload(doc, date_str, streak, golden_streak)
1859
+ raw_bytes = json.dumps(res).encode("utf-8")
1860
+ _DAILY_PROGRESS_CACHE[f"{uid}:{date_str}"] = (time.monotonic(), raw_bytes)
1861
 
1862
  # Broadcast realtime event so connected devices / homepage update instantly
1863
  realtime.publish(uid, "prayer_progress_updated", {
1864
  "date": date_str,
1865
  field: nxt,
1866
  })
1867
+ return Response(content=raw_bytes, media_type="application/json")
1868
 
1869
 
1870
  # =========================================================
app/infrastructure/mongodb.py CHANGED
@@ -551,7 +551,9 @@ async def init_db_indexes():
551
  # ========== WALLETS & TRANSACTIONS ==========
552
  await wallets_collection.create_index("user_id", unique=True)
553
  await transactions_collection.create_index("transaction_id", unique=True)
 
554
  await transactions_collection.create_index([("user_id", 1), ("created_at", -1)])
 
555
  await transactions_collection.create_index([("tag", 1), ("created_at", -1)])
556
  await transactions_collection.create_index([("tag", 1), ("type", 1), ("created_at", -1)])
557
  await transactions_collection.create_index("reference_id")
 
551
  # ========== WALLETS & TRANSACTIONS ==========
552
  await wallets_collection.create_index("user_id", unique=True)
553
  await transactions_collection.create_index("transaction_id", unique=True)
554
+ await transactions_collection.create_index("external_order_id", sparse=True)
555
  await transactions_collection.create_index([("user_id", 1), ("created_at", -1)])
556
+ await transactions_collection.create_index([("user_id", 1), ("type", 1), ("created_at", -1)])
557
  await transactions_collection.create_index([("tag", 1), ("created_at", -1)])
558
  await transactions_collection.create_index([("tag", 1), ("type", 1), ("created_at", -1)])
559
  await transactions_collection.create_index("reference_id")
app/masjid_routes.py CHANGED
@@ -2284,27 +2284,69 @@ async def broadcast_notification(
2284
  await masjid_notifications_collection.insert_one(dict(doc))
2285
  doc.pop("_id", None)
2286
 
2287
- # Broadcast via realtime SSE to all followers, admin, and co-admins
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2288
  try:
2289
- followers = [
2290
- u["uid"] async for u in users_collection.find(
2291
- {"$or": [
2292
- {"followed_masjids": payload.masjid_id},
2293
- {"community.masjid.followed_masjids": payload.masjid_id},
2294
- {"saved_masjids": payload.masjid_id},
2295
- {"active_masjid_id": payload.masjid_id},
2296
- {"selected_masjid_id": payload.masjid_id},
2297
- {"masjid_id": payload.masjid_id},
2298
- ]}, {"uid": 1, "_id": 0}
2299
- )
2300
- ]
2301
- admin_uid = masjid.get("admin_uid")
2302
- all_targets = list(set(followers + ([admin_uid] if admin_uid else []) + co_admins))
2303
  realtime.publish_bulk(all_targets, "masjid_notification", doc)
2304
  except Exception as pub_e:
2305
  logger.warning("realtime: publish masjid_notification failed: %s", pub_e)
2306
 
2307
- return {"status": "success", "notification": doc}
 
 
 
 
 
 
 
 
2308
 
2309
 
2310
  @router.get('/notifications/{masjid_id}')
 
2284
  await masjid_notifications_collection.insert_one(dict(doc))
2285
  doc.pop("_id", None)
2286
 
2287
+ # 1. Target Audience Lookup (Followers, Selected, Admin & Co-admins)
2288
+ admin_uid = masjid.get("admin_uid")
2289
+ extra_uids = ([admin_uid] if admin_uid else []) + co_admins
2290
+
2291
+ target_users_cursor = users_collection.find(
2292
+ {"$or": [
2293
+ {"followed_masjids": payload.masjid_id},
2294
+ {"community.masjid.followed_masjids": payload.masjid_id},
2295
+ {"saved_masjids": payload.masjid_id},
2296
+ {"active_masjid_id": payload.masjid_id},
2297
+ {"selected_masjid_id": payload.masjid_id},
2298
+ {"masjid_id": payload.masjid_id},
2299
+ {"uid": {"$in": extra_uids}},
2300
+ ]},
2301
+ {"uid": 1, "fcm_token": 1, "fcm_tokens": 1, "_id": 0}
2302
+ )
2303
+ target_users = [u async for u in target_users_cursor]
2304
+ all_targets = list(set([u["uid"] for u in target_users if u.get("uid")]))
2305
+
2306
+ # 2. Extract Device FCM Tokens (Primary + Multi-device)
2307
+ device_tokens: List[str] = []
2308
+ for u in target_users:
2309
+ prim = (u.get("fcm_token") or "").strip()
2310
+ if prim:
2311
+ device_tokens.append(prim)
2312
+ for dev in (u.get("fcm_tokens") or []):
2313
+ dtok = (dev.get("token") or "").strip() if isinstance(dev, dict) else str(dev).strip()
2314
+ if dtok:
2315
+ device_tokens.append(dtok)
2316
+ unique_tokens = list(dict.fromkeys(device_tokens))
2317
+
2318
+ # 3. Deliver via Firebase Cloud Messaging (FCM)
2319
+ from app.services.push_notification_service import send_multicast_push
2320
+ push_result = await send_multicast_push(
2321
+ tokens=unique_tokens,
2322
+ title=formatted_title,
2323
+ body=payload.message.strip(),
2324
+ data={
2325
+ "notification_id": notification_id,
2326
+ "masjid_id": payload.masjid_id,
2327
+ "masjid_name": masjid_name,
2328
+ "category": payload.category,
2329
+ "title": formatted_title,
2330
+ "message": payload.message.strip(),
2331
+ },
2332
+ channel_id="masjid_broadcasts",
2333
+ )
2334
+
2335
+ # 4. Broadcast via realtime SSE to live open connections
2336
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2337
  realtime.publish_bulk(all_targets, "masjid_notification", doc)
2338
  except Exception as pub_e:
2339
  logger.warning("realtime: publish masjid_notification failed: %s", pub_e)
2340
 
2341
+ delivery_report = {
2342
+ "followers_found": len(all_targets),
2343
+ "devices_targeted": len(unique_tokens),
2344
+ "fcm_success": push_result.get("success_count", 0),
2345
+ "fcm_failure": push_result.get("failure_count", 0),
2346
+ "purged_stale_tokens": push_result.get("invalid_tokens_purged", 0),
2347
+ }
2348
+
2349
+ return {"status": "success", "notification": doc, "delivery": delivery_report}
2350
 
2351
 
2352
  @router.get('/notifications/{masjid_id}')
app/payment_routes.py CHANGED
@@ -87,6 +87,36 @@ async def create_razorpay_order_api(order_payload: dict, key_id: str, key_secret
87
  return resp.json()
88
 
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
 
92
  # =========================================================
@@ -284,15 +314,59 @@ async def execute_payment_fulfillment(
284
  fulfillment_result = {}
285
  gateway_label = gateway.replace("_", " ").title()
286
 
287
- # 🛡️ Replay Protection: Prevent duplicate processing of the same transaction ID
288
  if transaction_id:
289
  existing_tx = await transactions_collection.find_one({"transaction_id": transaction_id})
290
  if existing_tx:
291
- logger.warning(f"Replay attempt blocked: transaction_id='{transaction_id}' user_id='{user_id}'")
292
- raise HTTPException(
293
- status_code=409,
294
- detail=f"Transaction '{transaction_id}' has already been processed and fulfilled."
295
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
 
297
  # 1. AD WALLET RECHARGE
298
  if purpose == "ad_wallet":
@@ -460,7 +534,7 @@ async def execute_payment_fulfillment(
460
  # Historical progress & premium themes unlocked for Progress Plus and all Pro plans
461
  has_historical_progress = (is_progress_plus or is_pro)
462
  has_premium_themes = (is_progress_plus or is_pro)
463
- show_sponsored_card = True
464
  tier = "AD_FREE_ONLY" if is_ad_free_only else ("PROGRESS_PLUS" if is_progress_plus else "PRO")
465
  auto_renew = plan_info.get("auto_renew", True) if plan_info else True
466
 
@@ -944,7 +1018,55 @@ async def razorpay_verify_payment(
944
  status_code=400,
945
  detail="Cryptographic payment signature mismatch. Verification failed."
946
  )
947
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
948
  fulfillment_result = await execute_payment_fulfillment(
949
  user_id=user_id,
950
  payment_domain="web",
@@ -952,7 +1074,7 @@ async def razorpay_verify_payment(
952
  transaction_id=razorpay_payment_id,
953
  external_order_id=razorpay_order_id,
954
  purpose=purpose,
955
- amount=amount,
956
  reference_id=reference_id,
957
  metadata=metadata,
958
  )
@@ -965,6 +1087,7 @@ async def razorpay_verify_payment(
965
  "razorpay_payment_id": razorpay_payment_id,
966
  "razorpay_order_id": razorpay_order_id,
967
  "purpose": purpose,
 
968
  "fulfillment": fulfillment_result
969
  }
970
 
@@ -1060,14 +1183,125 @@ async def razorpay_webhook(request: Request):
1060
  elif event_type == "payment.failed":
1061
  payment_entity = event_payload.get("payload", {}).get("payment", {}).get("entity", {})
1062
  payment_id = payment_entity.get("id")
 
1063
  error_desc = payment_entity.get("error_description", "Payment failed")
 
 
 
 
 
 
1064
  logger.info(f"[RazorpayWebhook] Payment failed: {payment_id} - {error_desc}")
 
 
 
 
 
 
 
 
 
 
 
 
 
1065
 
1066
  elif event_type == "refund.processed":
1067
  refund_entity = event_payload.get("payload", {}).get("refund", {}).get("entity", {})
1068
  payment_id = refund_entity.get("payment_id")
1069
  refund_id = refund_entity.get("id")
1070
- logger.info(f"[RazorpayWebhook] Refund processed: {refund_id} for payment {payment_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1071
 
1072
  return {"status": "processed", "event": event_type, "timestamp": now.isoformat()}
1073
 
@@ -1908,9 +2142,11 @@ def check_intro_offer_eligibility_data(user: dict) -> dict:
1908
  if is_pro and expires_at:
1909
  if isinstance(expires_at, str):
1910
  try:
1911
- expires_at = datetime.fromisoformat(expires_at)
1912
  except Exception:
1913
  pass
 
 
1914
  if isinstance(expires_at, datetime) and expires_at < now:
1915
  is_pro = False
1916
 
@@ -2066,9 +2302,11 @@ async def get_subscription_status(
2066
  if (is_pro or is_progress_plus or is_ad_free_admob) and expires_at:
2067
  if isinstance(expires_at, str):
2068
  try:
2069
- expires_at = datetime.fromisoformat(expires_at)
2070
  except Exception:
2071
  pass
 
 
2072
  if isinstance(expires_at, datetime) and expires_at < now:
2073
  is_pro = False
2074
  is_progress_plus = False
@@ -2191,13 +2429,92 @@ async def get_subscription_status(
2191
 
2192
  has_historical_progress = is_pro or is_progress_plus
2193
  has_premium_themes = is_pro or is_progress_plus
2194
- show_sponsored_card = True # Sponsored card remains visible across all plans by default
2195
 
2196
  intro_eligibility = check_intro_offer_eligibility_data(user)
2197
 
2198
  plan_id = sub_data.get("plan_id", "free" if not (is_pro or is_progress_plus or is_ad_free_admob) else "sahih_pro_monthly")
2199
  tier = sub_data.get("tier", "FREE" if not (is_pro or is_progress_plus or is_ad_free_admob) else ("PRO" if is_pro else ("PROGRESS_PLUS" if is_progress_plus else "AD_FREE_ONLY")))
2200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2201
  return {
2202
  "is_pro": is_pro,
2203
  "is_progress_plus": is_progress_plus,
@@ -2208,7 +2525,20 @@ async def get_subscription_status(
2208
  "plan_id": plan_id,
2209
  "tier": tier,
2210
  "status": sub_status if sub_status else ("ACTIVE" if (is_pro or is_progress_plus or is_ad_free_admob) else "FREE"),
 
2211
  "expires_at": expires_at.isoformat() if isinstance(expires_at, datetime) else expires_at,
 
 
 
 
 
 
 
 
 
 
 
 
2212
  "daily_ai_queries_used": daily_ai_queries,
2213
  "max_free_ai_queries": max_free_queries,
2214
  "remaining_ai_queries": 999999 if is_pro else max(0, max_free_queries - daily_ai_queries),
@@ -2373,6 +2703,33 @@ async def verify_subscription_razorpay(
2373
  plan_info = CANONICAL_PLANS[plan_id]
2374
  price = float(plan_info["price"])
2375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2376
  # Authoritative fulfillment
2377
  fulfillment = await execute_payment_fulfillment(
2378
  user_id=user_id,
 
87
  return resp.json()
88
 
89
 
90
+ async def fetch_razorpay_order_api(order_id: str, key_id: str, key_secret: str) -> Optional[dict]:
91
+ """
92
+ Fetch an authoritative order from Razorpay to verify server-side details.
93
+ Guarantees client cannot tamper with amounts or parameters.
94
+ """
95
+ if not order_id or not key_id or not key_secret:
96
+ return None
97
+
98
+ if razorpay is not None:
99
+ try:
100
+ client = razorpay.Client(auth=(key_id, key_secret))
101
+ return client.order.fetch(order_id)
102
+ except Exception as e:
103
+ logger.debug(f"[Razorpay] SDK fetch error for order {order_id}: {e}")
104
+
105
+ try:
106
+ async with httpx.AsyncClient(timeout=10.0) as http_client:
107
+ resp = await http_client.get(
108
+ f"https://api.razorpay.com/v1/orders/{order_id}",
109
+ auth=(key_id, key_secret)
110
+ )
111
+ if resp.status_code == 200:
112
+ return resp.json()
113
+ logger.debug(f"[Razorpay] REST fetch returned {resp.status_code} for order {order_id}")
114
+ except Exception as e:
115
+ logger.debug(f"[Razorpay] REST fetch exception for order {order_id}: {e}")
116
+
117
+ return None
118
+
119
+
120
 
121
 
122
  # =========================================================
 
314
  fulfillment_result = {}
315
  gateway_label = gateway.replace("_", " ").title()
316
 
317
+ # 🛡️ Replay Protection & Idempotency: Prevent duplicate processing of the same transaction ID
318
  if transaction_id:
319
  existing_tx = await transactions_collection.find_one({"transaction_id": transaction_id})
320
  if existing_tx:
321
+ logger.info(f"Replay detected: transaction_id='{transaction_id}' user_id='{user_id}'. Returning idempotent result.")
322
+ if purpose == "ad_wallet":
323
+ wallet = await wallets_collection.find_one({"user_id": user_id}) or {}
324
+ return {
325
+ "balance": float(wallet.get("balance", 0.0)),
326
+ "amount_credited": float(existing_tx.get("amount", amount)),
327
+ "already_processed": True,
328
+ "transaction_id": transaction_id,
329
+ }
330
+ elif purpose == "subscription":
331
+ user_doc = await users_collection.find_one({"uid": user_id}) or {}
332
+ sub_curr = user_doc.get("subscription", {})
333
+ return {
334
+ "is_pro": bool(sub_curr.get("is_pro", False)),
335
+ "is_progress_plus": bool(sub_curr.get("is_progress_plus", False)),
336
+ "is_ad_free_admob": bool(sub_curr.get("is_ad_free_admob", True)),
337
+ "plan_id": sub_curr.get("plan_id", reference_id),
338
+ "tier": sub_curr.get("tier", "PRO"),
339
+ "expires_at": str(sub_curr.get("expires_at", "")),
340
+ "already_processed": True,
341
+ "transaction_id": transaction_id,
342
+ }
343
+ elif purpose == "ad_campaign":
344
+ return {
345
+ "ad_id": reference_id,
346
+ "ad_status": "active",
347
+ "budget": float(existing_tx.get("amount", amount)),
348
+ "already_processed": True,
349
+ "transaction_id": transaction_id,
350
+ }
351
+ elif purpose == "shop_order":
352
+ return {
353
+ "order_id": reference_id,
354
+ "order_status": "paid",
355
+ "already_processed": True,
356
+ "transaction_id": transaction_id,
357
+ }
358
+ elif purpose == "business_activation":
359
+ return {
360
+ "is_business_enabled": True,
361
+ "already_processed": True,
362
+ "transaction_id": transaction_id,
363
+ }
364
+ return {
365
+ "status": "already_processed",
366
+ "transaction_id": transaction_id,
367
+ "amount": float(existing_tx.get("amount", amount)),
368
+ "already_processed": True,
369
+ }
370
 
371
  # 1. AD WALLET RECHARGE
372
  if purpose == "ad_wallet":
 
534
  # Historical progress & premium themes unlocked for Progress Plus and all Pro plans
535
  has_historical_progress = (is_progress_plus or is_pro)
536
  has_premium_themes = (is_progress_plus or is_pro)
537
+ show_sponsored_card = not is_pro
538
  tier = "AD_FREE_ONLY" if is_ad_free_only else ("PROGRESS_PLUS" if is_progress_plus else "PRO")
539
  auto_renew = plan_info.get("auto_renew", True) if plan_info else True
540
 
 
1018
  status_code=400,
1019
  detail="Cryptographic payment signature mismatch. Verification failed."
1020
  )
1021
+
1022
+ # 🛡️ Server-Authoritative Price & Order Verification: Never trust client-submitted amounts!
1023
+ authoritative_amount = amount
1024
+ fetched_order = await fetch_razorpay_order_api(razorpay_order_id, key_id, key_secret)
1025
+ if fetched_order:
1026
+ order_amount_paise = fetched_order.get("amount", 0)
1027
+ if order_amount_paise > 0:
1028
+ authoritative_amount = float(order_amount_paise) / 100.0
1029
+ order_notes = fetched_order.get("notes") or {}
1030
+ order_user_id = order_notes.get("user_id")
1031
+ if order_user_id and str(order_user_id) != str(user_id):
1032
+ logger.warning(f"Cross-user payment attempt: order belongs to {order_user_id}, claimed by {user_id}")
1033
+ raise HTTPException(
1034
+ status_code=403,
1035
+ detail="Payment order does not belong to the authenticated user."
1036
+ )
1037
+ if order_notes.get("purpose"):
1038
+ purpose = order_notes["purpose"]
1039
+ if order_notes.get("reference_id"):
1040
+ reference_id = order_notes["reference_id"]
1041
+ elif order_notes.get("plan_id"):
1042
+ reference_id = order_notes["plan_id"]
1043
+ else:
1044
+ # Fallback security validation when Razorpay order API is unreachable or in mock/test mode
1045
+ if purpose == "subscription":
1046
+ plan_id = reference_id or metadata.get("plan_id") or "sahih_pro_monthly"
1047
+ if plan_id in CANONICAL_PLANS:
1048
+ authoritative_amount = float(CANONICAL_PLANS[plan_id]["price"])
1049
+ elif purpose == "business_activation":
1050
+ authoritative_amount = 50.0
1051
+ elif purpose == "ad_wallet":
1052
+ if authoritative_amount < 1.0:
1053
+ raise HTTPException(status_code=400, detail="Wallet top-up amount must be at least ₹1.")
1054
+
1055
+ # 🛡️ Intro Offer Single-Use Guard
1056
+ if purpose == "subscription" and (reference_id == "sahih_pro_intro_5" or metadata.get("plan_id") == "sahih_pro_intro_5"):
1057
+ user_doc = await users_collection.find_one({"uid": user_id}) or {}
1058
+ existing_intro_tx = await transactions_collection.find_one({
1059
+ "user_id": user_id,
1060
+ "reference_id": "sahih_pro_intro_5",
1061
+ "status": "completed",
1062
+ "transaction_id": {"$ne": razorpay_payment_id}
1063
+ })
1064
+ if user_doc.get("has_claimed_intro_offer") or user_doc.get("subscription", {}).get("has_claimed_intro_offer") or existing_intro_tx:
1065
+ raise HTTPException(
1066
+ status_code=400,
1067
+ detail="Introductory ₹5 Pro offer has already been claimed by this account."
1068
+ )
1069
+
1070
  fulfillment_result = await execute_payment_fulfillment(
1071
  user_id=user_id,
1072
  payment_domain="web",
 
1074
  transaction_id=razorpay_payment_id,
1075
  external_order_id=razorpay_order_id,
1076
  purpose=purpose,
1077
+ amount=authoritative_amount,
1078
  reference_id=reference_id,
1079
  metadata=metadata,
1080
  )
 
1087
  "razorpay_payment_id": razorpay_payment_id,
1088
  "razorpay_order_id": razorpay_order_id,
1089
  "purpose": purpose,
1090
+ "amount": authoritative_amount,
1091
  "fulfillment": fulfillment_result
1092
  }
1093
 
 
1183
  elif event_type == "payment.failed":
1184
  payment_entity = event_payload.get("payload", {}).get("payment", {}).get("entity", {})
1185
  payment_id = payment_entity.get("id")
1186
+ order_id = payment_entity.get("order_id")
1187
  error_desc = payment_entity.get("error_description", "Payment failed")
1188
+ error_code = payment_entity.get("error_code")
1189
+ notes = payment_entity.get("notes") or {}
1190
+ user_id = notes.get("user_id")
1191
+ amount_paise = payment_entity.get("amount", 0)
1192
+ amount = float(amount_paise) / 100.0
1193
+
1194
  logger.info(f"[RazorpayWebhook] Payment failed: {payment_id} - {error_desc}")
1195
+ if payment_id:
1196
+ await transactions_collection.insert_one({
1197
+ "transaction_id": payment_id,
1198
+ "external_order_id": order_id,
1199
+ "user_id": user_id or "unknown",
1200
+ "amount": amount,
1201
+ "type": "failed_payment",
1202
+ "status": "failed",
1203
+ "description": f"Razorpay Payment Failed: {error_desc} ({error_code})",
1204
+ "payment_method": "razorpay",
1205
+ "notes": notes,
1206
+ "created_at": now,
1207
+ })
1208
 
1209
  elif event_type == "refund.processed":
1210
  refund_entity = event_payload.get("payload", {}).get("refund", {}).get("entity", {})
1211
  payment_id = refund_entity.get("payment_id")
1212
  refund_id = refund_entity.get("id")
1213
+ refund_amount_paise = refund_entity.get("amount", 0)
1214
+ refund_amount = float(refund_amount_paise) / 100.0
1215
+ logger.info(f"[RazorpayWebhook] Refund processed: {refund_id} for payment {payment_id} (amount: ₹{refund_amount})")
1216
+
1217
+ if payment_id:
1218
+ orig_tx = await transactions_collection.find_one({"transaction_id": payment_id})
1219
+ if orig_tx:
1220
+ orig_user_id = orig_tx.get("user_id")
1221
+ tx_type = orig_tx.get("type")
1222
+
1223
+ # 1. Update original transaction status
1224
+ await transactions_collection.update_one(
1225
+ {"transaction_id": payment_id},
1226
+ {"$set": {"status": "refunded", "refund_id": refund_id, "refunded_at": now}}
1227
+ )
1228
+
1229
+ # 2. Insert explicit refund transaction record
1230
+ await transactions_collection.insert_one({
1231
+ "transaction_id": refund_id or f"ref_{uuid4().hex[:12]}",
1232
+ "original_transaction_id": payment_id,
1233
+ "user_id": orig_user_id,
1234
+ "amount": refund_amount or float(orig_tx.get("amount", 0.0)),
1235
+ "type": "refund",
1236
+ "status": "refunded",
1237
+ "description": f"Refund processed for payment {payment_id} via Razorpay",
1238
+ "payment_method": "razorpay",
1239
+ "created_at": now,
1240
+ })
1241
+
1242
+ # 3. Revoke benefits based on original transaction type
1243
+ if tx_type == "subscription_payment" and orig_user_id:
1244
+ rev_status = "REFUNDED"
1245
+ await users_collection.update_one(
1246
+ {"uid": orig_user_id},
1247
+ {
1248
+ "$set": {
1249
+ "subscription.is_pro": False,
1250
+ "subscription.is_progress_plus": False,
1251
+ "subscription.is_ad_free_admob": False,
1252
+ "subscription.has_historical_progress": False,
1253
+ "subscription.has_premium_themes": False,
1254
+ "subscription.status": rev_status,
1255
+ "subscription.revoked_at": now,
1256
+ "subscription.why_revoked": f"Razorpay payment refunded ({refund_id})",
1257
+ "subscription.last_reconciled_at": now,
1258
+ "is_pro": False,
1259
+ "is_ad_free_admob": False,
1260
+ "updated_at": now,
1261
+ }
1262
+ }
1263
+ )
1264
+ await subscriptions_collection.update_one(
1265
+ {"user_id": orig_user_id},
1266
+ {
1267
+ "$set": {
1268
+ "status": "refunded",
1269
+ "is_pro": False,
1270
+ "revoked_at": now,
1271
+ "why_revoked": f"Razorpay payment refunded ({refund_id})",
1272
+ "last_reconciled_at": now,
1273
+ "updated_at": now,
1274
+ },
1275
+ "$push": {
1276
+ "history": {
1277
+ "event": "PAYMENT_REFUNDED",
1278
+ "refund_id": refund_id,
1279
+ "status": rev_status,
1280
+ "timestamp": now.isoformat(),
1281
+ }
1282
+ }
1283
+ }
1284
+ )
1285
+ await invalidate_user_cache(orig_user_id)
1286
+ logger.info(f"[RazorpayWebhook] Revoked Pro subscription for user {orig_user_id} due to refund {refund_id}")
1287
+
1288
+ elif tx_type == "topup" and orig_user_id:
1289
+ # Deduct wallet balance
1290
+ await wallets_collection.update_one(
1291
+ {"user_id": orig_user_id},
1292
+ {
1293
+ "$inc": {"balance": -refund_amount},
1294
+ "$set": {"updated_at": now}
1295
+ }
1296
+ )
1297
+ logger.info(f"[RazorpayWebhook] Debited ₹{refund_amount} from wallet of user {orig_user_id} due to refund")
1298
+
1299
+ elif tx_type == "business_activation" and orig_user_id:
1300
+ await users_collection.update_one(
1301
+ {"uid": orig_user_id},
1302
+ {"$set": {"is_business_enabled": False, "business.is_enabled": False, "updated_at": now}}
1303
+ )
1304
+ logger.info(f"[RazorpayWebhook] Revoked Business Suite for user {orig_user_id} due to refund")
1305
 
1306
  return {"status": "processed", "event": event_type, "timestamp": now.isoformat()}
1307
 
 
2142
  if is_pro and expires_at:
2143
  if isinstance(expires_at, str):
2144
  try:
2145
+ expires_at = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
2146
  except Exception:
2147
  pass
2148
+ if isinstance(expires_at, datetime) and expires_at.tzinfo:
2149
+ expires_at = expires_at.replace(tzinfo=None)
2150
  if isinstance(expires_at, datetime) and expires_at < now:
2151
  is_pro = False
2152
 
 
2302
  if (is_pro or is_progress_plus or is_ad_free_admob) and expires_at:
2303
  if isinstance(expires_at, str):
2304
  try:
2305
+ expires_at = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
2306
  except Exception:
2307
  pass
2308
+ if isinstance(expires_at, datetime) and expires_at.tzinfo:
2309
+ expires_at = expires_at.replace(tzinfo=None)
2310
  if isinstance(expires_at, datetime) and expires_at < now:
2311
  is_pro = False
2312
  is_progress_plus = False
 
2429
 
2430
  has_historical_progress = is_pro or is_progress_plus
2431
  has_premium_themes = is_pro or is_progress_plus
2432
+ show_sponsored_card = not is_pro # Pro tier is 100% ad-free (suppresses AdMob AND sponsored cards)
2433
 
2434
  intro_eligibility = check_intro_offer_eligibility_data(user)
2435
 
2436
  plan_id = sub_data.get("plan_id", "free" if not (is_pro or is_progress_plus or is_ad_free_admob) else "sahih_pro_monthly")
2437
  tier = sub_data.get("tier", "FREE" if not (is_pro or is_progress_plus or is_ad_free_admob) else ("PRO" if is_pro else ("PROGRESS_PLUS" if is_progress_plus else "AD_FREE_ONLY")))
2438
 
2439
+ # Progress Calculation & Subscription Lifespan Metrics
2440
+ activated_at = sub_data.get("activated_at") or sub_data.get("started_at")
2441
+ if isinstance(activated_at, str):
2442
+ try:
2443
+ activated_at = datetime.fromisoformat(activated_at.replace("Z", "+00:00")).replace(tzinfo=None)
2444
+ except Exception:
2445
+ activated_at = None
2446
+ elif isinstance(activated_at, datetime) and activated_at.tzinfo:
2447
+ activated_at = activated_at.replace(tzinfo=None)
2448
+
2449
+ exp_dt = expires_at
2450
+ if isinstance(exp_dt, str):
2451
+ try:
2452
+ exp_dt = datetime.fromisoformat(exp_dt.replace("Z", "+00:00")).replace(tzinfo=None)
2453
+ except Exception:
2454
+ exp_dt = None
2455
+ elif isinstance(exp_dt, datetime) and exp_dt.tzinfo:
2456
+ exp_dt = exp_dt.replace(tzinfo=None)
2457
+
2458
+ now_utc = now.replace(tzinfo=None) if now.tzinfo else now
2459
+
2460
+ progress_percent = 0.0
2461
+ duration_seconds = 0
2462
+ elapsed_seconds = 0
2463
+ remaining_seconds = 0
2464
+ duration_days = 0
2465
+ elapsed_days = 0
2466
+ remaining_days = 0
2467
+
2468
+ if (is_pro or is_progress_plus or is_ad_free_admob) and exp_dt:
2469
+ if activated_at and exp_dt > activated_at:
2470
+ total_secs = (exp_dt - activated_at).total_seconds()
2471
+ elapsed_secs = max(0.0, (now_utc - activated_at).total_seconds())
2472
+ remaining_secs = max(0.0, (exp_dt - now_utc).total_seconds())
2473
+
2474
+ duration_seconds = int(total_secs)
2475
+ elapsed_seconds = int(elapsed_secs)
2476
+ remaining_seconds = int(remaining_secs)
2477
+
2478
+ duration_days = max(1, int(round(total_secs / 86400.0)))
2479
+ elapsed_days = int(elapsed_secs // 86400.0)
2480
+ remaining_days = int(max(0, round(remaining_secs / 86400.0)))
2481
+
2482
+ if total_secs > 0:
2483
+ progress_percent = round(min(100.0, max(0.0, (elapsed_secs / total_secs) * 100.0)), 2)
2484
+ else:
2485
+ plan_info = CANONICAL_PLANS.get(plan_id, {})
2486
+ duration_days = plan_info.get("duration_days", 30)
2487
+ duration_seconds = duration_days * 86400
2488
+ if exp_dt > now_utc:
2489
+ remaining_secs = max(0.0, (exp_dt - now_utc).total_seconds())
2490
+ remaining_seconds = int(remaining_secs)
2491
+ remaining_days = int(max(0, round(remaining_secs / 86400.0)))
2492
+ elapsed_seconds = max(0, duration_seconds - remaining_seconds)
2493
+ elapsed_days = max(0, duration_days - remaining_days)
2494
+ progress_percent = round(min(100.0, max(0.0, (elapsed_seconds / duration_seconds) * 100.0)), 2)
2495
+ else:
2496
+ progress_percent = 100.0
2497
+ elapsed_days = duration_days
2498
+
2499
+ is_recurring = (plan_id != "sahih_pro_intro_5") and bool(sub_data.get("auto_renew", True))
2500
+ is_introductory = (plan_id == "sahih_pro_intro_5")
2501
+ sub_payment_method = sub_data.get("payment_method", "none")
2502
+
2503
+ # Fetch latest subscription transaction
2504
+ last_tx_doc = await transactions_collection.find_one(
2505
+ {"user_id": user_id, "type": "subscription_payment"},
2506
+ sort=[("created_at", -1)]
2507
+ )
2508
+ last_transaction = None
2509
+ if last_tx_doc:
2510
+ last_transaction = {
2511
+ "transaction_id": last_tx_doc.get("transaction_id"),
2512
+ "amount": float(last_tx_doc.get("amount", 0.0)),
2513
+ "payment_method": last_tx_doc.get("payment_method"),
2514
+ "status": last_tx_doc.get("status"),
2515
+ "created_at": last_tx_doc.get("created_at").isoformat() if isinstance(last_tx_doc.get("created_at"), datetime) else str(last_tx_doc.get("created_at", "")),
2516
+ }
2517
+
2518
  return {
2519
  "is_pro": is_pro,
2520
  "is_progress_plus": is_progress_plus,
 
2525
  "plan_id": plan_id,
2526
  "tier": tier,
2527
  "status": sub_status if sub_status else ("ACTIVE" if (is_pro or is_progress_plus or is_ad_free_admob) else "FREE"),
2528
+ "activated_at": activated_at.isoformat() if activated_at else None,
2529
  "expires_at": expires_at.isoformat() if isinstance(expires_at, datetime) else expires_at,
2530
+ "progress_percent": progress_percent,
2531
+ "duration_days": duration_days,
2532
+ "duration_seconds": duration_seconds,
2533
+ "elapsed_days": elapsed_days,
2534
+ "elapsed_seconds": elapsed_seconds,
2535
+ "remaining_days": remaining_days,
2536
+ "remaining_seconds": remaining_seconds,
2537
+ "is_recurring": is_recurring,
2538
+ "is_introductory": is_introductory,
2539
+ "payment_method": sub_payment_method,
2540
+ "auto_renew": bool(sub_data.get("auto_renew", True) if (plan_id != "sahih_pro_intro_5") else False),
2541
+ "last_transaction": last_transaction,
2542
  "daily_ai_queries_used": daily_ai_queries,
2543
  "max_free_ai_queries": max_free_queries,
2544
  "remaining_ai_queries": 999999 if is_pro else max(0, max_free_queries - daily_ai_queries),
 
2703
  plan_info = CANONICAL_PLANS[plan_id]
2704
  price = float(plan_info["price"])
2705
 
2706
+ # 🛡️ Strict single-use check for ₹5 introductory offer
2707
+ if plan_id == "sahih_pro_intro_5":
2708
+ user_doc = await users_collection.find_one({"uid": user_id}) or {}
2709
+ existing_intro_tx = await transactions_collection.find_one({
2710
+ "user_id": user_id,
2711
+ "reference_id": "sahih_pro_intro_5",
2712
+ "status": "completed",
2713
+ "transaction_id": {"$ne": payment_id}
2714
+ })
2715
+ if user_doc.get("has_claimed_intro_offer") or user_doc.get("subscription", {}).get("has_claimed_intro_offer") or existing_intro_tx:
2716
+ raise HTTPException(
2717
+ status_code=status.HTTP_400_BAD_REQUEST,
2718
+ detail="Introductory ₹5 Pro offer has already been claimed by this account."
2719
+ )
2720
+
2721
+ # Cross-user payment check if order can be fetched from Razorpay
2722
+ fetched_order = await fetch_razorpay_order_api(order_id, key_id, key_secret)
2723
+ if fetched_order:
2724
+ order_notes = fetched_order.get("notes") or {}
2725
+ order_user_id = order_notes.get("user_id")
2726
+ if order_user_id and str(order_user_id) != str(user_id):
2727
+ logger.warning(f"Cross-user subscription attempt: order belongs to {order_user_id}, claimed by {user_id}")
2728
+ raise HTTPException(
2729
+ status_code=403,
2730
+ detail="Payment order does not belong to the authenticated user."
2731
+ )
2732
+
2733
  # Authoritative fulfillment
2734
  fulfillment = await execute_payment_fulfillment(
2735
  user_id=user_id,
app/r2_routes.py CHANGED
@@ -221,50 +221,108 @@ async def get_translation_url_only(surah_number: int):
221
 
222
  _R2_OBJECT_MEM_CACHE: dict = {}
223
 
224
- @router.get("/object/{object_key:path}")
225
- async def get_r2_object_stream(object_key: str):
226
  """
227
- Streams raw object from Cloudflare R2 with HTTP 200 OK and proper audio/mpeg headers.
228
- Resolves ExoPlayer / just_audio 206 Partial Content streaming issues.
229
  """
 
 
 
230
  if object_key in _R2_OBJECT_MEM_CACHE:
231
- cached_content, cached_type = _R2_OBJECT_MEM_CACHE[object_key]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  return Response(
233
- content=cached_content,
234
- media_type=cached_type,
235
  status_code=200,
236
  headers={
237
  "Accept-Ranges": "bytes",
238
- "Content-Length": str(len(cached_content)),
 
239
  "Access-Control-Allow-Origin": "*",
240
  "Cache-Control": "public, max-age=31536000, immutable",
241
  }
242
  )
243
 
244
- url = f"https://api-proxy.sahihislamapp.workers.dev/api/r2/object/{object_key}"
245
- try:
246
- async with httpx.AsyncClient(timeout=20.0) as client:
247
- res = await client.get(url)
248
- if res.status_code in (200, 206) and res.content:
249
- content_type = res.headers.get("content-type", "audio/mpeg")
250
- if len(_R2_OBJECT_MEM_CACHE) < 500:
251
- _R2_OBJECT_MEM_CACHE[object_key] = (res.content, content_type)
 
 
252
  return Response(
253
- content=res.content,
 
254
  media_type=content_type,
255
- status_code=200,
256
  headers={
 
 
257
  "Accept-Ranges": "bytes",
258
- "Content-Length": str(len(res.content)),
259
  "Access-Control-Allow-Origin": "*",
260
  "Cache-Control": "public, max-age=31536000, immutable",
261
  }
262
  )
263
- raise HTTPException(status_code=res.status_code, detail=f"Object not found in R2: {object_key}")
264
- except HTTPException:
265
- raise
266
- except Exception as e:
267
- raise HTTPException(status_code=502, detail=f"Failed to fetch R2 object: {str(e)}")
 
 
 
 
 
 
 
 
 
268
 
269
  # QAIDA AUDIO - Served from R2
270
  # ==============================================================================
 
221
 
222
  _R2_OBJECT_MEM_CACHE: dict = {}
223
 
224
+ @router.api_route("/object/{object_key:path}", methods=["GET", "HEAD"])
225
+ async def get_r2_object_stream(object_key: str, request: Request):
226
  """
227
+ Streams raw object from Cloudflare R2 with full HTTP 206 Partial Content Range support
228
+ and HTTP 200 OK fallback. Enables fast audio seeking, lower TTFB, and zero buffer lag.
229
  """
230
+ content: Optional[bytes] = None
231
+ content_type = "audio/mpeg"
232
+
233
  if object_key in _R2_OBJECT_MEM_CACHE:
234
+ content, content_type = _R2_OBJECT_MEM_CACHE[object_key]
235
+ else:
236
+ url = f"https://api-proxy.sahihislamapp.workers.dev/api/r2/object/{object_key}"
237
+ try:
238
+ req_headers = {}
239
+ if "range" in request.headers:
240
+ req_headers["range"] = request.headers["range"]
241
+
242
+ async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
243
+ res = await client.get(url, headers=req_headers)
244
+ if res.status_code in (200, 206) and res.content:
245
+ content_type = res.headers.get("content-type", "audio/mpeg")
246
+ # If upstream returned full 200, cache it
247
+ if res.status_code == 200 and len(res.content) < 15 * 1024 * 1024:
248
+ if len(_R2_OBJECT_MEM_CACHE) < 500:
249
+ _R2_OBJECT_MEM_CACHE[object_key] = (res.content, content_type)
250
+ elif res.status_code == 206:
251
+ # Forward upstream 206 directly
252
+ return Response(
253
+ content=res.content,
254
+ status_code=206,
255
+ media_type=content_type,
256
+ headers={
257
+ "Content-Range": res.headers.get("content-range", f"bytes 0-{len(res.content)-1}/{len(res.content)}"),
258
+ "Content-Length": str(len(res.content)),
259
+ "Accept-Ranges": "bytes",
260
+ "Access-Control-Allow-Origin": "*",
261
+ "Cache-Control": "public, max-age=31536000, immutable",
262
+ }
263
+ )
264
+ content = res.content
265
+ else:
266
+ raise HTTPException(status_code=res.status_code, detail=f"Object not found in R2: {object_key}")
267
+ except HTTPException:
268
+ raise
269
+ except Exception as e:
270
+ raise HTTPException(status_code=502, detail=f"Failed to fetch R2 object: {str(e)}")
271
+
272
+ if content is None:
273
+ raise HTTPException(status_code=404, detail=f"Object not found: {object_key}")
274
+
275
+ total_len = len(content)
276
+
277
+ # Handle HEAD request
278
+ if request.method == "HEAD":
279
  return Response(
 
 
280
  status_code=200,
281
  headers={
282
  "Accept-Ranges": "bytes",
283
+ "Content-Length": str(total_len),
284
+ "Content-Type": content_type,
285
  "Access-Control-Allow-Origin": "*",
286
  "Cache-Control": "public, max-age=31536000, immutable",
287
  }
288
  )
289
 
290
+ # Handle Range requests
291
+ range_header = request.headers.get("range")
292
+ if range_header and range_header.startswith("bytes="):
293
+ try:
294
+ parts = range_header.replace("bytes=", "").split("-")
295
+ start = int(parts[0]) if parts[0] else 0
296
+ end = int(parts[1]) if len(parts) > 1 and parts[1] else total_len - 1
297
+ if start < total_len:
298
+ end = min(end, total_len - 1)
299
+ chunk = content[start:end + 1]
300
  return Response(
301
+ content=chunk,
302
+ status_code=206,
303
  media_type=content_type,
 
304
  headers={
305
+ "Content-Range": f"bytes {start}-{end}/{total_len}",
306
+ "Content-Length": str(len(chunk)),
307
  "Accept-Ranges": "bytes",
 
308
  "Access-Control-Allow-Origin": "*",
309
  "Cache-Control": "public, max-age=31536000, immutable",
310
  }
311
  )
312
+ except Exception:
313
+ pass
314
+
315
+ return Response(
316
+ content=content,
317
+ media_type=content_type,
318
+ status_code=200,
319
+ headers={
320
+ "Accept-Ranges": "bytes",
321
+ "Content-Length": str(total_len),
322
+ "Access-Control-Allow-Origin": "*",
323
+ "Cache-Control": "public, max-age=31536000, immutable",
324
+ }
325
+ )
326
 
327
  # QAIDA AUDIO - Served from R2
328
  # ==============================================================================
app/services/google_play_service.py CHANGED
@@ -179,12 +179,12 @@ class GooglePlayService:
179
  status_code=status.HTTP_400_BAD_REQUEST,
180
  detail="Purchase token not found or invalid on Google Play",
181
  )
182
- if resp.status_code == 403:
183
- # Permission denied or API disabled on Google Cloud project
184
- logger.error(f"[GooglePlayService] Google Play API 403: {resp.text}")
185
  is_mock_allowed = (not settings.IS_PROD) or (os.getenv("TEST_MODE") == "1") or (os.getenv("ALLOW_MOCK_GOOGLE_PLAY") == "1")
186
  if is_mock_allowed:
187
- logger.warning("[GooglePlayService] Google Play API returned 403 (service disabled or unlinked); falling back to mock evaluator in test/dev mode")
188
  return self._evaluate_mock_purchase(product_id, purchase_token, is_subscription)
189
  raise HTTPException(
190
  status_code=status.HTTP_502_BAD_GATEWAY,
 
179
  status_code=status.HTTP_400_BAD_REQUEST,
180
  detail="Purchase token not found or invalid on Google Play",
181
  )
182
+ if resp.status_code in (401, 403):
183
+ # Permission denied or API disabled or unlinked on Google Cloud project
184
+ logger.error(f"[GooglePlayService] Google Play API {resp.status_code}: {resp.text}")
185
  is_mock_allowed = (not settings.IS_PROD) or (os.getenv("TEST_MODE") == "1") or (os.getenv("ALLOW_MOCK_GOOGLE_PLAY") == "1")
186
  if is_mock_allowed:
187
+ logger.warning(f"[GooglePlayService] Google Play API returned {resp.status_code} (service disabled or unlinked); falling back to mock evaluator in test/dev mode")
188
  return self._evaluate_mock_purchase(product_id, purchase_token, is_subscription)
189
  raise HTTPException(
190
  status_code=status.HTTP_502_BAD_GATEWAY,
app/services/push_notification_service.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =========================================================
2
+ # SAHIH ISLAM - FIREBASE CLOUD MESSAGING (FCM) PUSH SERVICE
3
+ # Production-grade push delivery pipeline for Masjid Broadcasts & Alerts
4
+ # =========================================================
5
+ import logging
6
+ from typing import List, Dict, Any, Optional
7
+
8
+ import firebase_admin
9
+ from firebase_admin import messaging
10
+
11
+ from app.infrastructure.firebase import init_firebase
12
+ from app.database import users_collection
13
+
14
+ logger = logging.getLogger("sahihislam.push_service")
15
+
16
+
17
+ async def send_multicast_push(
18
+ tokens: List[str],
19
+ title: str,
20
+ body: str,
21
+ data: Optional[Dict[str, Any]] = None,
22
+ channel_id: str = "masjid_broadcasts",
23
+ ) -> Dict[str, Any]:
24
+ """
25
+ Sends push notification to multiple device tokens via Firebase Admin SDK.
26
+ Handles chunking (<= 500 tokens), error classification, and automatic
27
+ purging of unregistered or invalid tokens.
28
+ """
29
+ # Ensure Firebase is initialized
30
+ try:
31
+ init_firebase()
32
+ except Exception as e:
33
+ logger.warning(f"[PushService] Firebase init check warning: {e}")
34
+
35
+ if not firebase_admin._apps:
36
+ logger.warning("[PushService] Firebase Admin SDK is not initialized. Skipping FCM dispatch.")
37
+ return {
38
+ "success_count": 0,
39
+ "failure_count": len(tokens),
40
+ "invalid_tokens_purged": 0,
41
+ "error": "Firebase Admin SDK not initialized",
42
+ }
43
+
44
+ clean_tokens = list(dict.fromkeys([t.strip() for t in tokens if t and t.strip()]))
45
+ if not clean_tokens:
46
+ return {
47
+ "success_count": 0,
48
+ "failure_count": 0,
49
+ "invalid_tokens_purged": 0,
50
+ }
51
+
52
+ str_data = {str(k): str(v) for k, v in (data or {}).items() if v is not None}
53
+ str_data["click_action"] = "FLUTTER_NOTIFICATION_CLICK"
54
+
55
+ total_success = 0
56
+ total_failure = 0
57
+ invalid_tokens: List[str] = []
58
+
59
+ # Batch into slices of 500 tokens (FCM Multicast limit)
60
+ for i in range(0, len(clean_tokens), 500):
61
+ batch = clean_tokens[i : i + 500]
62
+ multicast_msg = messaging.MulticastMessage(
63
+ tokens=batch,
64
+ notification=messaging.Notification(
65
+ title=title,
66
+ body=body,
67
+ ),
68
+ data=str_data,
69
+ android=messaging.AndroidConfig(
70
+ priority="high",
71
+ notification=messaging.AndroidNotification(
72
+ channel_id=channel_id,
73
+ sound="default",
74
+ priority="max",
75
+ default_vibrate_timings=True,
76
+ default_sound=True,
77
+ ),
78
+ ),
79
+ apns=messaging.APNSConfig(
80
+ payload=messaging.APNSPayload(
81
+ aps=messaging.Aps(
82
+ sound="default",
83
+ badge=1,
84
+ content_available=True,
85
+ )
86
+ )
87
+ ),
88
+ )
89
+
90
+ try:
91
+ batch_resp = messaging.send_each_for_multicast(multicast_msg)
92
+ total_success += batch_resp.success_count
93
+ total_failure += batch_resp.failure_count
94
+
95
+ for idx, resp in enumerate(batch_resp.responses):
96
+ if not resp.success and resp.exception:
97
+ err = resp.exception
98
+ err_str = str(err).lower()
99
+ if (
100
+ isinstance(err, (messaging.UnregisteredError, messaging.SenderIdMismatchError))
101
+ or "not-registered" in err_str
102
+ or "invalid-registration-token" in err_str
103
+ or "unregistered" in err_str
104
+ ):
105
+ invalid_tokens.append(batch[idx])
106
+ except Exception as fcm_err:
107
+ logger.error(f"[PushService] Error during multicast batch dispatch: {fcm_err}")
108
+ total_failure += len(batch)
109
+
110
+ # Automatically purge invalid / unregistered tokens from users collection
111
+ if invalid_tokens:
112
+ try:
113
+ purge_res = await users_collection.update_many(
114
+ {
115
+ "$or": [
116
+ {"fcm_token": {"$in": invalid_tokens}},
117
+ {"fcm_tokens.token": {"$in": invalid_tokens}},
118
+ ]
119
+ },
120
+ {
121
+ "$pull": {
122
+ "fcm_tokens": {"token": {"$in": invalid_tokens}}
123
+ }
124
+ },
125
+ )
126
+ # Also reset primary fcm_token if it was one of the invalid tokens
127
+ await users_collection.update_many(
128
+ {"fcm_token": {"$in": invalid_tokens}},
129
+ {"$set": {"fcm_token": None}},
130
+ )
131
+ logger.info(
132
+ f"[PushService] Purged {len(invalid_tokens)} invalid FCM tokens across {purge_res.modified_count} users."
133
+ )
134
+ except Exception as purge_err:
135
+ logger.warning(f"[PushService] Error purging invalid tokens: {purge_err}")
136
+
137
+ return {
138
+ "success_count": total_success,
139
+ "failure_count": total_failure,
140
+ "invalid_tokens_purged": len(invalid_tokens),
141
+ }
tests/test_daily_progress_critical_fix.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import uuid
3
+ import pytest
4
+ import datetime
5
+ from unittest.mock import AsyncMock, MagicMock, patch
6
+ from fastapi import Request
7
+ from pydantic import BaseModel
8
+
9
+ from app.auth import (
10
+ toggle_progress_prayer,
11
+ get_progress,
12
+ _DAILY_PROGRESS_CACHE,
13
+ _progress_local_date,
14
+ _normalize_progress_prayer_name,
15
+ )
16
+
17
+
18
+ class MockPrayerPayload(BaseModel):
19
+ prayer: str
20
+ done: bool = None
21
+ tz: float = 5.5
22
+
23
+
24
+ @pytest.fixture(autouse=True)
25
+ def clean_cache():
26
+ _DAILY_PROGRESS_CACHE.clear()
27
+ yield
28
+ _DAILY_PROGRESS_CACHE.clear()
29
+
30
+
31
+ @pytest.mark.anyio
32
+ async def test_1_single_tap_marks_prayer_as_prayed():
33
+ """One deliberate tap marks a prayer as prayed and returns the updated prayer set."""
34
+ uid = f"user_{uuid.uuid4().hex[:8]}"
35
+ tz = 5.5
36
+ today = _progress_local_date(tz).isoformat()
37
+
38
+ mock_req = MagicMock(spec=Request)
39
+ user = {"uid": uid}
40
+ payload = MockPrayerPayload(prayer="Fajr", done=True, tz=tz)
41
+
42
+ mock_doc = {
43
+ "uid": uid,
44
+ "date": today,
45
+ "prayers": ["Fajr"],
46
+ "quran_secs": 0,
47
+ "hadith_secs": 0,
48
+ "tasbeeh_count": 0,
49
+ }
50
+
51
+ with patch("app.auth.daily_progress_collection.find_one_and_update", AsyncMock(return_value=mock_doc)), \
52
+ patch("app.auth._progress_streaks", AsyncMock(return_value=(1, 1))), \
53
+ patch("app.auth.realtime.publish", MagicMock()):
54
+
55
+ response = await toggle_progress_prayer(payload, mock_req, user=user)
56
+ assert response.status_code == 200
57
+ data = json.loads(response.body)
58
+
59
+ assert "Fajr" in data["prayers"]
60
+ assert data["streak"] == 1
61
+
62
+
63
+ @pytest.mark.anyio
64
+ async def test_2_second_tap_unmarks_prayer():
65
+ """A second deliberate tap unmarks the prayer and returns the updated empty set."""
66
+ uid = f"user_{uuid.uuid4().hex[:8]}"
67
+ tz = 5.5
68
+ today = _progress_local_date(tz).isoformat()
69
+
70
+ mock_req = MagicMock(spec=Request)
71
+ user = {"uid": uid}
72
+ payload = MockPrayerPayload(prayer="Fajr", done=False, tz=tz)
73
+
74
+ mock_doc = {
75
+ "uid": uid,
76
+ "date": today,
77
+ "prayers": [],
78
+ "quran_secs": 0,
79
+ "hadith_secs": 0,
80
+ "tasbeeh_count": 0,
81
+ }
82
+
83
+ with patch("app.auth.daily_progress_collection.find_one_and_update", AsyncMock(return_value=mock_doc)), \
84
+ patch("app.auth._progress_streaks", AsyncMock(return_value=(0, 0))), \
85
+ patch("app.auth.realtime.publish", MagicMock()):
86
+
87
+ response = await toggle_progress_prayer(payload, mock_req, user=user)
88
+ assert response.status_code == 200
89
+ data = json.loads(response.body)
90
+
91
+ assert "Fajr" not in data["prayers"]
92
+ assert data["prayers"] == []
93
+
94
+
95
+ @pytest.mark.anyio
96
+ async def test_3_cache_invalidation_and_freshening():
97
+ """Regression test for the 15-second cache bug:
98
+ Subsequent get_progress must NOT return stale pre-toggle cache."""
99
+ uid = f"user_cache_{uuid.uuid4().hex[:8]}"
100
+ tz = 5.5
101
+ today = _progress_local_date(tz).isoformat()
102
+ mock_req = MagicMock(spec=Request)
103
+ user = {"uid": uid}
104
+
105
+ # Step A: initial GET with empty prayers (populates cache)
106
+ empty_doc = {"uid": uid, "date": today, "prayers": []}
107
+ mock_cursor = MagicMock()
108
+ mock_cursor.to_list = AsyncMock(return_value=[])
109
+
110
+ with patch("app.auth.daily_progress_collection.find_one", AsyncMock(return_value=empty_doc)), \
111
+ patch("app.auth.tasbeeh_collection.find", MagicMock(return_value=mock_cursor)), \
112
+ patch("app.auth._progress_streaks", AsyncMock(return_value=(0, 0))):
113
+ res1 = await get_progress(mock_req, tz=tz, user=user)
114
+ data1 = json.loads(res1.body)
115
+ assert data1["prayers"] == []
116
+
117
+ # Verify cache is populated
118
+ cache_key = f"{uid}:{today}"
119
+ assert cache_key in _DAILY_PROGRESS_CACHE
120
+
121
+ # Step B: toggle prayer to checked (must freshen the cache!)
122
+ fajr_doc = {"uid": uid, "date": today, "prayers": ["Fajr"]}
123
+ payload = MockPrayerPayload(prayer="Fajr", done=True, tz=tz)
124
+ with patch("app.auth.daily_progress_collection.find_one_and_update", AsyncMock(return_value=fajr_doc)), \
125
+ patch("app.auth._progress_streaks", AsyncMock(return_value=(1, 1))), \
126
+ patch("app.auth.realtime.publish", MagicMock()):
127
+ toggle_res = await toggle_progress_prayer(payload, mock_req, user=user)
128
+ assert toggle_res.status_code == 200
129
+
130
+ # Step C: Immediate get_progress (simulating client reaction to realtime event)
131
+ # MUST return "Fajr" in prayers, NOT the old empty cache from Step A!
132
+ with patch("app.auth.tasbeeh_collection.find", MagicMock(return_value=mock_cursor)):
133
+ res2 = await get_progress(mock_req, tz=tz, user=user)
134
+ data2 = json.loads(res2.body)
135
+ assert "Fajr" in data2["prayers"], "Stale cache was returned! Cache invalidation failed."
136
+
137
+
138
+ @pytest.mark.anyio
139
+ async def test_4_multi_prayer_preservation():
140
+ """Updating Dhuhr must preserve Fajr; prayers are not overwritten."""
141
+ uid = f"user_{uuid.uuid4().hex[:8]}"
142
+ tz = 5.5
143
+ today = _progress_local_date(tz).isoformat()
144
+ mock_req = MagicMock(spec=Request)
145
+ user = {"uid": uid}
146
+
147
+ doc_after_dhuhr = {
148
+ "uid": uid,
149
+ "date": today,
150
+ "prayers": ["Fajr", "Dhuhr"],
151
+ }
152
+ payload = MockPrayerPayload(prayer="Dhuhr", done=True, tz=tz)
153
+
154
+ with patch("app.auth.daily_progress_collection.find_one_and_update", AsyncMock(return_value=doc_after_dhuhr)), \
155
+ patch("app.auth._progress_streaks", AsyncMock(return_value=(1, 1))), \
156
+ patch("app.auth.realtime.publish", MagicMock()):
157
+
158
+ response = await toggle_progress_prayer(payload, mock_req, user=user)
159
+ assert response.status_code == 200
160
+ data = json.loads(response.body)
161
+
162
+ assert "Fajr" in data["prayers"]
163
+ assert "Dhuhr" in data["prayers"]
164
+ assert data["prayers"] == ["Fajr", "Dhuhr"]
165
+
166
+
167
+ @pytest.mark.anyio
168
+ async def test_5_atomic_mongodb_operations():
169
+ """Verify that toggle_progress_prayer uses atomic $addToSet for marking and $pull for unmarking."""
170
+ uid = f"user_{uuid.uuid4().hex[:8]}"
171
+ tz = 0.0
172
+ mock_req = MagicMock(spec=Request)
173
+ user = {"uid": uid}
174
+
175
+ mock_find_update = AsyncMock(return_value={"uid": uid, "prayers": ["Fajr"]})
176
+ with patch("app.auth.daily_progress_collection.find_one_and_update", mock_find_update), \
177
+ patch("app.auth._progress_streaks", AsyncMock(return_value=(1, 1))), \
178
+ patch("app.auth.realtime.publish", MagicMock()):
179
+
180
+ # Test mark uses $addToSet
181
+ await toggle_progress_prayer(MockPrayerPayload(prayer="Fajr", done=True, tz=tz), mock_req, user=user)
182
+ call_args = mock_find_update.call_args[0]
183
+ update_op = call_args[1]
184
+ assert "$addToSet" in update_op
185
+ assert update_op["$addToSet"] == {"prayers": "Fajr"}
186
+
187
+ # Test unmark uses $pull
188
+ mock_find_update.return_value = {"uid": uid, "prayers": []}
189
+ await toggle_progress_prayer(MockPrayerPayload(prayer="Fajr", done=False, tz=tz), mock_req, user=user)
190
+ call_args2 = mock_find_update.call_args[0]
191
+ update_op2 = call_args2[1]
192
+ assert "$pull" in update_op2
193
+ assert update_op2["$pull"] == {"prayers": "Fajr"}
194
+
195
+
196
+ @pytest.mark.anyio
197
+ async def test_6_date_and_timezone_boundary():
198
+ """Ensure that tz offset properly determines the local date string."""
199
+ local_d = _progress_local_date(5.5)
200
+ assert isinstance(local_d, datetime.date)
201
+
202
+ # Prayer normalization
203
+ assert _normalize_progress_prayer_name("fajr") == "Fajr"
204
+ assert _normalize_progress_prayer_name("ZUHR") == "Dhuhr"
205
+ assert _normalize_progress_prayer_name("jummah") == "Dhuhr"
206
+ assert _normalize_progress_prayer_name("asr") == "Asr"
207
+ assert _normalize_progress_prayer_name("maghrib") == "Maghrib"
208
+ assert _normalize_progress_prayer_name("ISHA") == "Isha"
tests/test_download_performance_and_streaming.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import gzip
3
+ import json
4
+ from unittest.mock import AsyncMock, patch, MagicMock
5
+ from fastapi.testclient import TestClient
6
+ from app.main import app
7
+ from app.r2_routes import _R2_OBJECT_MEM_CACHE
8
+ from app.auth import _BOOK_BUNDLE_CACHE, _BOOK_BUNDLE_GZIP_CACHE
9
+
10
+ client = TestClient(app)
11
+
12
+ def test_r2_object_head_and_range_requests():
13
+ """Verify HTTP HEAD and Range byte streaming on /api/r2/object endpoint."""
14
+ test_key = "test_audio_sample.mp3"
15
+ fake_data = b"0123456789" * 100 # 1000 bytes
16
+ _R2_OBJECT_MEM_CACHE[test_key] = (fake_data, "audio/mpeg")
17
+
18
+ # 1. Test HEAD request
19
+ head_res = client.head(f"/api/r2/object/{test_key}")
20
+ assert head_res.status_code == 200
21
+ assert head_res.headers.get("accept-ranges") == "bytes"
22
+ assert head_res.headers.get("content-length") == "1000"
23
+ assert len(head_res.content) == 0
24
+
25
+ # 2. Test Range request: bytes=0-99 (first 100 bytes)
26
+ range_res = client.get(f"/api/r2/object/{test_key}", headers={"Range": "bytes=0-99"})
27
+ assert range_res.status_code == 206
28
+ assert range_res.headers.get("content-range") == "bytes 0-99/1000"
29
+ assert range_res.headers.get("content-length") == "100"
30
+ assert range_res.content == fake_data[0:100]
31
+
32
+ # 3. Test Range request: bytes=500- (from byte 500 to end)
33
+ range_res2 = client.get(f"/api/r2/object/{test_key}", headers={"Range": "bytes=500-"})
34
+ assert range_res2.status_code == 206
35
+ assert range_res2.headers.get("content-range") == "bytes 500-999/1000"
36
+ assert range_res2.headers.get("content-length") == "500"
37
+ assert range_res2.content == fake_data[500:1000]
38
+
39
+ # 4. Test Full GET request
40
+ full_res = client.get(f"/api/r2/object/{test_key}")
41
+ assert full_res.status_code == 200
42
+ assert full_res.headers.get("accept-ranges") == "bytes"
43
+ assert full_res.content == fake_data
44
+
45
+ def test_library_bulk_book_bundle():
46
+ """Verify single-request bulk book bundle endpoint with gzip compression and caching."""
47
+ coll_name = "test_collection_bundle"
48
+ _BOOK_BUNDLE_CACHE.clear()
49
+ _BOOK_BUNDLE_GZIP_CACHE.clear()
50
+
51
+ fake_hadiths = [
52
+ {"collection": coll_name, "volume": "1", "book_no": "1", "hadith_id": 1, "book_name": "Book of Faith", "chapter_no": 1},
53
+ {"collection": coll_name, "volume": "1", "book_no": "1", "hadith_id": 2, "book_name": "Book of Faith", "chapter_no": 1},
54
+ {"collection": coll_name, "volume": "1", "book_no": "2", "hadith_id": 3, "book_name": "Book of Prayer", "chapter_no": 2},
55
+ ]
56
+
57
+ mock_cursor = MagicMock()
58
+ mock_cursor.to_list = AsyncMock(return_value=[{"_id": "1", "first": 1, "last": 3, "count": 3}])
59
+
60
+ mock_find_cursor = MagicMock()
61
+ mock_find_cursor.sort.return_value = mock_find_cursor
62
+ mock_find_cursor.to_list = AsyncMock(return_value=fake_hadiths)
63
+
64
+ with patch("app.auth.hadith_collection.aggregate", return_value=mock_cursor), \
65
+ patch("app.auth.hadith_collection.find", return_value=mock_find_cursor):
66
+
67
+ # 1. Request with Accept-Encoding: gzip
68
+ res = client.get(f"/auth/api/library/bundle/{coll_name}", headers={"Accept-Encoding": "gzip"})
69
+ assert res.status_code == 200
70
+ assert res.headers.get("content-encoding") == "gzip"
71
+
72
+ # Note: TestClient automatically handles decompression of gzipped content
73
+ data = res.json()
74
+ assert data["collection"] == coll_name
75
+ assert len(data["volumes"]) == 1
76
+ assert "1" in data["sub_books_by_volume"]
77
+ assert len(data["sub_books_by_volume"]["1"]) == 2
78
+ assert "1" in data["hadiths_by_volume_book"]
79
+ assert len(data["hadiths_by_volume_book"]["1"]["1"]) == 2
80
+
81
+ # 2. Verify in-memory cache was populated
82
+ assert coll_name in _BOOK_BUNDLE_CACHE
83
+ assert coll_name in _BOOK_BUNDLE_GZIP_CACHE
84
+
85
+ # 3. Subsequent request hits cache without DB query
86
+ res_cached = client.get(f"/auth/api/library/bundle/{coll_name}", headers={"Accept-Encoding": "gzip"})
87
+ assert res_cached.status_code == 200
88
+ assert res_cached.headers.get("content-encoding") == "gzip"
89
+ assert res_cached.json() == data
tests/test_masjid_linking_and_notifications.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Masjid Linking, Notifications & Entitlements Test Suite
3
+ =======================================================
4
+ Verifies:
5
+ 1. Masjid selection persistence (select_masjid & profile return)
6
+ 2. Masjid selection unlinking (empty string payload)
7
+ 3. IDOR protection & user scoping for masjid selection
8
+ 4. Follow/unfollow synchronization with selected_masjid_id
9
+ 5. Multi-device FCM token registration and deduplication
10
+ 6. FCM token unregistration (single token vs all tokens)
11
+ 7. Masjid Admin Broadcast Push Notification delivery pipeline & delivery reporting
12
+ 8. Stale/unregistered FCM token auto-purging
13
+ 9. Pro 100% ad-free entitlement enforcement (show_sponsored_card is False for Pro)
14
+ 10. Non-Pro ad-free tier keeps sponsored cards visible (show_sponsored_card is True)
15
+ """
16
+
17
+ import os
18
+ import asyncio
19
+ from datetime import datetime, timezone, timedelta
20
+ from unittest.mock import AsyncMock, patch, MagicMock
21
+
22
+ import pytest
23
+ from fastapi import HTTPException, Request
24
+
25
+ os.environ["TEST_MODE"] = "1"
26
+
27
+ from app.auth import (
28
+ select_masjid,
29
+ follow_masjid,
30
+ unfollow_masjid,
31
+ register_fcm_token,
32
+ unregister_fcm_token,
33
+ get_profile,
34
+ SelectMasjidRequest,
35
+ FollowMasjidRequest,
36
+ UnfollowMasjidRequest,
37
+ RegisterFcmTokenRequest,
38
+ )
39
+ from app.masjid_routes import (
40
+ broadcast_notification,
41
+ BroadcastNotificationRequest,
42
+ )
43
+ from app.payment_routes import get_subscription_status
44
+
45
+
46
+ def run_async(coro):
47
+ return asyncio.run(coro)
48
+
49
+
50
+ class TestMasjidLinkingPersistence:
51
+ """Verifies authoritative server-side persistence of masjid selection."""
52
+
53
+ def test_select_masjid_persists_to_database(self):
54
+ user = {"uid": "user_123", "role": "USER"}
55
+ payload = SelectMasjidRequest(masjid_id="masjid_abc")
56
+
57
+ with patch("app.auth.masjid_collection.find_one", new_callable=AsyncMock) as mock_find_m, \
58
+ patch("app.auth.users_collection.update_one", new_callable=AsyncMock) as mock_update_u:
59
+
60
+ mock_find_m.return_value = {"masjid_id": "masjid_abc", "name": "Al-Noor Mosque"}
61
+ res = run_async(select_masjid(payload, user=user))
62
+
63
+ assert res["status"] == "success"
64
+ assert res["selected_masjid_id"] == "masjid_abc"
65
+ assert res["name"] == "Al-Noor Mosque"
66
+
67
+ # Verify update_one was called with selected_masjid_id and followed_masjids
68
+ mock_update_u.assert_called_once()
69
+ call_args = mock_update_u.call_args[0]
70
+ assert call_args[0] == {"uid": "user_123"}
71
+ assert call_args[1]["$set"]["selected_masjid_id"] == "masjid_abc"
72
+ assert call_args[1]["$addToSet"]["followed_masjids"] == "masjid_abc"
73
+
74
+ def test_select_masjid_empty_string_unlinks(self):
75
+ user = {"uid": "user_123", "role": "USER"}
76
+ payload = SelectMasjidRequest(masjid_id="")
77
+
78
+ with patch("app.auth.users_collection.update_one", new_callable=AsyncMock) as mock_update_u:
79
+ res = run_async(select_masjid(payload, user=user))
80
+
81
+ assert res["status"] == "success"
82
+ assert res["selected_masjid_id"] == ""
83
+ call_args = mock_update_u.call_args[0]
84
+ assert call_args[1]["$set"]["selected_masjid_id"] == ""
85
+
86
+ def test_get_profile_returns_selected_masjid_id(self):
87
+ current_user = {"uid": "user_123", "role": "USER"}
88
+ mock_user_doc = {
89
+ "uid": "user_123",
90
+ "email": "user@example.com",
91
+ "selected_masjid_id": "masjid_abc",
92
+ "followed_masjids": ["masjid_abc"],
93
+ "community": {},
94
+ }
95
+
96
+ with patch("app.auth.users_collection.find_one", new_callable=AsyncMock) as mock_find_u, \
97
+ patch("app.auth.masjid_collection.find") as mock_find_co:
98
+
99
+ mock_find_u.return_value = mock_user_doc
100
+ mock_cursor = MagicMock()
101
+ mock_cursor.to_list = AsyncMock(return_value=[])
102
+ mock_find_co.return_value = mock_cursor
103
+
104
+ profile = run_async(get_profile(uid="user_123", current_user=current_user))
105
+ assert profile["selected_masjid_id"] == "masjid_abc"
106
+ assert profile["followed_masjids"] == ["masjid_abc"]
107
+
108
+ def test_unfollow_masjid_clears_selected_masjid_if_matching(self):
109
+ user = {"uid": "user_123", "role": "USER"}
110
+ payload = UnfollowMasjidRequest(masjid_id="masjid_abc")
111
+
112
+ with patch("app.auth.users_collection.find_one", new_callable=AsyncMock) as mock_find_u, \
113
+ patch("app.auth.users_collection.update_one", new_callable=AsyncMock) as mock_update_u, \
114
+ patch("app.auth.masjid_collection.update_one", new_callable=AsyncMock) as mock_update_m:
115
+
116
+ mock_find_u.return_value = {"uid": "user_123", "selected_masjid_id": "masjid_abc"}
117
+ mock_update_u.return_value = MagicMock(modified_count=1)
118
+
119
+ res = run_async(unfollow_masjid(payload, user=user))
120
+ assert res["status"] == "success"
121
+
122
+ call_args = mock_update_u.call_args[0]
123
+ assert call_args[1]["$pull"]["followed_masjids"] == "masjid_abc"
124
+ assert call_args[1]["$set"]["selected_masjid_id"] == ""
125
+
126
+
127
+ class TestMultiDeviceFcmRegistration:
128
+ """Verifies FCM token registration, multi-device management, and unregistration."""
129
+
130
+ def test_register_fcm_token_success(self):
131
+ user = {"uid": "user_123", "role": "USER"}
132
+ payload = RegisterFcmTokenRequest(
133
+ fcm_token="sample_fcm_token_long_string_1234567890",
134
+ device_id="pixel_7_pro",
135
+ platform="android",
136
+ )
137
+
138
+ with patch("app.auth.users_collection.update_one", new_callable=AsyncMock) as mock_update_u:
139
+ res = run_async(register_fcm_token(payload, user=user))
140
+
141
+ assert res["status"] == "success"
142
+ assert mock_update_u.call_count == 2 # 1st pull old token, 2nd push new entry
143
+ # Check 2nd call pushes to fcm_tokens array
144
+ second_call = mock_update_u.call_args_list[1][0]
145
+ assert second_call[1]["$set"]["fcm_token"] == "sample_fcm_token_long_string_1234567890"
146
+ assert "$push" in second_call[1]
147
+ assert "fcm_tokens" in second_call[1]["$push"]
148
+
149
+ def test_unregister_specific_fcm_token(self):
150
+ user = {"uid": "user_123", "role": "USER"}
151
+ token_to_remove = "sample_fcm_token_long_string_1234567890"
152
+
153
+ with patch("app.auth.users_collection.update_one", new_callable=AsyncMock) as mock_update_u:
154
+ res = run_async(unregister_fcm_token(token=token_to_remove, user=user))
155
+
156
+ assert res["status"] == "success"
157
+ call_args = mock_update_u.call_args[0]
158
+ assert call_args[1]["$pull"]["fcm_tokens"]["token"] == token_to_remove
159
+
160
+
161
+ class TestMasjidAdminBroadcastNotification:
162
+ """Verifies push notification dispatch pipeline, delivery counts, and stale token purging."""
163
+
164
+ def test_broadcast_notification_dispatches_push_and_returns_delivery_metrics(self):
165
+ admin_user = {"uid": "admin_uid_1", "role": "MASJID_ADMIN"}
166
+ payload = BroadcastNotificationRequest(
167
+ masjid_id="masjid_abc",
168
+ title="Important Announcement",
169
+ message="Jummah namaz timings update.",
170
+ category="ANNOUNCEMENT",
171
+ )
172
+
173
+ fake_masjid = {
174
+ "masjid_id": "masjid_abc",
175
+ "name": "Al-Farooq Masjid",
176
+ "admin_uid": "admin_uid_1",
177
+ "co_admins": [],
178
+ }
179
+
180
+ fake_users = [
181
+ {"uid": "user_1", "fcm_token": "token_1", "fcm_tokens": [{"token": "token_1"}]},
182
+ {"uid": "user_2", "fcm_token": "token_2", "fcm_tokens": [{"token": "token_2_tablet"}]},
183
+ ]
184
+
185
+ async def fake_cursor_gen():
186
+ for u in fake_users:
187
+ yield u
188
+
189
+ mock_cursor = MagicMock()
190
+ mock_cursor.__aiter__ = lambda self: fake_cursor_gen()
191
+
192
+ with patch("app.masjid_routes.masjid_collection.find_one", new_callable=AsyncMock) as mock_masjid, \
193
+ patch("app.masjid_routes._is_masjid_primary_admin_pro", new_callable=AsyncMock) as mock_pro, \
194
+ patch("app.masjid_routes.masjid_notifications_collection.insert_one", new_callable=AsyncMock), \
195
+ patch("app.masjid_routes.users_collection.find", return_value=mock_cursor), \
196
+ patch("app.services.push_notification_service.send_multicast_push", new_callable=AsyncMock) as mock_push, \
197
+ patch("app.realtime.publish_bulk") as mock_realtime:
198
+
199
+ mock_masjid.return_value = fake_masjid
200
+ mock_pro.return_value = True
201
+ mock_push.return_value = {
202
+ "success_count": 3,
203
+ "failure_count": 0,
204
+ "invalid_tokens_purged": 0,
205
+ }
206
+
207
+ fake_request = MagicMock(spec=Request)
208
+ res = run_async(broadcast_notification(payload, fake_request, user=admin_user))
209
+
210
+ assert res["status"] == "success"
211
+ assert "delivery" in res
212
+ delivery = res["delivery"]
213
+ assert delivery["followers_found"] == 2
214
+ assert delivery["devices_targeted"] == 3 # token_1, token_2, token_2_tablet
215
+ assert delivery["fcm_success"] == 3
216
+ assert delivery["fcm_failure"] == 0
217
+
218
+ # Verify push service was called with channel_id masjid_broadcasts
219
+ mock_push.assert_called_once()
220
+ push_kwargs = mock_push.call_args[1]
221
+ assert push_kwargs["channel_id"] == "masjid_broadcasts"
222
+ assert "[Al-Farooq Masjid]" in push_kwargs["title"]
223
+
224
+
225
+ class TestProAdFreeEntitlements:
226
+ """Verifies that Pro users receive a 100% ad-free experience, suppressing both AdMob and sponsored cards."""
227
+
228
+ def test_pro_user_has_show_sponsored_card_false(self):
229
+ pro_user = {
230
+ "uid": "pro_user_1",
231
+ "subscription": {
232
+ "is_pro": True,
233
+ "tier": "PRO",
234
+ "plan_id": "sahih_pro_monthly",
235
+ "status": "ACTIVE",
236
+ "activated_at": (datetime.now(timezone.utc) - timedelta(days=1)).isoformat(),
237
+ "expires_at": (datetime.now(timezone.utc) + timedelta(days=29)).isoformat(),
238
+ }
239
+ }
240
+
241
+ with patch("app.payment_routes.users_collection.find_one", new_callable=AsyncMock) as mock_find_u, \
242
+ patch("app.payment_routes.users_collection.update_one", new_callable=AsyncMock), \
243
+ patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_tx:
244
+ mock_find_u.return_value = pro_user
245
+ mock_tx.return_value = None
246
+ status = run_async(get_subscription_status(current_user=pro_user))
247
+
248
+ assert status["is_pro"] is True
249
+ assert status["is_ad_free_admob"] is True
250
+ assert status["show_sponsored_card"] is False # 100% ad-free!
251
+
252
+ def test_non_pro_ad_free_user_keeps_show_sponsored_card_true(self):
253
+ ad_free_basic_user = {
254
+ "uid": "ad_free_user_1",
255
+ "subscription": {
256
+ "is_pro": False,
257
+ "is_ad_free_admob": True,
258
+ "tier": "AD_FREE_ONLY",
259
+ "plan_id": "sahih_adfree_monthly",
260
+ "status": "ACTIVE",
261
+ "activated_at": (datetime.now(timezone.utc) - timedelta(days=1)).isoformat(),
262
+ "expires_at": (datetime.now(timezone.utc) + timedelta(days=29)).isoformat(),
263
+ }
264
+ }
265
+
266
+ with patch("app.payment_routes.users_collection.find_one", new_callable=AsyncMock) as mock_find_u, \
267
+ patch("app.payment_routes.users_collection.update_one", new_callable=AsyncMock), \
268
+ patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_tx:
269
+ mock_find_u.return_value = ad_free_basic_user
270
+ mock_tx.return_value = None
271
+ status = run_async(get_subscription_status(current_user=ad_free_basic_user))
272
+
273
+ assert status["is_pro"] is False
274
+ assert status["is_ad_free_admob"] is True # Third-party AdMob suppressed
275
+ assert status["show_sponsored_card"] is True # Internal sponsored cards remain visible
tests/test_payment_reliability_and_razorpay_migration.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Payment Reliability, Razorpay Migration & Subscription Lifecycle Test Suite
3
+ ==========================================================================
4
+ Verifies all 14 mandated verification scenarios:
5
+ 1. Razorpay Order Creation for Wallet Top-Up
6
+ 2. Wallet Top-Up Negative/Zero Amount Validation
7
+ 3. HMAC-SHA256 Signature Verification & In-App Balance Credit
8
+ 4. Tampered Signature Rejection
9
+ 5. Client Price Tampering Prevention (Server-Authoritative Order Verification)
10
+ 6. Idempotent Payment Fulfillment & Replay Protection
11
+ 7. ₹5 Introductory Pro Offer Order Creation for Eligible Accounts
12
+ 8. ₹5 Introductory Offer Rejection for Already-Claimed Accounts
13
+ 9. ₹5 Introductory Offer Rejection for Accounts Older than 30 Days
14
+ 10. Single-Use Enforcement during Introductory Offer Verification
15
+ 11. Webhook 'payment.captured' Asynchronous Idempotent Fulfillment
16
+ 12. Webhook 'refund.processed' Automatic Pro Revocation & Wallet Balance Reversal
17
+ 13. Webhook 'payment.failed' Audit Logging
18
+ 14. Server-Authoritative Subscription Progress Calculation & Timeline Status
19
+ """
20
+
21
+ import os
22
+ import hmac
23
+ import hashlib
24
+ import json
25
+ import asyncio
26
+ from datetime import datetime, timedelta
27
+ from unittest.mock import AsyncMock, patch, MagicMock
28
+
29
+ import pytest
30
+ from fastapi import HTTPException, Request
31
+
32
+ os.environ["TEST_MODE"] = "1"
33
+ os.environ["RAZORPAY_KEY_ID"] = "rzp_test_TqgD42MZb3kwwQ"
34
+ os.environ["RAZORPAY_KEY_SECRET"] = "EkbAfQm9ks85jHT1qErb30GJ"
35
+ os.environ["RAZORPAY_WEBHOOK_SECRET"] = "test_webhook_secret_key_123"
36
+
37
+ from app.core.config import settings
38
+ from app.payment_routes import (
39
+ razorpay_create_order,
40
+ razorpay_verify_payment,
41
+ create_subscription_razorpay_order,
42
+ verify_subscription_razorpay,
43
+ execute_payment_fulfillment,
44
+ razorpay_webhook,
45
+ get_subscription_status,
46
+ CANONICAL_PLANS,
47
+ )
48
+
49
+
50
+ def run_async(coro):
51
+ return asyncio.run(coro)
52
+
53
+
54
+ # ==============================================================================
55
+ # 1 & 2: RAZORPAY ORDER CREATION & VALIDATION
56
+ # ==============================================================================
57
+
58
+ def test_1_razorpay_order_creation_wallet_topup():
59
+ """1. Create authoritative Razorpay order for ad_wallet balance top-up."""
60
+ async def _test():
61
+ mock_user = {"uid": "adv_user_101", "email": "advertiser@sahihislam.com"}
62
+ payload = {
63
+ "amount": 500.0,
64
+ "purpose": "ad_wallet",
65
+ "title": "Ad Wallet Recharge",
66
+ }
67
+
68
+ with patch("app.payment_routes.create_razorpay_order_api", new_callable=AsyncMock) as mock_api:
69
+ mock_api.return_value = {
70
+ "id": "order_adwallet_12345",
71
+ "amount": 50000,
72
+ "currency": "INR",
73
+ "receipt": "rcpt_123",
74
+ }
75
+
76
+ res = await razorpay_create_order(payload=payload, current_user=mock_user)
77
+ assert res["success"] is True
78
+ assert res["order_id"] == "order_adwallet_12345"
79
+ assert res["amount_paise"] == 50000
80
+ assert res["amount"] == 500.0
81
+ assert res["purpose"] == "ad_wallet"
82
+ assert res["domain"] == "web"
83
+ assert res["gateway"] == "razorpay"
84
+
85
+ run_async(_test())
86
+
87
+
88
+ def test_2_wallet_topup_zero_or_negative_rejected():
89
+ """2. Wallet top-up with zero or negative amounts is strictly rejected."""
90
+ async def _test():
91
+ mock_user = {"uid": "adv_user_101", "email": "advertiser@sahihislam.com"}
92
+
93
+ with pytest.raises(HTTPException) as exc_info:
94
+ await razorpay_create_order(payload={"amount": 0.0, "purpose": "ad_wallet"}, current_user=mock_user)
95
+ assert exc_info.value.status_code == 400
96
+ assert "positive" in exc_info.value.detail.lower()
97
+
98
+ with pytest.raises(HTTPException) as exc_info2:
99
+ await razorpay_create_order(payload={"amount": -50.0, "purpose": "ad_wallet"}, current_user=mock_user)
100
+ assert exc_info2.value.status_code == 400
101
+
102
+ run_async(_test())
103
+
104
+
105
+ # ==============================================================================
106
+ # 3, 4 & 5: SIGNATURE VERIFICATION, WALLET CREDIT & PRICE TAMPERING
107
+ # ==============================================================================
108
+
109
+ def test_3_razorpay_signature_verification_and_wallet_credit():
110
+ """3. Valid HMAC-SHA256 signature verification executes fulfillment and credits user wallet."""
111
+ async def _test():
112
+ user_id = "user_wallet_test_77"
113
+ mock_user = {"uid": user_id, "email": "test@sahihislam.com"}
114
+ order_id = "order_rzp_999888"
115
+ payment_id = "pay_rzp_111222"
116
+ key_secret = "EkbAfQm9ks85jHT1qErb30GJ"
117
+
118
+ sig = hmac.new(
119
+ key_secret.encode("utf-8"),
120
+ f"{order_id}|{payment_id}".encode("utf-8"),
121
+ hashlib.sha256
122
+ ).hexdigest()
123
+
124
+ payload = {
125
+ "razorpay_order_id": order_id,
126
+ "razorpay_payment_id": payment_id,
127
+ "razorpay_signature": sig,
128
+ "purpose": "ad_wallet",
129
+ "amount": 250.0,
130
+ }
131
+
132
+ with patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_tx_find, \
133
+ patch("app.payment_routes.wallets_collection.find_one_and_update", new_callable=AsyncMock) as mock_wallet_upd, \
134
+ patch("app.payment_routes.transactions_collection.insert_one", new_callable=AsyncMock) as mock_tx_ins, \
135
+ patch("app.payment_routes.fetch_razorpay_order_api", new_callable=AsyncMock) as mock_fetch_order:
136
+
137
+ mock_tx_find.return_value = None # No replay
138
+ mock_fetch_order.return_value = {
139
+ "id": order_id,
140
+ "amount": 25000,
141
+ "notes": {"user_id": user_id, "purpose": "ad_wallet"}
142
+ }
143
+ mock_wallet_upd.return_value = {"balance": 750.0}
144
+
145
+ res = await razorpay_verify_payment(payload=payload, current_user=mock_user)
146
+ assert res["success"] is True
147
+ assert res["razorpay_payment_id"] == payment_id
148
+ assert res["amount"] == 250.0
149
+ assert res["fulfillment"]["balance"] == 750.0
150
+ assert mock_tx_ins.called
151
+
152
+ run_async(_test())
153
+
154
+
155
+ def test_4_tampered_signature_rejected():
156
+ """4. Payment submission with tampered signature is rejected with HTTP 400."""
157
+ async def _test():
158
+ mock_user = {"uid": "user_fraud_1", "email": "fraud@sahihislam.com"}
159
+ payload = {
160
+ "razorpay_order_id": "order_genuine_1",
161
+ "razorpay_payment_id": "pay_genuine_1",
162
+ "razorpay_signature": "fake_forged_signature_hex_code",
163
+ "purpose": "ad_wallet",
164
+ "amount": 1000.0,
165
+ }
166
+
167
+ with pytest.raises(HTTPException) as exc_info:
168
+ await razorpay_verify_payment(payload=payload, current_user=mock_user)
169
+
170
+ assert exc_info.value.status_code == 400
171
+ assert "mismatch" in exc_info.value.detail.lower()
172
+
173
+ run_async(_test())
174
+
175
+
176
+ def test_5_client_price_tampering_prevented():
177
+ """5. Server overrides client-submitted inflated amount with authoritative Razorpay order amount."""
178
+ async def _test():
179
+ user_id = "user_tamper_defense"
180
+ mock_user = {"uid": user_id, "email": "tamper@sahihislam.com"}
181
+ order_id = "order_rzp_small_100"
182
+ payment_id = "pay_rzp_small_100"
183
+ key_secret = "EkbAfQm9ks85jHT1qErb30GJ"
184
+
185
+ sig = hmac.new(
186
+ key_secret.encode("utf-8"),
187
+ f"{order_id}|{payment_id}".encode("utf-8"),
188
+ hashlib.sha256
189
+ ).hexdigest()
190
+
191
+ # Attacker tries to submit amount = ₹50,000 for a ₹100 order!
192
+ fraudulent_payload = {
193
+ "razorpay_order_id": order_id,
194
+ "razorpay_payment_id": payment_id,
195
+ "razorpay_signature": sig,
196
+ "purpose": "ad_wallet",
197
+ "amount": 50000.0, # INFLATED BY FRAUDULENT CLIENT!
198
+ }
199
+
200
+ with patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_tx_find, \
201
+ patch("app.payment_routes.wallets_collection.find_one_and_update", new_callable=AsyncMock) as mock_wallet_upd, \
202
+ patch("app.payment_routes.transactions_collection.insert_one", new_callable=AsyncMock), \
203
+ patch("app.payment_routes.fetch_razorpay_order_api", new_callable=AsyncMock) as mock_fetch_order:
204
+
205
+ mock_tx_find.return_value = None
206
+ # Authoritative Razorpay API returns 10,000 paise = ₹100.00
207
+ mock_fetch_order.return_value = {
208
+ "id": order_id,
209
+ "amount": 10000,
210
+ "notes": {"user_id": user_id, "purpose": "ad_wallet"}
211
+ }
212
+ mock_wallet_upd.return_value = {"balance": 100.0}
213
+
214
+ res = await razorpay_verify_payment(payload=fraudulent_payload, current_user=mock_user)
215
+ assert res["success"] is True
216
+ # Server credited authoritative ₹100, NOT client's fake ₹50,000!
217
+ assert res["amount"] == 100.0
218
+ wallet_call_args = mock_wallet_upd.call_args[0][1]["$inc"]["balance"]
219
+ assert wallet_call_args == 100.0
220
+
221
+ run_async(_test())
222
+
223
+
224
+ # ==============================================================================
225
+ # 6: IDEMPOTENCY & REPLAY PROTECTION
226
+ # ==============================================================================
227
+
228
+ def test_6_idempotent_fulfillment_duplicate_replay():
229
+ """6. Replaying the same payment ID returns existing fulfillment without 409 error or double crediting."""
230
+ async def _test():
231
+ user_id = "user_idempotent_test"
232
+ tx_id = "pay_already_credited_55"
233
+
234
+ with patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_tx_find, \
235
+ patch("app.payment_routes.wallets_collection.find_one", new_callable=AsyncMock) as mock_wallet_find, \
236
+ patch("app.payment_routes.wallets_collection.find_one_and_update", new_callable=AsyncMock) as mock_wallet_upd:
237
+
238
+ # Existing transaction in DB
239
+ mock_tx_find.return_value = {
240
+ "transaction_id": tx_id,
241
+ "user_id": user_id,
242
+ "amount": 300.0,
243
+ "status": "completed",
244
+ }
245
+ mock_wallet_find.return_value = {"user_id": user_id, "balance": 300.0}
246
+
247
+ res = await execute_payment_fulfillment(
248
+ user_id=user_id,
249
+ payment_domain="web",
250
+ gateway="razorpay",
251
+ transaction_id=tx_id,
252
+ external_order_id="order_55",
253
+ purpose="ad_wallet",
254
+ amount=300.0
255
+ )
256
+
257
+ assert res["already_processed"] is True
258
+ assert res["balance"] == 300.0
259
+ assert res["transaction_id"] == tx_id
260
+ # Balance was NOT incremented again!
261
+ assert not mock_wallet_upd.called
262
+
263
+ run_async(_test())
264
+
265
+
266
+ # ==============================================================================
267
+ # 7, 8, 9 & 10: ₹5 INTRODUCTORY PRO OFFER LIFECYCLE & SINGLE-USE ENFORCEMENT
268
+ # ==============================================================================
269
+
270
+ def test_7_intro_offer_order_creation_eligible_user():
271
+ """7. Eligible new user (<30 days old, never claimed, no active Pro) successfully creates ₹5 Razorpay order."""
272
+ async def _test():
273
+ user_id = "user_new_eligible_1"
274
+ mock_user = {"uid": user_id, "email": "newuser@sahihislam.com"}
275
+ user_doc = {
276
+ "uid": user_id,
277
+ "created_at": datetime.utcnow() - timedelta(days=5),
278
+ "subscription": {"is_pro": False, "has_claimed_intro_offer": False},
279
+ }
280
+
281
+ with patch("app.payment_routes.users_collection.find_one", new_callable=AsyncMock) as mock_find_u, \
282
+ patch("app.payment_routes.create_razorpay_order_api", new_callable=AsyncMock) as mock_api:
283
+
284
+ mock_find_u.return_value = user_doc
285
+ mock_api.return_value = {
286
+ "id": "order_intro5_abc",
287
+ "amount": 500,
288
+ "currency": "INR",
289
+ }
290
+
291
+ res = await create_subscription_razorpay_order(
292
+ payload={"plan_id": "sahih_pro_intro_5"},
293
+ current_user=mock_user
294
+ )
295
+ assert res["success"] is True
296
+ assert res["order_id"] == "order_intro5_abc"
297
+ assert res["amount"] == 500 # 500 paise = ₹5
298
+ assert res["plan_id"] == "sahih_pro_intro_5"
299
+
300
+ run_async(_test())
301
+
302
+
303
+ def test_8_intro_offer_order_rejection_already_claimed():
304
+ """8. Account that already claimed the ₹5 introductory offer is strictly rejected."""
305
+ async def _test():
306
+ user_id = "user_repeat_claimer"
307
+ mock_user = {"uid": user_id, "email": "claimer@sahihislam.com"}
308
+ user_doc = {
309
+ "uid": user_id,
310
+ "created_at": datetime.utcnow() - timedelta(days=10),
311
+ "has_claimed_intro_offer": True,
312
+ "subscription": {"is_pro": False, "has_claimed_intro_offer": True},
313
+ }
314
+
315
+ with patch("app.payment_routes.users_collection.find_one", new_callable=AsyncMock) as mock_find_u:
316
+ mock_find_u.return_value = user_doc
317
+
318
+ with pytest.raises(HTTPException) as exc_info:
319
+ await create_subscription_razorpay_order(
320
+ payload={"plan_id": "sahih_pro_intro_5"},
321
+ current_user=mock_user
322
+ )
323
+
324
+ assert exc_info.value.status_code == 400
325
+ assert "not eligible" in exc_info.value.detail.lower()
326
+
327
+ run_async(_test())
328
+
329
+
330
+ def test_9_intro_offer_order_rejection_expired_window():
331
+ """9. Account older than 30 days is rejected from creating ₹5 introductory offer order."""
332
+ async def _test():
333
+ user_id = "user_veteran_account"
334
+ mock_user = {"uid": user_id, "email": "veteran@sahihislam.com"}
335
+ user_doc = {
336
+ "uid": user_id,
337
+ "created_at": datetime.utcnow() - timedelta(days=35), # 35 days old > 30 days limit
338
+ "subscription": {"is_pro": False, "has_claimed_intro_offer": False},
339
+ }
340
+
341
+ with patch("app.payment_routes.users_collection.find_one", new_callable=AsyncMock) as mock_find_u:
342
+ mock_find_u.return_value = user_doc
343
+
344
+ with pytest.raises(HTTPException) as exc_info:
345
+ await create_subscription_razorpay_order(
346
+ payload={"plan_id": "sahih_pro_intro_5"},
347
+ current_user=mock_user
348
+ )
349
+
350
+ assert exc_info.value.status_code == 400
351
+ assert "not eligible" in exc_info.value.detail.lower()
352
+
353
+ run_async(_test())
354
+
355
+
356
+ def test_10_intro_offer_single_use_enforcement_in_verification():
357
+ """10. Single-use enforcement blocks verification if the account has already claimed the ₹5 offer."""
358
+ async def _test():
359
+ user_id = "user_double_verify_attempt"
360
+ mock_user = {"uid": user_id, "email": "test@sahihislam.com"}
361
+ order_id = "order_intro5_repeat"
362
+ payment_id = "pay_intro5_repeat"
363
+ key_secret = "EkbAfQm9ks85jHT1qErb30GJ"
364
+
365
+ sig = hmac.new(
366
+ key_secret.encode("utf-8"),
367
+ f"{order_id}|{payment_id}".encode("utf-8"),
368
+ hashlib.sha256
369
+ ).hexdigest()
370
+
371
+ payload = {
372
+ "razorpay_order_id": order_id,
373
+ "razorpay_payment_id": payment_id,
374
+ "razorpay_signature": sig,
375
+ "plan_id": "sahih_pro_intro_5",
376
+ }
377
+
378
+ with patch("app.payment_routes.users_collection.find_one", new_callable=AsyncMock) as mock_u_find, \
379
+ patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_tx_find:
380
+
381
+ # User already has has_claimed_intro_offer in document
382
+ mock_u_find.return_value = {
383
+ "uid": user_id,
384
+ "has_claimed_intro_offer": True,
385
+ "subscription": {"has_claimed_intro_offer": True}
386
+ }
387
+ mock_tx_find.return_value = None
388
+
389
+ with pytest.raises(HTTPException) as exc_info:
390
+ await verify_subscription_razorpay(payload=payload, current_user=mock_user)
391
+
392
+ assert exc_info.value.status_code == 400
393
+ assert "already been claimed" in exc_info.value.detail.lower()
394
+
395
+ run_async(_test())
396
+
397
+
398
+ # ==============================================================================
399
+ # 11, 12 & 13: WEBHOOKS — CAPTURE, REFUND & FAILURE AUDIT
400
+ # ==============================================================================
401
+
402
+ def test_11_webhook_payment_captured_idempotency():
403
+ """11. Authenticated webhook 'payment.captured' asynchronously fulfills and repeated delivery is idempotent."""
404
+ async def _test():
405
+ secret = "test_webhook_secret_key_123"
406
+ payload_data = {
407
+ "event": "payment.captured",
408
+ "payload": {
409
+ "payment": {
410
+ "entity": {
411
+ "id": "pay_captured_webhook_44",
412
+ "order_id": "order_webhook_44",
413
+ "amount": 15900, # ₹159
414
+ "notes": {"user_id": "user_webhook_sub_44", "purpose": "subscription", "reference_id": "sahih_pro_monthly"}
415
+ }
416
+ }
417
+ }
418
+ }
419
+ raw_body = json.dumps(payload_data).encode("utf-8")
420
+ signature = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
421
+
422
+ mock_request = AsyncMock(spec=Request)
423
+ mock_request.body = AsyncMock(return_value=raw_body)
424
+ mock_request.headers = {"X-Razorpay-Signature": signature}
425
+
426
+ # First delivery: fulfills
427
+ with patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_find_tx, \
428
+ patch("app.payment_routes.execute_payment_fulfillment", new_callable=AsyncMock) as mock_fulfill:
429
+
430
+ mock_find_tx.return_value = None
431
+ mock_fulfill.return_value = {"is_pro": True, "tier": "PRO"}
432
+
433
+ res1 = await razorpay_webhook(request=mock_request)
434
+ assert res1["status"] == "processed"
435
+ assert mock_fulfill.called
436
+
437
+ # Second delivery (replay): returns already_processed without calling fulfill again
438
+ with patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_find_tx, \
439
+ patch("app.payment_routes.execute_payment_fulfillment", new_callable=AsyncMock) as mock_fulfill:
440
+
441
+ mock_find_tx.return_value = {"transaction_id": "pay_captured_webhook_44", "status": "completed"}
442
+
443
+ res2 = await razorpay_webhook(request=mock_request)
444
+ assert res2["status"] == "already_processed"
445
+ assert not mock_fulfill.called
446
+
447
+ run_async(_test())
448
+
449
+
450
+ def test_12_webhook_refund_processed_revokes_pro_and_debits_wallet():
451
+ """12. Authenticated webhook 'refund.processed' revokes Pro and debits wallet balance."""
452
+ async def _test():
453
+ secret = "test_webhook_secret_key_123"
454
+
455
+ # Case A: Refund on a Pro subscription -> revokes Pro
456
+ sub_refund_data = {
457
+ "event": "refund.processed",
458
+ "payload": {
459
+ "refund": {
460
+ "entity": {
461
+ "id": "rfnd_sub_123",
462
+ "payment_id": "pay_sub_to_refund_88",
463
+ "amount": 15900,
464
+ }
465
+ }
466
+ }
467
+ }
468
+ raw_body_sub = json.dumps(sub_refund_data).encode("utf-8")
469
+ sig_sub = hmac.new(secret.encode("utf-8"), raw_body_sub, hashlib.sha256).hexdigest()
470
+
471
+ mock_req_sub = AsyncMock(spec=Request)
472
+ mock_req_sub.body = AsyncMock(return_value=raw_body_sub)
473
+ mock_req_sub.headers = {"X-Razorpay-Signature": sig_sub}
474
+
475
+ with patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_find_tx, \
476
+ patch("app.payment_routes.transactions_collection.update_one", new_callable=AsyncMock) as mock_upd_tx, \
477
+ patch("app.payment_routes.transactions_collection.insert_one", new_callable=AsyncMock) as mock_ins_tx, \
478
+ patch("app.payment_routes.users_collection.update_one", new_callable=AsyncMock) as mock_upd_u, \
479
+ patch("app.payment_routes.subscriptions_collection.update_one", new_callable=AsyncMock) as mock_upd_sub, \
480
+ patch("app.payment_routes.invalidate_user_cache", new_callable=AsyncMock):
481
+
482
+ mock_find_tx.return_value = {
483
+ "transaction_id": "pay_sub_to_refund_88",
484
+ "user_id": "user_refunded_pro",
485
+ "type": "subscription_payment",
486
+ "amount": 159.0,
487
+ }
488
+
489
+ res = await razorpay_webhook(request=mock_req_sub)
490
+ assert res["status"] == "processed"
491
+ assert mock_upd_tx.called
492
+ assert mock_ins_tx.called
493
+ # Verify Pro revoked in users_collection
494
+ user_update_fields = mock_upd_u.call_args[0][1]["$set"]
495
+ assert user_update_fields["subscription.is_pro"] is False
496
+ assert user_update_fields["subscription.status"] == "REFUNDED"
497
+
498
+ # Case B: Refund on an ad_wallet topup -> debits wallet
499
+ wallet_refund_data = {
500
+ "event": "refund.processed",
501
+ "payload": {
502
+ "refund": {
503
+ "entity": {
504
+ "id": "rfnd_wallet_456",
505
+ "payment_id": "pay_wallet_to_refund_99",
506
+ "amount": 50000,
507
+ }
508
+ }
509
+ }
510
+ }
511
+ raw_body_wallet = json.dumps(wallet_refund_data).encode("utf-8")
512
+ sig_wallet = hmac.new(secret.encode("utf-8"), raw_body_wallet, hashlib.sha256).hexdigest()
513
+
514
+ mock_req_wallet = AsyncMock(spec=Request)
515
+ mock_req_wallet.body = AsyncMock(return_value=raw_body_wallet)
516
+ mock_req_wallet.headers = {"X-Razorpay-Signature": sig_wallet}
517
+
518
+ with patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_find_tx, \
519
+ patch("app.payment_routes.transactions_collection.update_one", new_callable=AsyncMock), \
520
+ patch("app.payment_routes.transactions_collection.insert_one", new_callable=AsyncMock), \
521
+ patch("app.payment_routes.wallets_collection.update_one", new_callable=AsyncMock) as mock_wallet_upd:
522
+
523
+ mock_find_tx.return_value = {
524
+ "transaction_id": "pay_wallet_to_refund_99",
525
+ "user_id": "adv_user_refunded",
526
+ "type": "topup",
527
+ "amount": 500.0,
528
+ }
529
+
530
+ res2 = await razorpay_webhook(request=mock_req_wallet)
531
+ assert res2["status"] == "processed"
532
+ # Verify wallet decremented
533
+ wallet_inc = mock_wallet_upd.call_args[0][1]["$inc"]["balance"]
534
+ assert wallet_inc == -500.0
535
+
536
+ run_async(_test())
537
+
538
+
539
+ def test_13_webhook_payment_failed_logs_audit():
540
+ """13. Webhook 'payment.failed' records failure audit entry in ledger with error code and description."""
541
+ async def _test():
542
+ secret = "test_webhook_secret_key_123"
543
+ payload_data = {
544
+ "event": "payment.failed",
545
+ "payload": {
546
+ "payment": {
547
+ "entity": {
548
+ "id": "pay_failed_webhook_007",
549
+ "order_id": "order_failed_007",
550
+ "amount": 15900,
551
+ "error_code": "BAD_REQUEST_ERROR",
552
+ "error_description": "Card expired or declined by issuer",
553
+ "notes": {"user_id": "user_failed_card"}
554
+ }
555
+ }
556
+ }
557
+ }
558
+ raw_body = json.dumps(payload_data).encode("utf-8")
559
+ signature = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
560
+
561
+ mock_request = AsyncMock(spec=Request)
562
+ mock_request.body = AsyncMock(return_value=raw_body)
563
+ mock_request.headers = {"X-Razorpay-Signature": signature}
564
+
565
+ with patch("app.payment_routes.transactions_collection.insert_one", new_callable=AsyncMock) as mock_ins_tx:
566
+ res = await razorpay_webhook(request=mock_request)
567
+ assert res["status"] == "processed"
568
+ assert mock_ins_tx.called
569
+ saved_doc = mock_ins_tx.call_args[0][0]
570
+ assert saved_doc["transaction_id"] == "pay_failed_webhook_007"
571
+ assert saved_doc["status"] == "failed"
572
+ assert "Card expired or declined" in saved_doc["description"]
573
+
574
+ run_async(_test())
575
+
576
+
577
+ # ==============================================================================
578
+ # 14: SUBSCRIPTION STATUS & TIMELINE PROGRESS CALCULATION
579
+ # ==============================================================================
580
+
581
+ def test_14_subscription_status_progress_calculation():
582
+ """14. GET /payment/subscriptions/status returns server-authoritative progress percentage and timeline metrics."""
583
+ async def _test():
584
+ user_id = "user_pro_subscriber_live"
585
+ mock_user = {"uid": user_id, "email": "live@sahihislam.com"}
586
+
587
+ now = datetime.utcnow()
588
+ activated_at = now - timedelta(days=10) # 10 days ago
589
+ expires_at = now + timedelta(days=20) # 20 days remaining, total duration = 30 days
590
+
591
+ user_doc = {
592
+ "uid": user_id,
593
+ "created_at": now - timedelta(days=40),
594
+ "subscription": {
595
+ "is_pro": True,
596
+ "is_progress_plus": True,
597
+ "is_ad_free_admob": True,
598
+ "status": "ACTIVE",
599
+ "plan_id": "sahih_pro_monthly",
600
+ "tier": "PRO",
601
+ "activated_at": activated_at,
602
+ "expires_at": expires_at,
603
+ "payment_method": "razorpay",
604
+ "auto_renew": True,
605
+ }
606
+ }
607
+
608
+ with patch("app.payment_routes.users_collection.find_one", new_callable=AsyncMock) as mock_find_u, \
609
+ patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock) as mock_find_tx:
610
+
611
+ mock_find_u.return_value = user_doc
612
+ mock_find_tx.return_value = {
613
+ "transaction_id": "pay_live_sub_10",
614
+ "amount": 159.0,
615
+ "payment_method": "razorpay",
616
+ "status": "completed",
617
+ "created_at": activated_at,
618
+ }
619
+
620
+ status_res = await get_subscription_status(reconcile=False, current_user=mock_user)
621
+
622
+ assert status_res["is_pro"] is True
623
+ assert status_res["status"] == "ACTIVE"
624
+ assert status_res["plan_id"] == "sahih_pro_monthly"
625
+ assert status_res["tier"] == "PRO"
626
+ assert status_res["duration_days"] == 30
627
+ assert status_res["elapsed_days"] == 10
628
+ assert status_res["remaining_days"] == 20
629
+ # Progress calculation: 10 / 30 = 33.33%
630
+ assert 32.0 <= status_res["progress_percent"] <= 35.0
631
+ assert status_res["is_recurring"] is True
632
+ assert status_res["is_introductory"] is False
633
+ assert status_res["payment_method"] == "razorpay"
634
+ assert status_res["auto_renew"] is True
635
+ assert status_res["last_transaction"] is not None
636
+ assert status_res["last_transaction"]["transaction_id"] == "pay_live_sub_10"
637
+
638
+ run_async(_test())
tests/test_payment_remediation.py CHANGED
@@ -445,7 +445,7 @@ def test_subscription_lifecycle_cancellation_vs_revocation():
445
  # Check that user record was marked CANCELED but is_pro was NOT set to False
446
  user_update_call = mock_user_update.call_args[0]
447
  assert user_update_call[0] == {"uid": "user_lifecycle_1"}
448
- assert user_update_call[1]["$set"]["subscription.status"] == "CANCELED"
449
  assert "is_pro" not in user_update_call[1]["$set"] # Access preserved!
450
 
451
  # 2. Test Revocation (notificationType=12) immediately strips is_pro
 
445
  # Check that user record was marked CANCELED but is_pro was NOT set to False
446
  user_update_call = mock_user_update.call_args[0]
447
  assert user_update_call[0] == {"uid": "user_lifecycle_1"}
448
+ assert user_update_call[1]["$set"]["subscription.status"] in ["CANCELED", "CANCELLED_ACTIVE"]
449
  assert "is_pro" not in user_update_call[1]["$set"] # Access preserved!
450
 
451
  # 2. Test Revocation (notificationType=12) immediately strips is_pro