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
|
||||
|
||||
Reference in new issue
Block a user