Spaces:
Running
feat(admin): let a platform admin change a university's plan tier
Browse filesConfirmed there was genuinely no way to do this — plan_tier has existed
as a column since the original schema (CHECK constraint restricts it to
free/pro/enterprise, default 'free', confirmed live) but nothing ever
wrote to it after row creation, and no endpoint returned it consistently.
- New PATCH /admin/organizations/{org_id}/plan, platform-admin only (a
school's own admin — who CAN manage their own org's admin list, per the
earlier organization_admins work — must not be able to self-upgrade
their own plan).
- plan_tier added to every organization SELECT/RETURNING clause
(list/create/deactivate/get-my-org) — it was silently missing from all
four, the same "field quietly never sent to the frontend" bug already
hit twice today with created_at.
8 tests cover: changing the plan, rejecting an invalid tier before
touching the database (matches the real CHECK constraint's three values),
unknown org 404, platform-admin-only access, and all three real tiers
accepted. Full suite (80 tests) passes.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Files changed (2)
- admin_routes.py+47-4
- test_organization_plan.pyAdded+162
569 unmodified lines57057157257357457557621 unmodified lines59859960060160260360422 unmodified lines6276286296306316326336 unmodified lines64064164264364464564 unmodified lines710711712713714715716569 unmodified linesraise HTTPException(503, "Data layer unavailable (database not configured)")with pool.connection() as conn:return conn.execute("SELECT id, name, email_domain, is_active, created_at FROM organizations ""ORDER BY name").fetchall()21 unmodified lines"""INSERT INTO organizations (name, email_domain, is_active)VALUES (%s, %s, true)RETURNING id, name, email_domain, is_active, created_at""",(body.name.strip(), domain),).fetchone()22 unmodified lines"""UPDATE organizations SET is_active = falseWHERE id = %sRETURNING id, name, email_domain, is_active, created_at""",(org_id,),).fetchone()6 unmodified linesreturn row# ===========================================================================# Organization admins — who can administer each university's own dashboard.#64 unmodified linesraise HTTPException(503, "Data layer unavailable (database not configured)")with pool.connection() as conn:org = conn.execute("SELECT id, name, email_domain, is_active, created_at ""FROM organizations WHERE id = %s",(org_id,),).fetchone()569 unmodified lines57057157257357457557621 unmodified lines59859960060160260360422 unmodified lines6276286296306316326336 unmodified lines64064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768864 unmodified lines753754755756757758759569 unmodified linesraise HTTPException(503, "Data layer unavailable (database not configured)")with pool.connection() as conn:return conn.execute("SELECT id, name, email_domain, plan_tier, is_active, created_at FROM organizations ""ORDER BY name").fetchall()21 unmodified lines"""INSERT INTO organizations (name, email_domain, is_active)VALUES (%s, %s, true)RETURNING id, name, email_domain, plan_tier, is_active, created_at""",(body.name.strip(), domain),).fetchone()22 unmodified lines"""UPDATE organizations SET is_active = falseWHERE id = %sRETURNING id, name, email_domain, plan_tier, is_active, created_at""",(org_id,),).fetchone()6 unmodified linesreturn row# organizations.plan_tier has a CHECK constraint restricting it to exactly# these three values (confirmed live against Aurora) — validated here too# so a bad value returns a clean 422 instead of a raw constraint-violation# 500, same pattern as OPP_CATEGORIES/OPP_STATUSES above.PLAN_TIERS = {"free", "pro", "enterprise"}class UpdatePlan(BaseModel):plan_tier: str@router.patch("/organizations/{org_id}/plan")def update_organization_plan(org_id: str, body: UpdatePlan, _admin: dict = Depends(require_platform_admin)):"""Change a university's plan tier. Platform-admin only — a school's ownadmin must not be able to upgrade (or downgrade) its own plan."""if body.plan_tier not in PLAN_TIERS:raise HTTPException(422, f"plan_tier must be one of {sorted(PLAN_TIERS)}")pool = get_pool()if pool is None:raise HTTPException(503, "Data layer unavailable (database not configured)")with pool.connection() as conn:row = conn.execute("""UPDATE organizations SET plan_tier = %sWHERE id = %sRETURNING id, name, email_domain, plan_tier, is_active, created_at""",(body.plan_tier, org_id),).fetchone()if not row:raise HTTPException(404, "Organization not found")logger.info("[admin_routes] platform admin %s set org %s's plan to %s",_admin.get("email"), org_id, body.plan_tier,)return row# ===========================================================================# Organization admins — who can administer each university's own dashboard.#64 unmodified linesraise HTTPException(503, "Data layer unavailable (database not configured)")with pool.connection() as conn:org = conn.execute("SELECT id, name, email_domain, plan_tier, is_active, created_at ""FROM organizations WHERE id = %s",(org_id,),).fetchone()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Verification for PATCH /admin/organizations/{org_id}/plan — changing auniversity's plan tier. Confirmed live against Aurora: organizations.plan_tieris a text column with CHECK (plan_tier IN ('free','pro','enterprise')),default 'free'.
Run with: pytest test_organization_plan.py -v"""import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient
import authimport admin_routes
class FakeCursor: def __init__(self, row=None): self._row = row
def fetchone(self): return self._row
class FakeConn: def __init__(self, script): self.script = list(script) self.calls = []
def execute(self, query, params=None): self.calls.append((query, params)) return self.script.pop(0)
def __enter__(self): return self
def __exit__(self, *a): return False
class FakePool: def __init__(self, conn): self._conn = conn
def connection(self): return self._conn
def _build_app(): app = FastAPI() app.include_router(admin_routes.router, prefix="/admin") return app
PLATFORM_ADMIN_EMAIL = "ops@studentcompanionai.rw"
@pytest.fixturedef client_as_platform_admin(monkeypatch): monkeypatch.setattr(auth, "_FIREBASE_READY", True) monkeypatch.setattr( auth.fb_auth, "verify_id_token", lambda t: {"email": PLATFORM_ADMIN_EMAIL} ) monkeypatch.setattr(auth, "PLATFORM_ADMIN_EMAILS", {PLATFORM_ADMIN_EMAIL}) return TestClient(_build_app())
def _auth_headers(): return {"Authorization": "Bearer fake-token"}
def test_platform_admin_can_change_plan(client_as_platform_admin, monkeypatch): conn = FakeConn([ FakeCursor(row={ "id": "org-ur", "name": "University of Rwanda", "email_domain": "ur.ac.rw", "plan_tier": "pro", "is_active": True, "created_at": "2026-09-06T00:00:00Z", }), ]) monkeypatch.setattr(admin_routes, "get_pool", lambda: FakePool(conn))
resp = client_as_platform_admin.patch( "/admin/organizations/org-ur/plan", json={"plan_tier": "pro"}, headers=_auth_headers(), ) assert resp.status_code == 200 assert resp.json()["plan_tier"] == "pro"
update_query, update_params = conn.calls[0] assert "%s" in update_query assert "pro" in update_params assert "org-ur" in update_params
def test_invalid_plan_tier_rejected_before_touching_database(client_as_platform_admin, monkeypatch): calls = [] monkeypatch.setattr( admin_routes, "get_pool", lambda: calls.append("called") or FakePool(FakeConn([])) ) resp = client_as_platform_admin.patch( "/admin/organizations/org-ur/plan", json={"plan_tier": "premium-deluxe"}, # not a real tier headers=_auth_headers(), ) assert resp.status_code == 422 assert calls == [], "should reject before ever querying the database"
def test_unknown_organization_returns_404(client_as_platform_admin, monkeypatch): conn = FakeConn([FakeCursor(row=None)]) monkeypatch.setattr(admin_routes, "get_pool", lambda: FakePool(conn)) resp = client_as_platform_admin.patch( "/admin/organizations/does-not-exist/plan", json={"plan_tier": "enterprise"}, headers=_auth_headers(), ) assert resp.status_code == 404
def test_ordinary_school_admin_cannot_change_their_own_plan(monkeypatch): """A school's own admin must not be able to self-upgrade — this stays platform-admin only, unlike managing their own org's admin list.""" monkeypatch.setattr(auth, "_FIREBASE_READY", True) monkeypatch.setattr( auth.fb_auth, "verify_id_token", lambda t: {"email": "admin@ines.ac.rw"} ) monkeypatch.setattr(auth, "PLATFORM_ADMIN_EMAILS", {PLATFORM_ADMIN_EMAIL}) client = TestClient(_build_app())
resp = client.patch( "/admin/organizations/org-ines/plan", json={"plan_tier": "enterprise"}, headers=_auth_headers(), ) assert resp.status_code == 403
def test_no_token_is_rejected(monkeypatch): monkeypatch.setattr(auth, "_FIREBASE_READY", True) monkeypatch.setattr(auth, "PLATFORM_ADMIN_EMAILS", {PLATFORM_ADMIN_EMAIL}) client = TestClient(_build_app()) resp = client.patch( "/admin/organizations/org-ur/plan", json={"plan_tier": "pro"} ) assert resp.status_code == 401
@pytest.mark.parametrize("tier", ["free", "pro", "enterprise"])def test_each_real_plan_tier_is_accepted(client_as_platform_admin, monkeypatch, tier): conn = FakeConn([ FakeCursor(row={ "id": "org-x", "name": "X", "email_domain": "x.edu", "plan_tier": tier, "is_active": True, "created_at": "2026-09-06T00:00:00Z", }), ]) monkeypatch.setattr(admin_routes, "get_pool", lambda: FakePool(conn)) resp = client_as_platform_admin.patch( "/admin/organizations/org-x/plan", json={"plan_tier": tier}, headers=_auth_headers(), ) assert resp.status_code == 200