allowances: recognise YEARLY contributions so a yearly payer isn't read as unpaid
_payment_verdict treated MONTHLY as the only recurring frequency, so a live ACTIVE YEARLY contribution — one charge, current for twelve cycles — fell through to "no recurring (monthly) contribution" and would have been reminded and (with deactivation on) deactivated for eleven of those months. Make the verdict frequency-aware: only a MONTHLY or YEARLY order can cover an allowance cycle; an ACTIVE YEARLY covers while its window (last charge + 1yr, or nextChargeDate) includes now; PROCESSING stays paid-pending; a ONE-TIME payment is credit, never an allowance period and never a mask. A failed monthly charge still takes the remind path. Dormant on today's data: inference-cooperative has 0 yearly orders (104 orders: 88 MONTHLY, 16 ONETIME), verified per member ACCOUNT because a member's own yearly order does not appear in the collective-level order list. This changes no current member's decision — the report is identical before and after. Adds tests/test_payment_verdict.py (yearly branch + monthly/processing/onetime/ error/cancelled cases), runnable in the app container.
This commit is contained in:
1 parent
86e77a0ad4
commit
a984a443e1
2 files changed
+157
-12
No files matched your search
+63
-12
@@ -4176,30 +4176,81 @@ async def fetch_member_orders() -> dict[str, list[dict]]:
|
||||
return by_slug
|
||||
|
||||
|
||||
def _payment_verdict(orders: list[dict], cycle_start: datetime) -> tuple[bool, str]:
|
||||
def _payment_verdict(orders: list[dict], cycle_start: datetime,
|
||||
now: datetime | None = None) -> 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.
|
||||
Frequency-aware. Only a RECURRING contribution (MONTHLY or YEARLY) can cover
|
||||
an allowance cycle; a ONE-TIME payment is credit, not an allowance period, so
|
||||
it is never treated as covering a month and never masks an unpaid member.
|
||||
Returns (paid, evidence).
|
||||
|
||||
Rules, in order:
|
||||
* PROCESSING — a payment is in flight; treated as PAID (a payment mid-flight
|
||||
is not a failure), so a PROCESSING order never triggers a reminder.
|
||||
* ACTIVE MONTHLY — a live subscription; treated as paid even if its next
|
||||
charge is still ahead, so a member whose charge falls due tomorrow does
|
||||
not read as unpaid on every sweep.
|
||||
* ACTIVE YEARLY — paid only while its coverage window contains the current
|
||||
cycle: a year from its last charge, or until its nextChargeDate. A yearly
|
||||
contributor paid once and is current for twelve cycles; a flat monthly
|
||||
test would read them as unpaid (and, with deactivation on, deactivate
|
||||
them) for eleven of those months.
|
||||
* otherwise — judge on the most recent RECURRING charge: within the cycle
|
||||
(7-day slack) is paid, before it is the remind path.
|
||||
|
||||
DORMANT ON TODAY'S DATA: as of 2026-11-04 the collective has no yearly orders
|
||||
(104 orders: 88 MONTHLY, 16 ONETIME, 0 YEARLY — verified per member account,
|
||||
since a member's own yearly order does not appear in the collective-level
|
||||
order list). The yearly branch is defensive robustness for a tier we may add
|
||||
later; it is not a fix for any current member. `now` is injectable for tests.
|
||||
"""
|
||||
monthly = [o for o in orders if (o.get("frequency") or "").upper() == "MONTHLY"]
|
||||
if not monthly:
|
||||
now = now or datetime.now(timezone.utc)
|
||||
|
||||
def _freq(o: dict) -> str:
|
||||
return (o.get("frequency") or "").upper()
|
||||
|
||||
def _status(o: dict) -> str:
|
||||
return (o.get("status") or "").upper()
|
||||
|
||||
recurring = [o for o in orders if _freq(o) in ("MONTHLY", "YEARLY")]
|
||||
if not recurring:
|
||||
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]
|
||||
|
||||
live = [o for o in recurring if _status(o) in ("ACTIVE", "PROCESSING")]
|
||||
# An ACTIVE monthly subscription, or any PROCESSING order, is a live
|
||||
# contribution that covers the cycle (evidence string kept stable so a
|
||||
# report is comparable run to run).
|
||||
live_monthly = [o for o in live if _freq(o) == "MONTHLY" or _status(o) == "PROCESSING"]
|
||||
if live_monthly:
|
||||
charges = [c for c in (_parse_oc_dt(o.get("lastChargedAt")) for o in live_monthly) 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]
|
||||
# An ACTIVE yearly subscription covers the cycle only while its coverage
|
||||
# window (last charge + 1 year, or up to nextChargeDate) still includes now.
|
||||
for o in live:
|
||||
if _freq(o) != "YEARLY":
|
||||
continue
|
||||
lc = _parse_oc_dt(o.get("lastChargedAt"))
|
||||
nc = _parse_oc_dt(o.get("nextChargeDate"))
|
||||
# Coverage runs to the later of (next charge date) and (last charge + 1yr).
|
||||
covered_until = nc
|
||||
if lc:
|
||||
year_end = lc + timedelta(days=365)
|
||||
if covered_until is None or year_end > covered_until:
|
||||
covered_until = year_end
|
||||
if covered_until and now < covered_until:
|
||||
return True, (f"live yearly contribution covers this cycle "
|
||||
f"(last charged {lc.date().isoformat() if lc else 'unknown'}, "
|
||||
f"covers until {covered_until.date().isoformat()})")
|
||||
charged = [(_parse_oc_dt(o.get("lastChargedAt")), _status(o)) for o in recurring]
|
||||
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}))
|
||||
statuses = ",".join(sorted({_status(o) or "?" for o in recurring}))
|
||||
return False, f"no live recurring contribution (order status: {statuses})"
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regression tests for app.main._payment_verdict (allowance payment assessment).
|
||||
|
||||
Self-contained and runnable:
|
||||
|
||||
* from the repo root: python3 tests/test_payment_verdict.py
|
||||
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_payment_verdict.py
|
||||
(the container has the app's own dependencies; the host usually does not)
|
||||
|
||||
Covers the FREQUENCY-AWARE decision:
|
||||
- ACTIVE YEARLY whose coverage window includes the cycle -> paid (renew)
|
||||
[the regression this file exists for]
|
||||
- ACTIVE YEARLY whose year has lapsed -> not paid
|
||||
- ACTIVE MONTHLY -> paid
|
||||
- PROCESSING -> paid (paid-pending; never a reminder)
|
||||
- ONETIME-only -> not paid (credit, not an allowance cycle)
|
||||
- an ONETIME payment does NOT mask an unpaid monthly member
|
||||
- ERROR MONTHLY with the last charge before the cycle -> not paid (mark-meyer's
|
||||
exact order, asserted to keep his current, correct outcome)
|
||||
- CANCELLED MONTHLY with an old charge -> not paid
|
||||
|
||||
Does NOT cover (deliberate): the OC network fetch, the members table / anchor-day
|
||||
storage, email sending, the report/send modes, or deactivation. It tests the pure
|
||||
decision function only. The yearly case is SYNTHETIC: the collective has no yearly
|
||||
orders today, so this guards the branch without implying any member has one.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# Locate the app package: explicit env, the deployed path, or the repo root.
|
||||
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
|
||||
|
||||
from app.main import _payment_verdict # noqa: E402
|
||||
|
||||
NOW = datetime(2026, 11, 4, 12, 0, tzinfo=timezone.utc)
|
||||
CYCLE = datetime(2026, 10, 26, 0, 0, tzinfo=timezone.utc) # mark-meyer join-day 26
|
||||
|
||||
|
||||
def order(freq, status, last=None, next_=None):
|
||||
return {"frequency": freq, "status": status,
|
||||
"lastChargedAt": last, "nextChargeDate": next_}
|
||||
|
||||
|
||||
# (name, orders, expected_paid, evidence_must_contain)
|
||||
CASES = [
|
||||
("active yearly covers this cycle (last charge 2026-09-26, next 2027-09-01)",
|
||||
[order("YEARLY", "ACTIVE", "2026-09-26T18:00:00.000Z", "2027-09-01T00:00:00.000Z")],
|
||||
True, "yearly"),
|
||||
("active yearly whose year has lapsed",
|
||||
[order("YEARLY", "ACTIVE", "2024-01-01T00:00:00.000Z", "2025-01-01T00:00:00.000Z")],
|
||||
False, "before this cycle"),
|
||||
("active monthly",
|
||||
[order("MONTHLY", "ACTIVE", "2026-11-02T18:00:00.000Z", "2026-12-01T00:00:00.000Z")],
|
||||
True, "live recurring contribution"),
|
||||
("processing monthly is paid-pending",
|
||||
[order("MONTHLY", "PROCESSING", "2026-09-16T19:03:08.000Z", "2026-11-01T00:00:00.000Z")],
|
||||
True, "live recurring contribution"),
|
||||
("onetime-only is not an allowance cycle",
|
||||
[order("ONETIME", "PAID", "2026-11-01T00:00:00.000Z", None)],
|
||||
False, "no recurring"),
|
||||
("onetime does not mask an unpaid monthly",
|
||||
[order("ONETIME", "PAID", "2026-11-02T00:00:00.000Z", None),
|
||||
order("MONTHLY", "ERROR", "2026-09-26T18:05:00.000Z", "2026-11-06T00:00:00.000Z")],
|
||||
False, "before this cycle"),
|
||||
("mark-meyer's exact order: monthly ERROR, last charge 2026-09-26",
|
||||
[order("MONTHLY", "ERROR", "2026-09-26T18:05:00.000Z", "2026-11-06T00:00:00.000Z")],
|
||||
False, "last charge 2026-09-26 is before this cycle"),
|
||||
("cancelled monthly with old charge",
|
||||
[order("MONTHLY", "CANCELLED", "2026-08-01T11:05:08.000Z", None)],
|
||||
False, "before this cycle"),
|
||||
("monthly charged within the cycle (7-day slack)",
|
||||
[order("MONTHLY", "ERROR", "2026-10-28T00:00:00.000Z", None)],
|
||||
True, "within the current cycle"),
|
||||
("no orders at all",
|
||||
[],
|
||||
False, "no recurring"),
|
||||
]
|
||||
|
||||
failures = 0
|
||||
for name, orders, expect_paid, expect_text in CASES:
|
||||
paid, evidence = _payment_verdict(orders, CYCLE, now=NOW)
|
||||
ok = (paid == expect_paid) and (expect_text in evidence)
|
||||
if not ok:
|
||||
failures += 1
|
||||
print(f"[{'PASS' if ok else 'FAIL'}] {name}\n"
|
||||
f" paid={paid} (expected {expect_paid}) evidence={evidence!r}")
|
||||
|
||||
print(f"\n{len(CASES) - failures}/{len(CASES)} passed")
|
||||
sys.exit(1 if failures else 0)
|
||||
Reference in new issue
Block a user