allowances: add a would_deactivate PREVIEW (deactivation stays gated off)

Report mode (and a send run while ALLOWANCE_DEACTIVATE is off) now reports a
member whose reminder is past the grace window as would_deactivate, with the
reminder date, grace length and deadline in the evidence. The real action is
unchanged and still needs BOTH ALLOWANCE_POLICY=on AND ALLOWANCE_DEACTIVATE=on.

The lapse decision is extracted into a pure function (allowance_lapse_decision)
so it is unit-testable against a synthetic reminder time:
tests/test_allowance_lapse.py (would_deactivate past grace; in_grace inside).
This commit is contained in:
inference-bot committed 2026-11-04 18:46:54 +00:00
1 parent ee7ed77697
commit 8c85c912e8
2 files changed
+125 -11

No files matched your search

+52 -11
View File
@@ -4064,6 +4064,10 @@ async def reconcile_memberships() -> dict:
# reminded — no live recurring contribution; one reminder email is sent.
# deactivated — reminded on an earlier pass and still unpaid after the grace
# window; the member loses group access but keeps their account.
# would_* — report mode (and a send run while ALLOWANCE_DEACTIVATE is off)
# writes the `would_` form, including `would_deactivate` for a
# reminder older than the grace window, so the deactivation the
# policy WOULD apply is visible BEFORE the flag is enabled.
# Every decision is written to allowance_log with the Open Collective evidence
# (payment date, or its absence) so a dispute is answered from a record.
ALLOWANCE_POLICY = (os.environ.get("ALLOWANCE_POLICY", "report") or "report").strip().lower()
@@ -4433,6 +4437,32 @@ async def anchor_day_for_member(email: str, slug: str = "") -> int:
return _clamp_anchor_day(datetime.now(timezone.utc).day)
def allowance_lapse_decision(reminder_sent_at, now, grace_days, acting):
"""What to do with a member who was reminded and is still unpaid (pure).
No I/O — `now`, the reminder time and the grace length are all arguments, so
the lapse logic can be unit-tested against a SYNTHETIC reminder time without
touching any member's rows (see tests/test_allowance_lapse.py). Returns
`(decision, deadline)`:
* ("in_grace", None) — the grace window has not elapsed yet.
* ("would_deactivate", deadline) — elapsed, but this caller may not act
(a report run, or ALLOWANCE_DEACTIVATE still off). NOTHING changes.
* ("deactivated", deadline) — elapsed AND the caller is authorised.
`acting` must be True only when BOTH gates hold — a verified send run
(ALLOWANCE_POLICY=on) AND ALLOWANCE_DEACTIVATE=on — so enabling the preview
never by itself removes anyone's access. `deadline` is the moment the grace
window elapses (reminder sent + grace_days), carried into the decision log.
"""
if reminder_sent_at is None:
return "in_grace", None
deadline = reminder_sent_at + timedelta(days=grace_days)
if now < deadline:
return "in_grace", None
return ("deactivated" if acting else "would_deactivate"), deadline
async def reconcile_allowances(send: bool = False) -> dict:
"""Decide every active member's allowance renewal from OC payment evidence.
@@ -4548,12 +4578,29 @@ async def reconcile_allowances(send: bool = False) -> dict:
decision = "remind_failed"
else:
sent_at = _parse_oc_dt(str(reminded[0]))
elapsed = (now - sent_at).days if sent_at else None
if elapsed is not None and elapsed >= PAYMENT_GRACE_DAYS and ALLOWANCE_DEACTIVATE == "on":
decision = label("deactivate")
# Lapse decision is a pure, testable function: past the grace
# window it reports `would_deactivate` in EVERY mode; the real
# action needs `acting` — a verified send run AND the separate
# ALLOWANCE_DEACTIVATE gate. So a report run (and a send run with
# deactivate still off) PREVIEWS the deactivation and changes
# nobody's access.
acting = verified == "on" and ALLOWANCE_DEACTIVATE == "on"
lapse, deadline = allowance_lapse_decision(
sent_at, now, PAYMENT_GRACE_DAYS, acting)
if lapse == "in_grace":
decision = "in_grace"
counts["in_grace"] += 1
evidence = (f"{evidence}; reminder sent "
f"{str(reminded[0])[:10] if reminded[0] else '?'} "
f"(grace {int(PAYMENT_GRACE_DAYS)}d)")
else:
decision = lapse # would_deactivate | deactivated
counts[decision] += 1
evidence = f"{evidence}; reminder sent {str(reminded[0])[:10]}, grace {int(PAYMENT_GRACE_DAYS)}d elapsed"
if verified == "on":
dl = deadline.date().isoformat() if deadline else "?"
evidence = (f"{evidence}; reminder sent {str(reminded[0])[:10]}, "
f"grace {int(PAYMENT_GRACE_DAYS)}d elapsed, "
f"deadline {dl}")
if decision == "deactivated":
urow = conn.execute(
"SELECT cloudron_user_id FROM members WHERE email = ?", (email,)
).fetchone()
@@ -4562,12 +4609,6 @@ async def reconcile_allowances(send: bool = False) -> dict:
deactivate_member(email)
await revoke_member_litellm_access(email)
await listmonk_sync(email, subscribe=False)
else:
decision = "in_grace"
counts["in_grace"] += 1
evidence = (f"{evidence}; reminder sent "
f"{str(reminded[0])[:10] if reminded[0] else '?'} "
f"(grace {int(PAYMENT_GRACE_DAYS)}d)")
conn.execute(
"INSERT INTO allowance_log (email, cycle, decision, evidence, anchor_day)"
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Regression tests for app.main.allowance_lapse_decision (grace/deactivation).
Self-contained and runnable:
* from the repo root: python3 tests/test_allowance_lapse.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_allowance_lapse.py
(the container has the app's own dependencies; the host usually does not)
WHY THIS EXISTS
Deactivation is gated OFF (ALLOWANCE_DEACTIVATE=off) and the flag must stay
off until the preview is trusted. That makes the live preview legitimately
show ZERO past-grace members right after a reminder, so this file proves the
decision logic on a SYNTHETIC reminder time instead of waiting a week — and
without altering any real member's rows.
The decision is a pure function (no DB, no network, no clock), so a past
reminder, a grace boundary and the "armed" case are all exercised directly:
- reminder 10 days ago, NOT authorised -> ("would_deactivate", deadline)
[the preview this change adds]
- reminder 3 days ago (inside grace) -> ("in_grace", None)
- reminder exactly at the grace edge -> ("would_deactivate", deadline)
- reminder one second inside the edge -> ("in_grace", None)
- reminder 10 days ago, AUTHORISED -> ("deactivated", deadline)
[the real path, unchanged: needs policy=on AND deactivate=on]
- no reminder at all -> ("in_grace", None)
"""
import os
import sys
from datetime import datetime, timedelta, 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 allowance_lapse_decision # noqa: E402
NOW = datetime(2026, 11, 4, 12, 0, tzinfo=timezone.utc)
GRACE = 7.0
# (name, reminder_sent_at, acting, expected_decision, expected_deadline)
CASES = [
("reminder 10d ago, not authorised -> would_deactivate (preview)",
NOW - timedelta(days=10), False, "would_deactivate", NOW - timedelta(days=10) + timedelta(days=7)),
("reminder 3d ago (inside grace) -> in_grace",
NOW - timedelta(days=3), False, "in_grace", None),
("reminder exactly 7d ago (at the edge) -> would_deactivate",
NOW - timedelta(days=7), False, "would_deactivate", NOW),
("reminder 6d23h ago (one hour inside grace) -> in_grace",
NOW - timedelta(days=6, hours=23), False, "in_grace", None),
("reminder 10d ago, AUTHORISED -> deactivated (real path)",
NOW - timedelta(days=10), True, "deactivated", NOW - timedelta(days=10) + timedelta(days=7)),
("no reminder ever sent -> in_grace",
None, False, "in_grace", None),
]
failures = 0
for name, sent_at, acting, expect_dec, expect_dl in CASES:
decision, deadline = allowance_lapse_decision(sent_at, NOW, GRACE, acting)
dl_ok = (deadline == expect_dl)
ok = (decision == expect_dec) and dl_ok
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}\n"
f" decision={decision} (expected {expect_dec}) "
f"deadline={deadline} (expected {expect_dl}) acting={acting}")
print(f"\n{len(CASES) - failures}/{len(CASES)} passed")
sys.exit(1 if failures else 0)