Consulawtech Claude Opus 5.5 (1M context) commited on
Commit
fb3984d
·
1 Parent(s): ec0c85f

Staff credit tools: POST /credits/admin-grant and GET /credits/admin-ledger/{uid}

Browse files

Verified Firebase token + active admin_staff row required. Grants are
recorded in the ledger as admin_grant with the staff email in the note.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. app.py +56 -0
app.py CHANGED
@@ -1055,6 +1055,62 @@ async def credit_packs():
1055
  }
1056
 
1057
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1058
  def _charge_minutes_doc(request: Request, body: dict) -> None:
1059
  """Check and charge MINUTES_DOC_CREDITS once per transcript (PDF and DOCX
1060
  exports of the same meeting share one charge)."""
 
1055
  }
1056
 
1057
 
1058
+ def _require_staff(request: Request) -> str:
1059
+ """Email of an active admin_staff member, from a verified Firebase token."""
1060
+ auth = request.headers.get("authorization", "")
1061
+ if not auth.lower().startswith("bearer "):
1062
+ raise HTTPException(status_code=401, detail="Sign in as staff.")
1063
+ try:
1064
+ from google.oauth2 import id_token as _gid
1065
+ from google.auth.transport import requests as _gareq
1066
+ claims = _gid.verify_firebase_token(auth.split(" ", 1)[1].strip(), _gareq.Request(),
1067
+ audience=_FIREBASE_PROJECT) or {}
1068
+ except Exception:
1069
+ raise HTTPException(status_code=401, detail="Your session has expired. Please sign in again.")
1070
+ email = (claims.get("email") or "").lower()
1071
+ rows = _supabase_request("GET", "/rest/v1/admin_staff",
1072
+ params={"email": f"eq.{email}", "select": "role,active", "limit": "1"}) if email else None
1073
+ if not rows or rows[0].get("active") is False:
1074
+ raise HTTPException(status_code=403, detail="Staff only.")
1075
+ return email
1076
+
1077
+
1078
+ @app.post("/credits/admin-grant")
1079
+ async def credits_admin_grant(request: Request):
1080
+ """Staff adjust a user's balance (support refunds, testers, promotions).
1081
+ A negative amount removes credits (never below zero)."""
1082
+ staff = await asyncio.to_thread(_require_staff, request)
1083
+ body = await request.json()
1084
+ target = (body.get("firebase_uid") or "").strip()
1085
+ try:
1086
+ amount = int(body.get("amount"))
1087
+ except (TypeError, ValueError):
1088
+ raise HTTPException(status_code=400, detail="amount must be a whole number")
1089
+ if not target or amount == 0 or abs(amount) > 100000:
1090
+ raise HTTPException(status_code=400, detail="firebase_uid and a non-zero amount (max 100,000) are required")
1091
+ note = (body.get("note") or "").strip()[:200]
1092
+ balance = await asyncio.to_thread(
1093
+ _apply_credits, target, amount, "admin_grant", f"admin:{uuid.uuid4()}",
1094
+ f"{note or 'Adjusted by staff'} ({staff})",
1095
+ )
1096
+ if balance is None:
1097
+ raise HTTPException(status_code=500, detail="Could not update the balance.")
1098
+ logger.info(f"Staff {staff} changed {target} by {amount} credits (balance {balance})")
1099
+ return {"balance": balance}
1100
+
1101
+
1102
+ @app.get("/credits/admin-ledger/{firebase_uid}")
1103
+ async def credits_admin_ledger(firebase_uid: str, request: Request):
1104
+ """Staff view of a user's last 50 credit movements."""
1105
+ await asyncio.to_thread(_require_staff, request)
1106
+ rows = await asyncio.to_thread(
1107
+ _supabase_request, "GET", "/rest/v1/credit_ledger",
1108
+ None, {"firebase_uid": f"eq.{firebase_uid}", "order": "created_at.desc", "limit": "50",
1109
+ "select": "delta,balance_after,kind,note,created_at"},
1110
+ )
1111
+ return {"entries": rows or []}
1112
+
1113
+
1114
  def _charge_minutes_doc(request: Request, body: dict) -> None:
1115
  """Check and charge MINUTES_DOC_CREDITS once per transcript (PDF and DOCX
1116
  exports of the same meeting share one charge)."""