Files
member-portal/tests/test_allowance_shortfall.py
inference-bot ed66d73327 activation hook: fire Loomio+Matrix syncs at first broker login
New members were skipped by the syncs until their Cloudron account was
activated (deliberately - never invite a half-created account), but nothing
fired the syncs at the moment they DID activate: the 3x/day sweep was the
only pickup, so a newly-activated member could wait hours for forum/space
access (limdingwen waited ~5h on 2026-11-06).

Hook the broker identity path (_verify_broker_secret): after an active
member resolves, if loomio_invited_at is still null, confirm their Cloudron
account is activated (inviteAccepted, fail-CLOSED - an unreadable user list
never fires) and run the same idempotent syncs the sweep runs, as a
background task off the response. Established members pay one indexed
SELECT; concurrent first-logins collapse into one run via an inflight flag;
each service is independently best-effort so a Loomio outage cannot block
the Matrix invite or the response.

Tests: tests/test_first_login_sync.py (18 checks, fixture db + stubbed
network). Also fix test_allowance_shortfall, whose expected exclusion
reference still asserted the pre-a88ca86 placeholder.

Sweep, provisioning and deactivation paths are untouched.
2026-11-06 19:51:12 +00:00

120 lines
5.4 KiB
Python

#!/usr/bin/env python3
"""Regression tests for the allowance-shortfall derivation (OC billing alignment).
Runnable:
* from the repo root: python3 tests/test_allowance_shortfall.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_allowance_shortfall.py
(the container has the app's own dependencies; the host usually does not)
WHY THIS EXISTS
The shortfall credit must be derived FROM DATA and must never be paid twice.
`derive_shortfalls` is pure (no DB, no network, no clock), so the arithmetic,
the per-order boundary, the month-length boundary and the idempotence key are
all exercised directly on synthetic charge ladders.
Covered:
- a truncated first cycle -> one credit, pro-rated to the days lost
- a gap of exactly a full month -> NOT truncated (boundary)
- a gap LONGER than a full month -> NOT truncated (OC deferred a charge)
- credits are NEVER rounded -> 4.5 and 1.5 come out exact
- two orders are judged separately -> a cross-subscription pair is not
mistaken for one truncated cycle
- the reference is the EARLY charge -> it is the idempotence key
"""
import os
import sys
# 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 datetime import datetime, timezone # noqa: E402
from app.main import ( # noqa: E402
derive_shortfalls, shortfall_reason, _usd, SHORTFALL_REMEDIATED,
)
def dt(s):
return datetime.fromisoformat(s + "T00:00:00+00:00")
failures = 0
def check(name, got, want):
global failures
ok = got == want
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
# --- one truncated first cycle: joined/charged 11 Sep, re-aligned to 2 Oct (21d)
recs = [{"slug": "member-a", "order_id": "or_1",
"charges": [(dt("2026-09-11"), "tx_a1"), (dt("2026-10-02"), "tx_a2")]}]
got = derive_shortfalls(recs, budget=15.0)
check("truncated first cycle -> one credit",
[(g["prev"], g["cur"], g["gap_days"], g["days_lost"], g["amount"], g["reference"]) for g in got],
[("2026-09-11", "2026-10-02", 21, 9, 4.5, "tx_a2")])
# --- boundary: a gap of exactly 30 days is a full month -> nothing
recs = [{"slug": "member-b", "order_id": "or_2",
"charges": [(dt("2026-10-02"), "tx_b1"), (dt("2026-11-01"), "tx_b2")]}]
check("gap == full month -> no credit", derive_shortfalls(recs, budget=15.0), [])
# --- a gap LONGER than a month (OC deferred a charge) -> nothing
recs = [{"slug": "member-c", "order_id": "or_3",
"charges": [(dt("2026-09-28"), "tx_c1"), (dt("2026-11-02"), "tx_c2")]}]
check("gap > full month -> no credit", derive_shortfalls(recs, budget=15.0), [])
# --- no rounding: 24-day gap -> 6 days lost -> exact 3.0; 27-day -> 1.5
recs = [{"slug": "member-d", "order_id": "or_4",
"charges": [(dt("2026-10-09"), "tx_d1"), (dt("2026-11-02"), "tx_d2")]}]
check("exact pro-rate, no rounding", [g["amount"] for g in derive_shortfalls(recs, 15.0)], [3.0])
recs = [{"slug": "member-e", "order_id": "or_5",
"charges": [(dt("2026-10-06"), "tx_e1"), (dt("2026-11-02"), "tx_e2")]}]
check("half-dollar stays exact", [g["amount"] for g in derive_shortfalls(recs, 15.0)], [1.5])
# --- per-order boundary: two orders six days apart are NOT one truncated cycle
recs = [
{"slug": "member-f", "order_id": "or_6a", "charges": [(dt("2026-10-16"), "tx_f1")]},
{"slug": "member-f", "order_id": "or_6b", "charges": [(dt("2026-10-22"), "tx_f2")]},
]
check("two subscriptions are judged separately (no cross-order pair)",
derive_shortfalls(recs, budget=15.0), [])
# --- a later (non-first) cycle can be truncated too
recs = [{"slug": "member-g", "order_id": "or_7",
"charges": [(dt("2026-09-02"), "tx_g1"), (dt("2026-10-02"), "tx_g2"),
(dt("2026-10-20"), "tx_g3")]}]
check("a later cycle is caught too",
[(g["prev"], g["cur"], g["reference"]) for g in derive_shortfalls(recs, 15.0)],
[("2026-10-02", "2026-10-20", "tx_g3")])
# --- the reference is the EARLY charge (the idempotence key)
recs = [{"slug": "member-h", "order_id": "or_8",
"charges": [(dt("2026-10-15"), "tx_h1"), (dt("2026-11-02"), "tx_h2")]}]
check("reference is the truncating (second) charge",
[g["reference"] for g in derive_shortfalls(recs, 15.0)], ["tx_h2"])
# --- formatting and reason helpers
check("_usd keeps exact amounts", [_usd(2.0), _usd(4.5), _usd(1.5)], ["$2", "$4.5", "$1.5"])
check("reason names the cycle",
shortfall_reason("2026-10-07", "2026-11-02"),
"allowance shortfall, truncated paid cycle 2026-10-07→2026-11-02 (OC billing alignment)")
# --- the manual-remediation exclusion is keyed on the charge ref alone
# --- (no member PII in this public repo; identity/timeline live in ops docs;
# --- the OC tx id IS the reference key and was approved as such — see the
# --- commit that restored it to match the deployed image)
check("remediated charge excluded by reference",
"tx_Kr6n3rW577OSjr2bIt5IC" in SHORTFALL_REMEDIATED, True)
print(f"\n{'FAILED' if failures else 'OK'} — {failures} failure(s)")
sys.exit(1 if failures else 0)