Donne120 Claude Sonnet 5 commited on
Commit
ff2925e
·
1 Parent(s): bebdbb7

feat(admin): let a platform admin change a university's plan tier

Browse files

Confirmed 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) hide show
  1. admin_routes.py +47 -4
  2. test_organization_plan.py +162 -0
admin_routes.py CHANGED
@@ -570,7 +570,7 @@ def list_organizations(_admin: dict = Depends(require_platform_admin)):
570
  raise HTTPException(503, "Data layer unavailable (database not configured)")
571
  with pool.connection() as conn:
572
  return conn.execute(
573
- "SELECT id, name, email_domain, is_active, created_at FROM organizations "
574
  "ORDER BY name"
575
  ).fetchall()
576
 
@@ -598,7 +598,7 @@ def create_organization(
598
  """
599
  INSERT INTO organizations (name, email_domain, is_active)
600
  VALUES (%s, %s, true)
601
- RETURNING id, name, email_domain, is_active, created_at
602
  """,
603
  (body.name.strip(), domain),
604
  ).fetchone()
@@ -627,7 +627,7 @@ def deactivate_organization(
627
  """
628
  UPDATE organizations SET is_active = false
629
  WHERE id = %s
630
- RETURNING id, name, email_domain, is_active, created_at
631
  """,
632
  (org_id,),
633
  ).fetchone()
@@ -640,6 +640,49 @@ def deactivate_organization(
640
  return row
641
 
642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  # ===========================================================================
644
  # Organization admins — who can administer each university's own dashboard.
645
  #
@@ -710,7 +753,7 @@ def get_my_organization(
710
  raise HTTPException(503, "Data layer unavailable (database not configured)")
711
  with pool.connection() as conn:
712
  org = conn.execute(
713
- "SELECT id, name, email_domain, is_active, created_at "
714
  "FROM organizations WHERE id = %s",
715
  (org_id,),
716
  ).fetchone()
 
570
  raise HTTPException(503, "Data layer unavailable (database not configured)")
571
  with pool.connection() as conn:
572
  return conn.execute(
573
+ "SELECT id, name, email_domain, plan_tier, is_active, created_at FROM organizations "
574
  "ORDER BY name"
575
  ).fetchall()
576
 
 
598
  """
599
  INSERT INTO organizations (name, email_domain, is_active)
600
  VALUES (%s, %s, true)
601
+ RETURNING id, name, email_domain, plan_tier, is_active, created_at
602
  """,
603
  (body.name.strip(), domain),
604
  ).fetchone()
 
627
  """
628
  UPDATE organizations SET is_active = false
629
  WHERE id = %s
630
+ RETURNING id, name, email_domain, plan_tier, is_active, created_at
631
  """,
632
  (org_id,),
633
  ).fetchone()
 
640
  return row
641
 
642
 
643
+ # organizations.plan_tier has a CHECK constraint restricting it to exactly
644
+ # these three values (confirmed live against Aurora) — validated here too
645
+ # so a bad value returns a clean 422 instead of a raw constraint-violation
646
+ # 500, same pattern as OPP_CATEGORIES/OPP_STATUSES above.
647
+ PLAN_TIERS = {"free", "pro", "enterprise"}
648
+
649
+
650
+ class UpdatePlan(BaseModel):
651
+ plan_tier: str
652
+
653
+
654
+ @router.patch("/organizations/{org_id}/plan")
655
+ def update_organization_plan(
656
+ org_id: str, body: UpdatePlan, _admin: dict = Depends(require_platform_admin)
657
+ ):
658
+ """
659
+ Change a university's plan tier. Platform-admin only — a school's own
660
+ admin must not be able to upgrade (or downgrade) its own plan.
661
+ """
662
+ if body.plan_tier not in PLAN_TIERS:
663
+ raise HTTPException(422, f"plan_tier must be one of {sorted(PLAN_TIERS)}")
664
+
665
+ pool = get_pool()
666
+ if pool is None:
667
+ raise HTTPException(503, "Data layer unavailable (database not configured)")
668
+ with pool.connection() as conn:
669
+ row = conn.execute(
670
+ """
671
+ UPDATE organizations SET plan_tier = %s
672
+ WHERE id = %s
673
+ RETURNING id, name, email_domain, plan_tier, is_active, created_at
674
+ """,
675
+ (body.plan_tier, org_id),
676
+ ).fetchone()
677
+ if not row:
678
+ raise HTTPException(404, "Organization not found")
679
+ logger.info(
680
+ "[admin_routes] platform admin %s set org %s's plan to %s",
681
+ _admin.get("email"), org_id, body.plan_tier,
682
+ )
683
+ return row
684
+
685
+
686
  # ===========================================================================
687
  # Organization admins — who can administer each university's own dashboard.
688
  #
 
753
  raise HTTPException(503, "Data layer unavailable (database not configured)")
754
  with pool.connection() as conn:
755
  org = conn.execute(
756
+ "SELECT id, name, email_domain, plan_tier, is_active, created_at "
757
  "FROM organizations WHERE id = %s",
758
  (org_id,),
759
  ).fetchone()
test_organization_plan.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Verification for PATCH /admin/organizations/{org_id}/plan — changing a
3
+ university's plan tier. Confirmed live against Aurora: organizations.plan_tier
4
+ is a text column with CHECK (plan_tier IN ('free','pro','enterprise')),
5
+ default 'free'.
6
+
7
+ Run with: pytest test_organization_plan.py -v
8
+ """
9
+ import pytest
10
+ from fastapi import FastAPI
11
+ from fastapi.testclient import TestClient
12
+
13
+ import auth
14
+ import admin_routes
15
+
16
+
17
+ class FakeCursor:
18
+ def __init__(self, row=None):
19
+ self._row = row
20
+
21
+ def fetchone(self):
22
+ return self._row
23
+
24
+
25
+ class FakeConn:
26
+ def __init__(self, script):
27
+ self.script = list(script)
28
+ self.calls = []
29
+
30
+ def execute(self, query, params=None):
31
+ self.calls.append((query, params))
32
+ return self.script.pop(0)
33
+
34
+ def __enter__(self):
35
+ return self
36
+
37
+ def __exit__(self, *a):
38
+ return False
39
+
40
+
41
+ class FakePool:
42
+ def __init__(self, conn):
43
+ self._conn = conn
44
+
45
+ def connection(self):
46
+ return self._conn
47
+
48
+
49
+ def _build_app():
50
+ app = FastAPI()
51
+ app.include_router(admin_routes.router, prefix="/admin")
52
+ return app
53
+
54
+
55
+ PLATFORM_ADMIN_EMAIL = "ops@studentcompanionai.rw"
56
+
57
+
58
+ @pytest.fixture
59
+ def client_as_platform_admin(monkeypatch):
60
+ monkeypatch.setattr(auth, "_FIREBASE_READY", True)
61
+ monkeypatch.setattr(
62
+ auth.fb_auth, "verify_id_token", lambda t: {"email": PLATFORM_ADMIN_EMAIL}
63
+ )
64
+ monkeypatch.setattr(auth, "PLATFORM_ADMIN_EMAILS", {PLATFORM_ADMIN_EMAIL})
65
+ return TestClient(_build_app())
66
+
67
+
68
+ def _auth_headers():
69
+ return {"Authorization": "Bearer fake-token"}
70
+
71
+
72
+ def test_platform_admin_can_change_plan(client_as_platform_admin, monkeypatch):
73
+ conn = FakeConn([
74
+ FakeCursor(row={
75
+ "id": "org-ur", "name": "University of Rwanda", "email_domain": "ur.ac.rw",
76
+ "plan_tier": "pro", "is_active": True, "created_at": "2026-09-06T00:00:00Z",
77
+ }),
78
+ ])
79
+ monkeypatch.setattr(admin_routes, "get_pool", lambda: FakePool(conn))
80
+
81
+ resp = client_as_platform_admin.patch(
82
+ "/admin/organizations/org-ur/plan",
83
+ json={"plan_tier": "pro"},
84
+ headers=_auth_headers(),
85
+ )
86
+ assert resp.status_code == 200
87
+ assert resp.json()["plan_tier"] == "pro"
88
+
89
+ update_query, update_params = conn.calls[0]
90
+ assert "%s" in update_query
91
+ assert "pro" in update_params
92
+ assert "org-ur" in update_params
93
+
94
+
95
+ def test_invalid_plan_tier_rejected_before_touching_database(client_as_platform_admin, monkeypatch):
96
+ calls = []
97
+ monkeypatch.setattr(
98
+ admin_routes, "get_pool", lambda: calls.append("called") or FakePool(FakeConn([]))
99
+ )
100
+ resp = client_as_platform_admin.patch(
101
+ "/admin/organizations/org-ur/plan",
102
+ json={"plan_tier": "premium-deluxe"}, # not a real tier
103
+ headers=_auth_headers(),
104
+ )
105
+ assert resp.status_code == 422
106
+ assert calls == [], "should reject before ever querying the database"
107
+
108
+
109
+ def test_unknown_organization_returns_404(client_as_platform_admin, monkeypatch):
110
+ conn = FakeConn([FakeCursor(row=None)])
111
+ monkeypatch.setattr(admin_routes, "get_pool", lambda: FakePool(conn))
112
+ resp = client_as_platform_admin.patch(
113
+ "/admin/organizations/does-not-exist/plan",
114
+ json={"plan_tier": "enterprise"},
115
+ headers=_auth_headers(),
116
+ )
117
+ assert resp.status_code == 404
118
+
119
+
120
+ def test_ordinary_school_admin_cannot_change_their_own_plan(monkeypatch):
121
+ """A school's own admin must not be able to self-upgrade — this stays
122
+ platform-admin only, unlike managing their own org's admin list."""
123
+ monkeypatch.setattr(auth, "_FIREBASE_READY", True)
124
+ monkeypatch.setattr(
125
+ auth.fb_auth, "verify_id_token", lambda t: {"email": "admin@ines.ac.rw"}
126
+ )
127
+ monkeypatch.setattr(auth, "PLATFORM_ADMIN_EMAILS", {PLATFORM_ADMIN_EMAIL})
128
+ client = TestClient(_build_app())
129
+
130
+ resp = client.patch(
131
+ "/admin/organizations/org-ines/plan",
132
+ json={"plan_tier": "enterprise"},
133
+ headers=_auth_headers(),
134
+ )
135
+ assert resp.status_code == 403
136
+
137
+
138
+ def test_no_token_is_rejected(monkeypatch):
139
+ monkeypatch.setattr(auth, "_FIREBASE_READY", True)
140
+ monkeypatch.setattr(auth, "PLATFORM_ADMIN_EMAILS", {PLATFORM_ADMIN_EMAIL})
141
+ client = TestClient(_build_app())
142
+ resp = client.patch(
143
+ "/admin/organizations/org-ur/plan", json={"plan_tier": "pro"}
144
+ )
145
+ assert resp.status_code == 401
146
+
147
+
148
+ @pytest.mark.parametrize("tier", ["free", "pro", "enterprise"])
149
+ def test_each_real_plan_tier_is_accepted(client_as_platform_admin, monkeypatch, tier):
150
+ conn = FakeConn([
151
+ FakeCursor(row={
152
+ "id": "org-x", "name": "X", "email_domain": "x.edu",
153
+ "plan_tier": tier, "is_active": True, "created_at": "2026-09-06T00:00:00Z",
154
+ }),
155
+ ])
156
+ monkeypatch.setattr(admin_routes, "get_pool", lambda: FakePool(conn))
157
+ resp = client_as_platform_admin.patch(
158
+ "/admin/organizations/org-x/plan",
159
+ json={"plan_tier": tier},
160
+ headers=_auth_headers(),
161
+ )
162
+ assert resp.status_code == 200