File size: 10,444 Bytes
3f72838
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""Supabase client and data access helpers."""

from typing import Optional

from fastapi import HTTPException
from supabase import Client, create_client

from config import SUPABASE_SERVICE_ROLE_KEY, SUPABASE_URL

_supabase: Optional[Client] = None


def get_supabase() -> Client:
    """Return a singleton Supabase client using the service role key."""
    global _supabase
    if _supabase is None:
        if not SUPABASE_URL or not SUPABASE_SERVICE_ROLE_KEY:
            raise HTTPException(
                status_code=500,
                detail="Server missing SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY secrets.",
            )
        _supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY)
    return _supabase


def fetch_all_submissions(columns: str, limit: Optional[int] = None) -> list[dict]:
    """Fetch rows from submissions, paginating past Supabase's 1000-row cap."""
    sb = get_supabase()
    rows: list[dict] = []
    page = 0
    page_size = 1000

    while True:
        start = page * page_size
        end = start + page_size - 1
        query = (
            sb.table("submissions")
            .select(columns)
            .order("submitted_at", desc=True)
            .range(start, end)
        )
        result = query.execute()
        batch = result.data or []
        rows.extend(batch)

        if len(batch) < page_size:
            break
        if limit and len(rows) >= limit:
            break
        page += 1

    return rows[:limit] if limit else rows


def count_all_submissions() -> int:
    """Cheap row count, used to decide whether the in-process duplicate-check
    cache needs a full reload (see services/duplicate_service.py)."""
    sb = get_supabase()
    result = sb.table("submissions").select("id", count="exact", head=True).execute()
    return result.count or 0


def verify_access_code(code: str, email: str) -> Optional[dict]:
    """Look up a team by access code AND member email via the
    verify_access_code RPC, using the service role key (bypasses RLS — this
    is the only place access codes are checked). Both must match: the code
    alone is not enough."""
    sb = get_supabase()
    result = sb.rpc("verify_access_code", {"code": code, "member_email": email}).execute()
    rows = result.data or []
    row = rows[0] if isinstance(rows, list) else rows
    return row or None


def insert_submission(row: dict) -> dict:
    sb = get_supabase()
    try:
        result = sb.table("submissions").insert(row).select("id").execute()
    except Exception as exc:
        client_submission_id = row.get("client_submission_id")
        team_id = row.get("team_id")
        # Unique violation on (team_id, client_submission_id) means this is a
        # retried submit (offline outbox) whose earlier attempt actually
        # succeeded server-side but never got its response back to the
        # client. Treat that as success and hand back the existing row
        # instead of erroring the retry.
        if client_submission_id and "duplicate key" in str(exc).lower():
            existing = (
                sb.table("submissions")
                .select("id")
                .eq("team_id", team_id)
                .eq("client_submission_id", client_submission_id)
                .limit(1)
                .execute()
            )
            if existing.data:
                return existing.data[0]
        raise HTTPException(status_code=500, detail=f"Insert failed: {exc}") from exc

    data = result.data or []
    if not data:
        raise HTTPException(status_code=500, detail="Insert did not return a row")
    return data[0]


def fetch_submissions_for_team(team_id: str, columns: str) -> list[dict]:
    sb = get_supabase()
    result = (
        sb.table("submissions")
        .select(columns)
        .eq("team_id", team_id)
        .order("submitted_at", desc=True)
        .execute()
    )
    return result.data or []


def count_submissions_for_team(team_id: str) -> int:
    sb = get_supabase()
    result = (
        sb.table("submissions")
        .select("id", count="exact", head=True)
        .eq("team_id", team_id)
        .execute()
    )
    return result.count or 0


def update_judge_reviewed(submission_id: str, reviewed: bool) -> None:
    sb = get_supabase()
    sb.table("submissions").update({"judge_reviewed": reviewed}).eq("id", submission_id).execute()


# --- Judging (post-event blind review) --------------------------------------


def verify_judge_code(code: str) -> Optional[dict]:
    """Look up a judge by access code via the verify_judge_code RPC, same
    pattern as verify_access_code for teams -- service role only."""
    sb = get_supabase()
    result = sb.rpc("verify_judge_code", {"code": code}).execute()
    rows = result.data or []
    row = rows[0] if isinstance(rows, list) else rows
    return row or None


def create_judge(judge_name: str, access_code: str) -> dict:
    sb = get_supabase()
    result = sb.table("judges").insert(
        {"judge_name": judge_name, "access_code": access_code}
    ).execute()
    data = result.data or []
    if not data:
        raise HTTPException(status_code=500, detail="Insert did not return a row")
    return data[0]


def list_judges() -> list[dict]:
    sb = get_supabase()
    result = (
        sb.table("judges")
        .select("judge_id,judge_name,access_code,created_at")
        .order("created_at", desc=True)
        .execute()
    )
    return result.data or []


def fetch_unsampled_submission_ids_by_team() -> dict[str, list[str]]:
    """Candidates for judging, grouped by team_id: not already sampled, and
    not already flagged as a duplicate -- no point spending judge time on a
    row that won't be credited anyway. Grouped so sampling can be done
    per-team (stratified), rather than one flat pool that could leave some
    teams with zero items sampled just by chance."""
    rows = fetch_all_submissions("id,team_id,sampled_for_judging,flag_duplicate")
    by_team: dict[str, list[str]] = {}
    for row in rows:
        if row.get("sampled_for_judging") or row.get("flag_duplicate"):
            continue
        team_id = row.get("team_id")
        if not team_id:
            continue
        by_team.setdefault(team_id, []).append(row["id"])
    return by_team


def mark_sampled_for_judging(submission_ids: list[str]) -> None:
    sb = get_supabase()
    for start in range(0, len(submission_ids), 200):
        batch = submission_ids[start : start + 200]
        if batch:
            sb.table("submissions").update(
                {"sampled_for_judging": True, "sampled_at": "now()"}
            ).in_("id", batch).execute()


def fetch_judge_queue(judge_id: str) -> list[dict]:
    """All sampled submissions this judge hasn't labeled yet. Text only --
    callers (routers/judge.py) must not select or return original labels."""
    sb = get_supabase()
    already = (
        sb.table("judge_labels")
        .select("submission_id")
        .eq("judge_id", judge_id)
        .execute()
    )
    already_ids = {row["submission_id"] for row in (already.data or [])}

    result = (
        sb.table("submissions")
        .select("id,text")
        .eq("sampled_for_judging", True)
        .execute()
    )
    rows = result.data or []
    return [row for row in rows if row["id"] not in already_ids]


def upsert_judge_label(judge_id: str, row: dict) -> dict:
    sb = get_supabase()
    payload = {**row, "judge_id": judge_id}
    result = (
        sb.table("judge_labels")
        .upsert(payload, on_conflict="submission_id,judge_id")
        .execute()
    )
    data = result.data or []
    if not data:
        raise HTTPException(status_code=500, detail="Judge label upsert did not return a row")
    return data[0]


def fetch_sampled_submissions_with_labels(columns: str) -> list[dict]:
    """Sampled submissions (with their original labels) for the admin
    judge-report -- admin-only, never exposed to judges."""
    sb = get_supabase()
    result = (
        sb.table("submissions")
        .select(columns)
        .eq("sampled_for_judging", True)
        .execute()
    )
    return result.data or []


def fetch_all_judge_labels() -> list[dict]:
    sb = get_supabase()
    result = sb.table("judge_labels").select("*").execute()
    return result.data or []


# --- Admin accounts (multiple named organizer logins) ----------------------


def fetch_admin_by_email(email: str) -> Optional[dict]:
    """Look up an admin by email via the verify_admin_email RPC (service
    role only) -- returns the bcrypt hash for admin_service.py to check,
    never compared in SQL."""
    sb = get_supabase()
    result = sb.rpc("verify_admin_email", {"admin_email": email}).execute()
    rows = result.data or []
    row = rows[0] if isinstance(rows, list) else rows
    return row or None


def count_admins() -> int:
    sb = get_supabase()
    result = sb.table("admins").select("admin_id", count="exact").execute()
    return result.count or 0


def create_admin(admin_name: str, email: str, password_hash: str) -> dict:
    sb = get_supabase()
    result = (
        sb.table("admins")
        .insert({"admin_name": admin_name, "email": email, "password_hash": password_hash})
        .execute()
    )
    data = result.data or []
    if not data:
        raise HTTPException(status_code=500, detail="Insert did not return a row")
    return data[0]


def list_admins() -> list[dict]:
    sb = get_supabase()
    result = (
        sb.table("admins")
        .select("admin_id,admin_name,email,created_at")
        .order("created_at", desc=True)
        .execute()
    )
    return result.data or []


def list_teams() -> list[dict]:
    sb = get_supabase()
    result = sb.table("teams").select(
        "team_id,team_name,access_code,member_emails,created_at"
    ).order("created_at", desc=True).execute()
    return result.data or []


def create_team(team_id: str, team_name: str, access_code: str, member_emails: list[str]) -> dict:
    sb = get_supabase()
    result = (
        sb.table("teams")
        .insert(
            {
                "team_id": team_id,
                "team_name": team_name,
                "access_code": access_code,
                "member_emails": member_emails,
            }
        )
        .execute()
    )
    data = result.data or []
    if not data:
        raise HTTPException(status_code=500, detail="Insert did not return a row")
    return data[0]