From d878c32d68c71b557f9e23d9d86d15020846337a Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Wed, 4 Nov 2026 05:17:12 +0000 Subject: [PATCH] allowances: restore fetch_member_orders/_payment_verdict/payment_reminder_email dropped in the slug fix --- app/main.py | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/app/main.py b/app/main.py index 145dd77..0947c93 100644 --- a/app/main.py +++ b/app/main.py @@ -4135,6 +4135,128 @@ def cycle_start_for_anchor_day(anchor_day: int, now: datetime | None = None) -> +async def fetch_member_orders() -> dict[str, list[dict]]: + """Every OC order for the collective, grouped by the payer's slug. + + One query for the whole collective (orders(limit: 200)) rather than a call + per member. Raises on failure so the caller can skip rather than mis-decide. + """ + if not OC_PERSONAL_TOKEN: + raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch orders") + query = ( + '{ collective(slug: "%s") { orders(limit: 200) { totalCount nodes { ' + "frequency status createdAt lastChargedAt nextChargeDate " + "fromAccount { slug } totalAmount { value currency } } } } }" + % OC_COLLECTIVE_SLUG + ) + async with httpx.AsyncClient(timeout=30.0) as client: + r = await client.post( + OC_GRAPHQL_URL, + headers={"Content-Type": "application/json", + "Authorization": f"Bearer {OC_PERSONAL_TOKEN}", + "Api-Version": "2022-01-01", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"}, + json={"query": query}, + ) + if r.status_code != 200: + raise RuntimeError(f"OC order fetch failed: HTTP {r.status_code}") + body = r.json() + if body.get("errors"): + raise RuntimeError(f"OC order fetch errors: {str(body['errors'])[:200]}") + orders = (((body.get("data") or {}).get("collective") or {}).get("orders") or {}) + by_slug: dict[str, list[dict]] = {} + for o in orders.get("nodes") or []: + slug = ((o.get("fromAccount") or {}).get("slug") or "").strip() + if slug: + by_slug.setdefault(slug, []).append(o) + return by_slug + + +def _payment_verdict(orders: list[dict], cycle_start: datetime) -> tuple[bool, str]: + """Did this member's recurring contribution pay for the current cycle? + + Returns (paid, evidence). A PROCESSING order counts as PAID (a payment in + flight is not a missed payment). A live ACTIVE recurring contribution is + treated as paid even if its next charge is still ahead — otherwise a member + whose charge falls due tomorrow reads as unpaid on every sweep. + """ + monthly = [o for o in orders if (o.get("frequency") or "").upper() == "MONTHLY"] + if not monthly: + return False, "no recurring (monthly) contribution on Open Collective" + live = [o for o in monthly if (o.get("status") or "").upper() in ("ACTIVE", "PROCESSING")] + if live: + charges = [c for c in (_parse_oc_dt(o.get("lastChargedAt")) for o in live) if c] + last = max(charges).date().isoformat() if charges else "unknown" + return True, f"live recurring contribution (last charged {last})" + charged = [(_parse_oc_dt(o.get("lastChargedAt")), o.get("status")) for o in monthly] + charged = [(c, s) for c, s in charged if c] + if charged: + last_dt, _ = max(charged, key=lambda t: t[0]) + if last_dt >= cycle_start - timedelta(days=7): + return True, f"charged {last_dt.date().isoformat()} within the current cycle" + return False, f"last charge {last_dt.date().isoformat()} is before this cycle" + statuses = ",".join(sorted({(o.get("status") or "?").upper() for o in monthly})) + return False, f"no live recurring contribution (order status: {statuses})" + + +def payment_reminder_email(name: str, contribute_url: str) -> tuple[str, str, str]: + """Build the one-per-cycle 'we haven't seen your contribution' reminder. + + Same shell as welcome_email()/budget_notice_email(): cream background, white + card, forest-green button, inline pine-tree mark, table-based, no external + assets. Plain and direct — it names the action, not the plumbing. + """ + subject = "Your Inference Cooperative membership needs attention" + text = ( + f"Hi {name},\n\n" + "Our records at Open Collective don't show a current monthly contribution " + "for your account, so your monthly allowance won't renew.\n\n" + "To keep your access, restart or update your contribution here:\n\n" + f"{contribute_url}\n\n" + "If your payment has already gone through, ignore this — your allowance " + "will renew on its own. If we don't see a contribution after a short grace " + "period, your account stays in place but loses access until your " + "contribution resumes.\n\n" + "Questions? Reply to this email or write to info@inference.coop.\n\n" + "— The Inference Cooperative\n" + ) + html = f""" + + + + + + + +
+ + + + + + + + + + +
+ {PINE_LOGO_SVG} +
+

Your membership needs attention

+

Our records at Open Collective don't show a current monthly contribution for your account, so your monthly allowance won't renew.

+

To keep your access, restart or update your contribution. If your payment has already gone through, ignore this.

+ Update your contribution +

If we don't see a contribution after a short grace period, your account stays in place but loses access until your contribution resumes.

+
+ Questions? Reply to this email or write to info@inference.coop.
+ The Inference Cooperative · inference.coop +
+
+ +""" + return subject, text, html + + async def fetch_member_index() -> dict[str, dict]: """email -> {slug, joined, role, tier} from the live OC member list.