File size: 3,389 Bytes
1ffd0a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"""
CNIC verification and fake-report accountability service.

Domain ownership
----------------
- CNIC format validation
- User lookup by Firebase uid
- Atomic strike increment + state transitions (warned β†’ blacklisted)

Strike state machine
--------------------
  0-2  β†’ strike_recorded  (silent)
   3   β†’ warned=True      (FCM warning sent by Phase 10)
  4+   β†’ blacklisted=True (FCM blacklist sent by Phase 10)

The transition logic lives here; FCM dispatch lives in Phase 10. This
module only updates Firestore state and returns the action taken.
"""

from __future__ import annotations

import re

from google.cloud.firestore import FieldFilter, async_transactional

from backend.core.firebase import get_async_db

CNIC_PATTERN = re.compile(r"^\d{5}-\d{7}-\d$")


def validate_cnic_format(cnic: str) -> bool:
    """Return True iff `cnic` matches the Pakistani XXXXX-XXXXXXX-X format."""
    return bool(CNIC_PATTERN.match(cnic))


async def get_user_by_uid(uid: str) -> dict | None:
    """Fetch the user record whose `uid` field matches the given Firebase uid.

    The Firestore `users` collection is keyed by CNIC, so this is a query
    rather than a direct document lookup.

    Returns:
        User dict with a `cnic` key added (the document ID), or None if no
        matching record exists.
    """
    db = get_async_db()
    query = db.collection("users").where(filter=FieldFilter("uid", "==", uid))
    async for doc in query.stream():
        return {"cnic": doc.id, **doc.to_dict()}
    return None


# ── Atomic strike increment ────────────────────────────────────────────────
#
# Defined at module level so @async_transactional can wrap it correctly.
# The decorator handles retry on contention β€” the function body must be
# idempotent with respect to Firestore writes.

@async_transactional
async def _apply_strike(transaction, user_ref) -> dict:
    """Transactional inner function β€” must only be called via record_false_report."""
    snap = await user_ref.get(transaction=transaction)
    if not snap.exists:
        raise ValueError(f"User document {user_ref.id!r} not found in Firestore")

    data = snap.to_dict()
    new_count = (data.get("strike_count") or 0) + 1

    updates: dict = {"strike_count": new_count}
    if new_count == 3:
        updates["warned"] = True
        action = "warned"
    elif new_count >= 4:
        updates["blacklisted"] = True
        action = "blacklisted"
    else:
        action = "strike_recorded"

    transaction.update(user_ref, updates)
    return {"action": action, "strike_count": new_count}


async def record_false_report(cnic: str) -> dict:
    """Atomically increment the strike count for a CNIC and apply state transitions.

    Uses a Firestore transaction so concurrent calls cannot produce a
    split-brain where the counter and the flags disagree.

    Args:
        cnic: The document ID of the user in the `users` collection.

    Returns:
        {"action": "strike_recorded" | "warned" | "blacklisted",
         "strike_count": <new value>}

    Raises:
        ValueError: If no user document exists for `cnic`.
    """
    db = get_async_db()
    user_ref = db.collection("users").document(cnic)
    transaction = db.transaction()
    return await _apply_strike(transaction, user_ref)