allowances: restore fetch_member_orders/_payment_verdict/payment_reminder_email dropped in the slug fix

This commit is contained in:
inference-bot committed 2026-11-04 05:17:12 +00:00
1 parent ea4660690d
commit d878c32d68
1 file changed
+122
+122
View File
@@ -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"""<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin:0;padding:0;background:#faf8f5;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#faf8f5;padding:40px 16px;">
<tr>
<td align="center">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;">
<tr>
<td align="center" style="padding-bottom:24px;">
{PINE_LOGO_SVG}
</td>
</tr>
<tr>
<td align="center" style="background:#ffffff;border:1px solid #e8e2d8;border-radius:16px;padding:40px 32px;">
<h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">Your membership needs attention</h1>
<p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">Our records at Open Collective don't show a current monthly contribution for your account, so your monthly allowance won't renew.</p>
<p style="margin:0 0 28px;font-size:15px;color:#6b7a62;line-height:1.5;">To keep your access, restart or update your contribution. If your payment has already gone through, ignore this.</p>
<a href="{contribute_url}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:999px;font-size:16px;font-weight:600;">Update your contribution</a>
<p style="margin:28px 0 0;font-size:13px;color:#94a08c;line-height:1.5;">If we don't see a contribution after a short grace period, your account stays in place but loses access until your contribution resumes.</p>
</td>
</tr>
<tr>
<td align="center" style="padding-top:24px;font-size:13px;color:#94a08c;line-height:1.6;">
Questions? Reply to this email or write to <a href="mailto:info@inference.coop" style="color:#6b7a62;">info@inference.coop</a>.<br>
<span style="color:#2d3327;">The Inference Cooperative</span> &middot; inference.coop
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>"""
return subject, text, html
async def fetch_member_index() -> dict[str, dict]:
"""email -> {slug, joined, role, tier} from the live OC member list.