credits: infer anchor days for org-backed members
ci/woodpecker/push/woodpecker Pipeline was canceled
ci/woodpecker/push/woodpecker Pipeline was canceled
The allowance reconcile skips rows with org_slug (dues are paid by an OC Organization, not an individual order), so org members never got an anchor_day and close_credit_cycles skipped them forever — their packs regenerated monthly, the same defect as #12. - fetch_org_join_days(): paginated OC members walk, ORGANIZATION accounts only, slug -> membership createdAt. - reconcile_org_anchors(): for every active org-backed row with anchor_day NULL, set anchor = org join day clamped to 1..28 and pin the team reset to its next occurrence. Only NULL rows are touched (idempotent); an org with no OC record is reported, never guessed, and keeps being reported until resolved. - Runs in /admin/sweep and immediately in the org-member webhook path. tests/test_org_anchors.py: anchor math incl. clamp, reset pin, idempotence, unresolved reporting.
This commit is contained in:
1 parent
3d326ed428
commit
0296f8d066
2 files changed
+225
No files matched your search
+111
@@ -5278,6 +5278,13 @@ async def _process_opencollective_webhook(request: Request, token: str):
|
||||
except Exception as e:
|
||||
logger.warning("Webhook: org re-provision failed for %s: %s",
|
||||
org_email, e)
|
||||
# Org rows are skipped by the allowance reconcile, so nothing
|
||||
# else would give this member an anchor day; infer it now
|
||||
# rather than waiting for the next sweep.
|
||||
try:
|
||||
await reconcile_org_anchors()
|
||||
except Exception as e:
|
||||
logger.warning("Webhook: org anchor pass failed: %s", e)
|
||||
else:
|
||||
logger.warning(
|
||||
"Webhook: Membership payment from ORGANIZATION %s (%s) — "
|
||||
@@ -10681,6 +10688,101 @@ async def derive_member_sources() -> dict:
|
||||
return {"checked": len(stale), "flipped": flipped}
|
||||
|
||||
|
||||
async def fetch_org_join_days() -> dict[str, datetime]:
|
||||
"""org slug -> the date that ORGANIZATION joined the collective on OC.
|
||||
|
||||
Organizations never expose an email, so fetch_member_index() drops them and
|
||||
the allowance reconcile skips org-backed rows. That is how an org member ends
|
||||
up with no `anchor_day` — and a credit cycle that can never close.
|
||||
"""
|
||||
if not OC_PERSONAL_TOKEN:
|
||||
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch organization members")
|
||||
out: dict[str, datetime] = {}
|
||||
offset = 0
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
for _ in range(20): # same 100/page cap as the individual walk
|
||||
query = (
|
||||
'{ collective(slug: "%s") { members(limit: 100, offset: %d) { totalCount '
|
||||
"nodes { role createdAt tier { name } account { slug type } } } } }"
|
||||
% (OC_COLLECTIVE_SLUG, offset)
|
||||
)
|
||||
r = await _oc_graphql_post(
|
||||
client, {"query": query}, {"Personal-Token": OC_PERSONAL_TOKEN},
|
||||
)
|
||||
if r.status_code != 200:
|
||||
raise RuntimeError(f"OC organization fetch failed: HTTP {r.status_code}")
|
||||
members = ((r.json().get("data") or {}).get("collective") or {}).get("members") or {}
|
||||
total = members.get("totalCount") or 0
|
||||
nodes = members.get("nodes") or []
|
||||
for n in nodes:
|
||||
acct = n.get("account") or {}
|
||||
slug = (acct.get("slug") or "").strip().lower()
|
||||
if not slug or (acct.get("type") or "").upper() != "ORGANIZATION":
|
||||
continue
|
||||
joined = _parse_oc_dt(n.get("createdAt"))
|
||||
if joined and slug not in out:
|
||||
out[slug] = joined # the join date never moves; first sight wins
|
||||
offset += len(nodes)
|
||||
if not nodes or offset >= total:
|
||||
return out
|
||||
raise RuntimeError("OC organization pagination exceeded 20 pages")
|
||||
|
||||
|
||||
async def reconcile_org_anchors() -> dict:
|
||||
"""Give every org-backed member an anchor day from the ORG's OC join date.
|
||||
|
||||
The allowance reconcile SKIPS rows with `org_slug` (dues are paid by an
|
||||
Organization, not by an individual order), so nothing ever set an anchor day
|
||||
for them and `close_credit_cycles` skipped them forever — their credit packs
|
||||
regenerated every month like everyone else's did before issue #12.
|
||||
|
||||
Anchor = day-of-month of the organization's OC membership `createdAt`,
|
||||
clamped to 1..28; the team reset is pinned to its next occurrence. Idempotent:
|
||||
only rows whose `anchor_day` is NULL are touched. An org with no membership
|
||||
record on OC is REPORTED, never guessed — a wrong anchor moves a member's
|
||||
billing boundary.
|
||||
"""
|
||||
conn = get_db()
|
||||
rows = conn.execute(
|
||||
"SELECT email, org_slug FROM members "
|
||||
"WHERE org_slug IS NOT NULL AND TRIM(org_slug) != '' AND anchor_day IS NULL"
|
||||
).fetchall()
|
||||
conn.close()
|
||||
if not rows:
|
||||
return {"checked": 0, "anchored": [], "unresolved": []}
|
||||
|
||||
try:
|
||||
joins = await fetch_org_join_days()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("reconcile_org_anchors: org fetch failed: %s", exc)
|
||||
return {"checked": len(rows), "anchored": [], "unresolved": [],
|
||||
"error": str(exc)[:200]}
|
||||
|
||||
anchored: list[dict] = []
|
||||
unresolved: list[dict] = []
|
||||
for email, org_slug in rows:
|
||||
joined = joins.get((org_slug or "").strip().lower())
|
||||
if not joined:
|
||||
unresolved.append({"email": email, "org_slug": org_slug})
|
||||
continue
|
||||
anchor = _clamp_anchor_day(joined.day)
|
||||
conn = get_db()
|
||||
try:
|
||||
conn.execute("UPDATE members SET anchor_day = ? WHERE email = ?", (anchor, email))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
try:
|
||||
team_id = await litellm_team_id_for_email(email)
|
||||
if team_id:
|
||||
await litellm_pin_reset_date(team_id, next_reset_for_anchor_day(anchor))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("reconcile_org_anchors: reset pin failed for %s: %s", email, exc)
|
||||
anchored.append({"email": email, "org_slug": org_slug, "anchor_day": anchor,
|
||||
"org_joined": joined.date().isoformat()})
|
||||
return {"checked": len(rows), "anchored": anchored, "unresolved": unresolved}
|
||||
|
||||
|
||||
FX_POLICY_EUR_USD = float(os.environ.get("FX_POLICY_EUR_USD", "1.0975") or 1.0975)
|
||||
FX_ALERT_PCT = float(os.environ.get("FX_ALERT_PCT", "2.0") or 2.0)
|
||||
|
||||
@@ -10782,6 +10884,15 @@ async def admin_sweep(request: Request):
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["allowances"] = {"error": str(exc)[:200]}
|
||||
|
||||
# Org-backed members get no anchor day from the allowance reconcile (it skips
|
||||
# them); infer it from the organization's OC membership date so their credit
|
||||
# cycles can close. Idempotent, and reports orgs with no OC record rather than
|
||||
# guessing a boundary. Wrapped so it can never break reconciliation.
|
||||
try:
|
||||
result["org_anchors"] = await reconcile_org_anchors()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["org_anchors"] = {"error": str(exc)[:200]}
|
||||
|
||||
# Allowance-shortfall credits: OC's billing-day alignment truncates some paid
|
||||
# cycles. Rides the same sweep so a new member is compensated automatically;
|
||||
# credits are idempotent on the OC charge reference. Wrapped so it can never
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/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")
|
||||
Reference in new issue
Block a user