diff --git a/app/main.py b/app/main.py index 0204dfd..d6a2af3 100644 --- a/app/main.py +++ b/app/main.py @@ -3227,6 +3227,106 @@ async def admin_held_refund(hold_id: int, request: Request): return {"status": "refunded", "id": hold_id} +@app.post("/admin/held-credits/{hold_id}/grant") +@limiter.limit("20/minute") +async def admin_held_grant(hold_id: int, request: Request): + """Apply a held credit pack to a specified member account. + + Body: {"email": "member@..."} — the member account that should receive the + held credits. This covers purchases made by someone other than the member + (e.g. a credit pack bought on another account's behalf), which the + provisioning-time auto-grant cannot match because it keys on the buyer's + own email/slug. + + Atomic and idempotent: the balance update and the ledger insert happen in + one transaction, and the hold is flipped `held` → `granted` in the same + transaction. The ledger reference is `held:` (the same shape the + provisioning-time auto-grant uses), so a re-run cannot double-apply. + """ + _verify_admin_token(request) + + body = await request.json() + email = (body.get("email") or "").strip().lower() + if not email: + raise HTTPException(400, "Missing email") + + conn = get_db() + row = conn.execute( + "SELECT id, slug, email, name, amount, oc_reference, status " + "FROM held_credits WHERE id = ?", + (hold_id,), + ).fetchone() + if not row: + conn.close() + raise HTTPException(404, "Held credit not found") + if row[6] != "held": + conn.close() + raise HTTPException(409, f"Held credit already {row[6]}") + + dest = conn.execute( + "SELECT active FROM members WHERE LOWER(email) = ?", (email,) + ).fetchone() + if not dest: + conn.close() + raise HTTPException(404, f"No member account for {email}") + if not dest[0]: + conn.close() + raise HTTPException(409, f"Member {email} is not active; refusing") + + amount = float(row[4] or 0.0) + reference = f"held:{hold_id}" + if credit_reference_exists(reference): + conn.close() + raise HTTPException(409, f"Credit already recorded for {reference}") + + buyer = row[2] or row[1] + buyer_name = row[3] or row[1] + reason = ( + f"credit pack (${amount:.2f}) bought by {buyer} ({buyer_name}); " + f"held credit transferred to this member account at the operator's " + f"instruction (hold #{hold_id}, oc:{row[5] or ''})" + ) + # One transaction: flip the hold, move the balance, write the audit row. + cur = conn.execute( + "UPDATE held_credits SET status = 'granted', resolved_at = datetime('now') " + "WHERE id = ? AND status = 'held'", + (hold_id,), + ) + if cur.rowcount != 1: + conn.close() + raise HTTPException(409, "Held credit already resolved") + conn.execute( + "UPDATE members SET credit_balance = MAX(0, COALESCE(credit_balance, 0) + ?) " + "WHERE LOWER(email) = ?", + (amount, email), + ) + conn.execute( + "INSERT INTO credit_ledger (email, delta, reason, reference) VALUES (?, ?, ?, ?)", + (email, amount, reason, reference), + ) + new_balance = conn.execute( + "SELECT credit_balance FROM members WHERE LOWER(email) = ?", (email,) + ).fetchone()[0] + conn.commit() + conn.close() + + applied = await sync_team_budget_from_balance(email) + logger.info( + "Held credit #%s ($%.2f) from %s granted to %s (balance %s)", + hold_id, amount, buyer, email, new_balance, + ) + return { + "status": "granted", + "hold_id": hold_id, + "email": email, + "credits_added": amount, + "credit_balance": float(new_balance), + "reference": reference, + "oc_reference": row[5], + "team_budget": applied, + } + + # Operator accounts — shown under a separate "admin" status in the panel and # excluded from the member counts. They're infrastructure accounts (the SSO # owner and the bot), not dues-paying members.