#!/usr/bin/env python3 """Regression tests for org-backed anchor days. Runnable: * inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_org_anchors.py * from the repo root, on a host that has the app's dependencies WHY THIS EXISTS The allowance reconcile SKIPS rows with `org_slug` (dues are paid by an OC Organization, not an individual order), so org-backed members never got an `anchor_day` — and close_credit_cycles skipped them forever, restoring their credit packs every month. The fix infers the anchor from the ORGANIZATION's OC membership createdAt. Covered: - anchor = org join day, clamped to 28 - the team reset is pinned to the next occurrence - idempotent: a second pass touches nothing - an org with no OC membership record is reported, never guessed """ import asyncio import os import sys import tempfile from datetime import datetime, timezone _TEST_DB = os.path.join(tempfile.mkdtemp(prefix="organchor-test-"), "members.db") os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code", os.path.dirname(os.path.dirname(os.path.abspath(__file__)))): if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")): sys.path.insert(0, _cand) break import app.main as m # noqa: E402 failures = 0 def check(name, got, want): global failures ok = got == want if not ok: failures += 1 print(f"[{'PASS' if ok else 'FAIL'}] {name}") if not ok: print(f" got {got!r}\n want {want!r}") pins = [] async def fake_org_joins(): return { "cosmos": datetime(2026, 10, 15, 23, 52, tzinfo=timezone.utc), "late": datetime(2026, 1, 31, 12, 0, tzinfo=timezone.utc), } async def fake_team_id(email): return f"team:{email}" async def fake_pin(team_id, reset_at): pins.append((team_id, reset_at.isoformat())) m.fetch_org_join_days = fake_org_joins m.litellm_team_id_for_email = fake_team_id m.litellm_pin_reset_date = fake_pin conn = m.get_db() m._ensure_allowance_tables(conn) # creates allowance_log and adds anchor_day conn.execute( "INSERT INTO members (email, key_token, active, account_type, org_slug) " "VALUES ('tech@cosmos.coop', '', 1, 'member', 'cosmos')") conn.execute( "INSERT INTO members (email, key_token, active, account_type, org_slug) " "VALUES ('ops@late.org', '', 1, 'member', 'late')") conn.execute( "INSERT INTO members (email, key_token, active, account_type, org_slug) " "VALUES ('x@unknown.org', '', 1, 'member', 'unknown-org')") conn.execute( "INSERT INTO members (email, key_token, active, account_type, org_slug, anchor_day) " "VALUES ('already@set.org', '', 1, 'member', 'cosmos', 7)") conn.commit() conn.close() first = asyncio.run(m.reconcile_org_anchors()) anchors = {r["email"]: r["anchor_day"] for r in first["anchored"]} check("org join day 15 -> anchor 15", anchors.get("tech@cosmos.coop"), 15) check("org join day 31 -> clamped to 28", anchors.get("ops@late.org"), 28) check("an org with no OC record is reported, not guessed", [u["email"] for u in first["unresolved"]], ["x@unknown.org"]) check("an already-anchored row is untouched", "already@set.org" not in anchors, True) reset = dict((t, r) for t, r in pins) check("reset pinned to the next occurrence of the anchor day (Dec 15)", reset.get("team:tech@cosmos.coop", "")[:10], "2026-12-15") second = asyncio.run(m.reconcile_org_anchors()) check("second pass leaves only the unresolved org to report", second["checked"], 1) check("second pass writes no anchors", second["anchored"], []) check("the unresolved org is reported again, not silently dropped", [u["email"] for u in second["unresolved"]], ["x@unknown.org"]) row = m.get_db().execute( "SELECT anchor_day FROM members WHERE email = 'tech@cosmos.coop'").fetchone() check("anchor persisted", row[0], 15) print() if failures: print(f"{failures} FAILURE(S)") sys.exit(1) print("all checks passed")