Compare commits
37
Commits
146bfaf45e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b7a74d891 | ||
|
|
205c695556 | ||
|
|
3db67e54f3 | ||
|
|
bbd8115058 | ||
|
|
ca336a3115 | ||
|
|
122824fd99 | ||
|
|
1191bcd521 | ||
|
|
aba53eabb5 | ||
|
|
fb6af42bbf | ||
|
|
6124d05ffd | ||
|
|
d10b36ed34 | ||
|
|
066a6fc2cf | ||
|
|
a70dd6ab4c | ||
|
|
cfb767dd4f | ||
|
|
18a4447aa2 | ||
|
|
dc53b27ad2 | ||
|
|
3e01f727c2 | ||
|
|
1070fc5dd0 | ||
|
|
0296f8d066 | ||
|
|
3d326ed428 | ||
|
|
97f0d6c3f1 | ||
|
|
237b695087 | ||
|
|
fe898905b4 | ||
|
|
bcdc0416e2 | ||
|
|
0e53c330e1 | ||
|
|
9ab8156da2 | ||
|
|
a3bfc56b77 | ||
|
|
c174cba5ce | ||
|
|
b3de608170 | ||
|
|
f1ba9d7313 | ||
|
|
419b1f4322 | ||
|
|
d190aa7762 | ||
|
|
db0c09e85d | ||
|
|
3ccaf0ec85 | ||
|
|
c60dc2c482 | ||
|
|
f09bec67d8 | ||
|
|
ffed06d492 |
No files matched your search
@@ -25,11 +25,19 @@
|
|||||||
"metrics_snapshot": {
|
"metrics_snapshot": {
|
||||||
"schedule": "15 3 * * *",
|
"schedule": "15 3 * * *",
|
||||||
"command": "/app/code/metrics_snapshot.py"
|
"command": "/app/code/metrics_snapshot.py"
|
||||||
|
},
|
||||||
|
"credit_cycle_close": {
|
||||||
|
"schedule": "*/10 * * * *",
|
||||||
|
"command": "/app/code/credit_cycle_close.sh"
|
||||||
|
},
|
||||||
|
"loomio_inbound": {
|
||||||
|
"schedule": "*/2 * * * *",
|
||||||
|
"command": "/app/code/loomio_inbound.py"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"manifestVersion": 2,
|
"manifestVersion": 2,
|
||||||
"website": "https://inference.coop",
|
"website": "https://inference.coop",
|
||||||
"contactEmail": "info@inference.coop",
|
"contactEmail": "info@inference.coop",
|
||||||
"dockerImage": "registry.inference.coop/code/member-portal:20261121-b761136"
|
"dockerImage": "registry.inference.coop/code/member-portal:20261203-3db67e5"
|
||||||
}
|
}
|
||||||
+3
-1
@@ -10,8 +10,10 @@ RUN pip install --no-cache-dir -r requirements.txt
|
|||||||
COPY app/ ./app/
|
COPY app/ ./app/
|
||||||
COPY sweep.sh /app/code/sweep.sh
|
COPY sweep.sh /app/code/sweep.sh
|
||||||
COPY service_sync.sh /app/code/service_sync.sh
|
COPY service_sync.sh /app/code/service_sync.sh
|
||||||
|
COPY credit_cycle_close.sh /app/code/credit_cycle_close.sh
|
||||||
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
|
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
|
||||||
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/metrics_snapshot.py
|
COPY loomio_inbound.py /app/code/loomio_inbound.py
|
||||||
|
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/credit_cycle_close.sh /app/code/metrics_snapshot.py /app/code/loomio_inbound.py
|
||||||
|
|
||||||
# Run as root (the base image default). Cloudron's sandboxing (read-only
|
# Run as root (the base image default). Cloudron's sandboxing (read-only
|
||||||
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
|
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ points. Remaining work before production:
|
|||||||
|
|
||||||
## Scheduled tasks (scheduler addon)
|
## Scheduled tasks (scheduler addon)
|
||||||
|
|
||||||
Four jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
|
Five jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
|
||||||
|
|
||||||
- **membership_sweep** (`0 3,11,19 * * *` UTC — three times a day) — `sweep.sh`
|
- **membership_sweep** (`0 3,11,19 * * *` UTC — three times a day) — `sweep.sh`
|
||||||
calls the portal's own `/admin/sweep` (auth: the `X-Admin-Token` header with
|
calls the portal's own `/admin/sweep` (auth: the `X-Admin-Token` header with
|
||||||
@@ -315,8 +315,18 @@ Four jobs run inside the container via `CloudronManifest.json` → `addons.sched
|
|||||||
only, leaving the membership curve as the nightly snapshots measured it.
|
only, leaving the membership curve as the nightly snapshots measured it.
|
||||||
Methodology: [Energy and carbon metrics](docs/energy-metrics.md).
|
Methodology: [Energy and carbon metrics](docs/energy-metrics.md).
|
||||||
|
|
||||||
|
- **loomio_inbound** (every 2 minutes) — `loomio_inbound.py` polls the
|
||||||
|
`replies@forum-reply.inference.coop` catch-all mailbox over IMAPS and POSTs
|
||||||
|
each raw message to Loomio's ActionMailbox relay
|
||||||
|
(`/rails/action_mailbox/relay/inbound_emails`, Basic auth
|
||||||
|
`actionmailbox:$RAILS_INBOUND_EMAIL_PASSWORD`). Cloudron's Loomio package has
|
||||||
|
no inbound receiver (Haraka needs port 25), so this is the reply-by-email
|
||||||
|
bridge. Env: `LOOMIO_INBOUND_IMAP_HOST/PORT/USERNAME/PASSWORD` and
|
||||||
|
`LOOMIO_INBOUND_RELAY_URL/PASSWORD`; processed messages are marked Seen and
|
||||||
|
purged after 30 days (`LOOMIO_INBOUND_KEEP_DAYS`).
|
||||||
|
|
||||||
Verify after any manifest change: the deploy log must show
|
Verify after any manifest change: the deploy log must show
|
||||||
`setupAddons: ... scheduler ...` listing all four tasks, and each script must
|
`setupAddons: ... scheduler ...` listing all five tasks, and each script must
|
||||||
succeed when run manually inside the container.
|
succeed when run manually inside the container.
|
||||||
|
|
||||||
### Allowance renewal (payment-driven, join-day anchored)
|
### Allowance renewal (payment-driven, join-day anchored)
|
||||||
|
|||||||
+1196
-105
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Credit cycle close — run by the Cloudron scheduler addon every 10 minutes.
|
||||||
|
#
|
||||||
|
# Calls the portal's own /admin/credit-cycle-close endpoint (localhost), which
|
||||||
|
# walks each active member's completed allowance cycles and draws the credits
|
||||||
|
# those cycles spent (issue #12: a monthly reset used to restore every credit
|
||||||
|
# pack, because nothing ever recorded what usage consumed).
|
||||||
|
#
|
||||||
|
# Idempotent: each closed cycle is keyed by the ledger reference
|
||||||
|
# `cycle-close:<email>:<cycle>`, so an overlapping tick or a restart never
|
||||||
|
# charges a cycle twice. Cheap: one SELECT when nobody has credits.
|
||||||
|
#
|
||||||
|
# The ADMIN_TOKEN env var is shared with the main app (scheduler runs in the
|
||||||
|
# same launch environment), so we use it to authenticate. Admin auth is a
|
||||||
|
# header, never a URL token.
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
if [ -z "$ADMIN_TOKEN" ]; then
|
||||||
|
echo "credit-cycle-close: ADMIN_TOKEN is not set; aborting" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
python3 - "$ADMIN_TOKEN" <<'PY'
|
||||||
|
import sys, urllib.request, urllib.error
|
||||||
|
|
||||||
|
token = sys.argv[1]
|
||||||
|
url = "http://127.0.0.1:8000/admin/credit-cycle-close"
|
||||||
|
req = urllib.request.Request(url, method="POST", data=b"", headers={
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Admin-Token": token,
|
||||||
|
})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=300) as resp:
|
||||||
|
print("credit-cycle-close:", resp.read().decode())
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
print(f"credit-cycle-close: HTTP {e.code}: {e.read().decode()}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"credit-cycle-close: request failed: {e}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
PY
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Relay Loomio reply-by-email messages from Cloudron mail into Loomio.
|
||||||
|
|
||||||
|
Loomio's notification Reply-To addresses look like
|
||||||
|
d=<discussion>&u=<user>&k=<email_api_key>@forum-reply.inference.coop
|
||||||
|
Cloudron's Loomio package has no inbound mail receiver (upstream Haraka needs
|
||||||
|
port 25, which Cloudron cannot expose), so this job polls the catch-all mailbox
|
||||||
|
and hands each raw message to Loomio's ActionMailbox relay endpoint.
|
||||||
|
|
||||||
|
Runs from the Cloudron scheduler addon. Env comes from the portal app's launch
|
||||||
|
environment (same secrets the app process sees).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import imaplib
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
|
||||||
|
def required(name: str) -> str:
|
||||||
|
value = os.environ.get(name)
|
||||||
|
if not value:
|
||||||
|
raise SystemExit(f"loomio-inbound: {name} is not set")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
IMAP_HOST = os.environ.get("LOOMIO_INBOUND_IMAP_HOST", "my.inference.coop")
|
||||||
|
IMAP_PORT = int(os.environ.get("LOOMIO_INBOUND_IMAP_PORT", "993"))
|
||||||
|
IMAP_USER = required("LOOMIO_INBOUND_IMAP_USERNAME")
|
||||||
|
IMAP_PASSWORD = required("LOOMIO_INBOUND_IMAP_PASSWORD")
|
||||||
|
RELAY_URL = os.environ.get(
|
||||||
|
"LOOMIO_INBOUND_RELAY_URL",
|
||||||
|
"https://forum.inference.coop/rails/action_mailbox/relay/inbound_emails",
|
||||||
|
)
|
||||||
|
RELAY_PASSWORD = required("LOOMIO_INBOUND_RELAY_PASSWORD")
|
||||||
|
MAX_PER_RUN = int(os.environ.get("LOOMIO_INBOUND_MAX", "50"))
|
||||||
|
KEEP_DAYS = int(os.environ.get("LOOMIO_INBOUND_KEEP_DAYS", "30"))
|
||||||
|
|
||||||
|
|
||||||
|
def relay(raw: bytes) -> int:
|
||||||
|
auth = base64.b64encode(f"actionmailbox:{RELAY_PASSWORD}".encode()).decode()
|
||||||
|
req = Request(
|
||||||
|
RELAY_URL,
|
||||||
|
data=raw,
|
||||||
|
method="POST",
|
||||||
|
headers={
|
||||||
|
"Authorization": f"Basic {auth}",
|
||||||
|
"Content-Type": "message/rfc822",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
with urlopen(req, timeout=60) as resp:
|
||||||
|
return resp.status
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_raw(imap: imaplib.IMAP4_SSL, uid: str) -> bytes:
|
||||||
|
typ, data = imap.uid("FETCH", uid, "(BODY.PEEK[])")
|
||||||
|
if typ != "OK":
|
||||||
|
raise RuntimeError(f"FETCH failed: {typ}")
|
||||||
|
for item in data or []:
|
||||||
|
if isinstance(item, tuple) and len(item) >= 2 and isinstance(item[1], (bytes, bytearray)):
|
||||||
|
return bytes(item[1])
|
||||||
|
raise RuntimeError("FETCH returned no message body")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
imap = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, ssl_context=ctx)
|
||||||
|
try:
|
||||||
|
imap.login(IMAP_USER, IMAP_PASSWORD)
|
||||||
|
typ, data = imap.select("INBOX")
|
||||||
|
if typ != "OK":
|
||||||
|
raise RuntimeError(f"SELECT INBOX failed: {typ}")
|
||||||
|
|
||||||
|
typ, data = imap.uid("SEARCH", "UNSEEN")
|
||||||
|
if typ != "OK":
|
||||||
|
raise RuntimeError(f"SEARCH UNSEEN failed: {typ}")
|
||||||
|
uids = (data[0].split() if data and data[0] else [])[:MAX_PER_RUN]
|
||||||
|
print(f"loomio-inbound: {len(uids)} unseen message(s)")
|
||||||
|
|
||||||
|
relayed = 0
|
||||||
|
for uid in uids:
|
||||||
|
try:
|
||||||
|
raw = fetch_raw(imap, uid.decode())
|
||||||
|
status = relay(raw)
|
||||||
|
imap.uid("STORE", uid.decode(), "+FLAGS", "(\\Seen)")
|
||||||
|
relayed += 1
|
||||||
|
print(f"loomio-inbound: uid {uid.decode()} relayed ({status}, {len(raw)} bytes)")
|
||||||
|
except HTTPError as exc:
|
||||||
|
print(
|
||||||
|
f"loomio-inbound: uid {uid.decode()} relay HTTP {exc.code}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
if exc.code in (401, 403):
|
||||||
|
return 1
|
||||||
|
except Exception as exc: # keep the message unseen for the next tick
|
||||||
|
print(
|
||||||
|
f"loomio-inbound: uid {uid.decode()} failed: "
|
||||||
|
f"{type(exc).__name__}: {exc}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
cutoff = (datetime.now(timezone.utc) - timedelta(days=KEEP_DAYS)).strftime("%d-%b-%Y")
|
||||||
|
typ, data = imap.uid("SEARCH", f"SEEN BEFORE {cutoff}")
|
||||||
|
old = data[0].split() if typ == "OK" and data and data[0] else []
|
||||||
|
for uid in old:
|
||||||
|
imap.uid("STORE", uid.decode(), "+FLAGS", "(\\Deleted)")
|
||||||
|
if old:
|
||||||
|
imap.expunge()
|
||||||
|
print(f"loomio-inbound: relayed={relayed} purged={len(old)}")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"loomio-inbound: purge skipped: {type(exc).__name__}: {exc}", file=sys.stderr)
|
||||||
|
|
||||||
|
return 0
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
imap.logout()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -77,6 +77,10 @@ try:
|
|||||||
f"member side is the member: teams ($10.005 + $5.005 -> 15.01, got {t['member_all_time_spend']})")
|
f"member side is the member: teams ($10.005 + $5.005 -> 15.01, got {t['member_all_time_spend']})")
|
||||||
check(t["own_all_time_spend"] == 2.59,
|
check(t["own_all_time_spend"] == 2.59,
|
||||||
f"own side is everything else: agents, sandboxes, unattributed (got {t['own_all_time_spend']})")
|
f"own side is everything else: agents, sandboxes, unattributed (got {t['own_all_time_spend']})")
|
||||||
|
check(t["own_unattributed_spend"] == 1.07,
|
||||||
|
f"rows that join to no team alias are named, not left as a silent remainder (got {t['own_unattributed_spend']})")
|
||||||
|
check(t["own_unattributed_spend"] <= t["own_all_time_spend"],
|
||||||
|
"unattributed is a part of own, never added on top of the total")
|
||||||
check(t["spend_all_time"] == round(t["member_all_time_spend"] + t["own_all_time_spend"], 2),
|
check(t["spend_all_time"] == round(t["member_all_time_spend"] + t["own_all_time_spend"], 2),
|
||||||
"total == member + own, so no dollar is counted twice or dropped")
|
"total == member + own, so no dollar is counted twice or dropped")
|
||||||
check(t["spend_all_time"] == round(sum(r[1] for r in ROWS), 2),
|
check(t["spend_all_time"] == round(sum(r[1] for r in ROWS), 2),
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for credit cycle close (issue #12).
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_credit_cycle_close.py
|
||||||
|
* from the repo root, on a host that has the app's dependencies
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
LiteLLM zeroes a team's `spend` at budget_reset_at and leaves max_budget
|
||||||
|
alone, and nothing ever reduced `credit_balance`. Result: a member who bought
|
||||||
|
a $50 pack and spent it got the $50 back at the next monthly reset — the
|
||||||
|
allowance returned to $65 instead of $15, forever. Covered here:
|
||||||
|
- the cap is allowance + credits STILL AVAILABLE (drawn in closed cycles)
|
||||||
|
- spend inside the CURRENT cycle never shrinks the cap (the inversion bug)
|
||||||
|
- closing a cycle draws the overage once, and a replay draws nothing
|
||||||
|
- a draw is capped by the credits actually available
|
||||||
|
- the issue's worked example end-to-end
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditclose-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
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 ( # noqa: E402
|
||||||
|
_prev_month, add_credits, apply_cycle_draw, compute_max_budget,
|
||||||
|
cycle_start_for_anchor_day, get_credit_balance, get_credits_drawn, get_db,
|
||||||
|
)
|
||||||
|
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|
||||||
|
def close(a, b):
|
||||||
|
return round(float(a), 6) == round(float(b), 6)
|
||||||
|
|
||||||
|
|
||||||
|
def check_near(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = close(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}")
|
||||||
|
|
||||||
|
|
||||||
|
# --- cycle boundary math ---------------------------------------------------
|
||||||
|
check("_prev_month steps back across a year boundary",
|
||||||
|
_prev_month(datetime(2026, 1, 1, tzinfo=timezone.utc)).isoformat(),
|
||||||
|
datetime(2025, 12, 1, tzinfo=timezone.utc).isoformat())
|
||||||
|
check("cycle_start_for_anchor_day is the last occurrence at/before now",
|
||||||
|
cycle_start_for_anchor_day(28, datetime(2026, 11, 27, 12, tzinfo=timezone.utc)).isoformat(),
|
||||||
|
datetime(2026, 10, 28, tzinfo=timezone.utc).isoformat())
|
||||||
|
|
||||||
|
# --- cap arithmetic --------------------------------------------------------
|
||||||
|
# allowance $15 + $50 pack, nothing drawn, fresh cycle
|
||||||
|
eff = compute_max_budget(15, 50, 0.0, 0.0)
|
||||||
|
check_near("fresh cycle cap = allowance + pack", eff["max_budget"], 65.0)
|
||||||
|
check_near("fresh cycle credits remaining = pack", eff["credits_remaining"], 50.0)
|
||||||
|
|
||||||
|
# mid-cycle spend NEVER shrinks the cap (the inversion bug)
|
||||||
|
mid = compute_max_budget(15, 50, 40.0, 0.0)
|
||||||
|
check_near("mid-cycle cap unchanged as credits burn", mid["max_budget"], 65.0)
|
||||||
|
check_near("mid-cycle credits used derived from spend", mid["credits_used"], 25.0)
|
||||||
|
check_near("mid-cycle credits remaining = pack - used", mid["credits_remaining"], 25.0)
|
||||||
|
|
||||||
|
# after the cycle closes with $50 drawn
|
||||||
|
after = compute_max_budget(15, 50, 0.0, 50.0)
|
||||||
|
check_near("after close cap = allowance only (pack spent)", after["max_budget"], 15.0)
|
||||||
|
check_near("after close credits remaining = 0", after["credits_remaining"], 0.0)
|
||||||
|
|
||||||
|
# every dollar of purchased credit raises the cap by a dollar
|
||||||
|
check_near("credit add raises the cap 1:1",
|
||||||
|
compute_max_budget(15, 70, 0.0, 50.0)["max_budget"], 35.0)
|
||||||
|
check_near("drawn beyond purchased never goes negative",
|
||||||
|
compute_max_budget(15, 50, 0.0, 80.0)["max_budget"], 15.0)
|
||||||
|
|
||||||
|
# --- a real (temporary) DB: apply_cycle_draw ---------------------------------
|
||||||
|
conn = get_db() # runs schema + migrations
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||||
|
"VALUES ('pack@example.com', '', 1, 'member', 15.0, 50.0)"
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
drawn = apply_cycle_draw("pack@example.com", "2026-10-28", spend=65.0, allowance=15.0)
|
||||||
|
check_near("cycle draws the overage ($65 spend - $15 allowance)", drawn, 50.0)
|
||||||
|
check_near("credits_drawn recorded", get_credits_drawn("pack@example.com"), 50.0)
|
||||||
|
check_near("credit_balance still says total purchased", get_credit_balance("pack@example.com"), 50.0)
|
||||||
|
|
||||||
|
# replay of the same cycle draws nothing
|
||||||
|
again = apply_cycle_draw("pack@example.com", "2026-10-28", spend=65.0, allowance=15.0)
|
||||||
|
check_near("replaying a closed cycle draws nothing", again, 0.0)
|
||||||
|
check_near("credits_drawn unchanged by the replay", get_credits_drawn("pack@example.com"), 50.0)
|
||||||
|
rows = sqlite3.connect(_TEST_DB).execute(
|
||||||
|
"SELECT COUNT(*) FROM credit_ledger WHERE reference = ?",
|
||||||
|
("cycle-close:pack@example.com:2026-10-28",)).fetchone()[0]
|
||||||
|
check("exactly ONE ledger row for the cycle", rows, 1)
|
||||||
|
|
||||||
|
# the issue's reproduction: after the reset the cap is the allowance, not $65
|
||||||
|
after = compute_max_budget(15, get_credit_balance("pack@example.com"), 0.0,
|
||||||
|
get_credits_drawn("pack@example.com"))
|
||||||
|
check_near("issue #12: next cycle cap is $15, not $65", after["max_budget"], 15.0)
|
||||||
|
|
||||||
|
# a draw cannot exceed what is left
|
||||||
|
conn = get_db()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||||
|
"VALUES ('small@example.com', '', 1, 'member', 15.0, 10.0)"
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
apply_cycle_draw("small@example.com", "2026-10-01", spend=100.0, allowance=15.0)
|
||||||
|
check_near("draw capped by credits available", get_credits_drawn("small@example.com"), 10.0)
|
||||||
|
check_near("cap after capped draw = allowance",
|
||||||
|
compute_max_budget(15, 10, 0.0, 10.0)["max_budget"], 15.0)
|
||||||
|
|
||||||
|
# spend under the allowance owes nothing
|
||||||
|
conn = get_db()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||||
|
"VALUES ('under@example.com', '', 1, 'member', 15.0, 20.0)"
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
check_near("no overage, no draw",
|
||||||
|
apply_cycle_draw("under@example.com", "2026-10-01", spend=9.0, allowance=15.0), 0.0)
|
||||||
|
check_near("balance untouched", get_credits_drawn("under@example.com"), 0.0)
|
||||||
|
|
||||||
|
# --- a clawback that would land under recorded spend is DEFERRED ------------
|
||||||
|
import asyncio # noqa: E402
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
now = m.datetime.now(m.timezone.utc)
|
||||||
|
anchor = now.day if now.day <= 28 else 28
|
||||||
|
conn = get_db()
|
||||||
|
m._ensure_allowance_tables(conn) # adds anchor_day
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance, anchor_day) "
|
||||||
|
"VALUES ('defer@example.com', '', 1, 'member', 15.0, 20.0, ?)", (anchor,))
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('defer@example.com', 20.0, 'pack (test)', 'test-pack', '2026-10-01 00:00:00')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
state = {"spend": 40.0, "cap": 35.0}
|
||||||
|
applied = []
|
||||||
|
|
||||||
|
async def fake_team(email):
|
||||||
|
return "team:defer" if email == "defer@example.com" else None
|
||||||
|
|
||||||
|
async def fake_update(team_id, budget):
|
||||||
|
applied.append(budget)
|
||||||
|
state["cap"] = budget
|
||||||
|
|
||||||
|
m.litellm_team_id_for_email = fake_team
|
||||||
|
m.litellm_update_team_budget = fake_update
|
||||||
|
m.get_team_budget_from_db = lambda tid: {"spend": state["spend"], "max_budget": state["cap"],
|
||||||
|
"budget_reset_at": None}
|
||||||
|
m.cycle_spend_from_ledger = lambda tid, a, b: 40.0
|
||||||
|
m.CREDIT_CLOSE_FROM = "2026-01-01"
|
||||||
|
|
||||||
|
r1 = asyncio.run(m.close_credit_cycles())
|
||||||
|
check_near("draw recorded even while the cap is deferred", get_credits_drawn("defer@example.com"), 20.0)
|
||||||
|
check("cap NOT lowered under recorded spend",
|
||||||
|
any(d["email"] == "defer@example.com" for d in r1["deferred"]), True)
|
||||||
|
check("no cap push while spend > new cap", applied, [])
|
||||||
|
|
||||||
|
state["spend"] = 0.0 # what LiteLLM does at the member's reset
|
||||||
|
r2 = asyncio.run(m.close_credit_cycles())
|
||||||
|
check("cap applied once spend resets", applied, [15.0])
|
||||||
|
check("no second draw on the same cycle", r2["credits_drawn"], 0.0)
|
||||||
|
|
||||||
|
# --- lowering a pack below what was drawn must not swallow NEW credits ----
|
||||||
|
add_credits("small@example.com", -10.0, reason="admin correction (test)")
|
||||||
|
check_near("drawn follows the pack down when it is reduced", get_credits_drawn("small@example.com"), 0.0)
|
||||||
|
check_near("balance reduced to zero", get_credit_balance("small@example.com"), 0.0)
|
||||||
|
add_credits("small@example.com", 5.0, reason="new pack (test)")
|
||||||
|
check_near("a new pack is fully available after the correction",
|
||||||
|
compute_max_budget(15, get_credit_balance("small@example.com"), 0.0,
|
||||||
|
get_credits_drawn("small@example.com"))["credits_remaining"], 5.0)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if failures:
|
||||||
|
print(f"{failures} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("all checks passed")
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests: a cycle draw may only charge spend credits could cover.
|
||||||
|
|
||||||
|
A pack bought mid-cycle must not be charged for spend incurred before it
|
||||||
|
existed. Reproduces the consensus_polo100 case: $27.81 spent before the $10
|
||||||
|
pack arrived, then $0.62 after it; the eligible draw is $0.62, not $10.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditelig-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|
||||||
|
def check_near(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = round(float(got), 6) == round(float(want), 6)
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn) # adds anchor_day
|
||||||
|
for email, purchased, anchor in [
|
||||||
|
("midcycle@example.com", 10.0, 15),
|
||||||
|
("carried@example.com", 50.0, 15),
|
||||||
|
("none@example.com", 0.0, 15),
|
||||||
|
("partial@example.com", 20.0, 15)]:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, "
|
||||||
|
"credit_balance, credits_drawn, anchor_day) VALUES (?, '', 1, 'member', 15.0, ?, 0, ?)",
|
||||||
|
(email, purchased, anchor))
|
||||||
|
|
||||||
|
# Pack bought inside the cycle, after the allowance had already been overspent.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('midcycle@example.com', 10.0, 'pack', 'pack-mid', '2026-11-12 13:05:26')")
|
||||||
|
# Pack held from before the cycle.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('carried@example.com', 50.0, 'pack', 'pack-carry', '2026-09-20 10:00:00')")
|
||||||
|
# Pack arrives when only part of the allowance has been used.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
||||||
|
"VALUES ('partial@example.com', 20.0, 'pack', 'pack-part', '2026-10-20 12:00:00')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
CS = datetime(2026, 10, 15, tzinfo=timezone.utc)
|
||||||
|
CE = datetime(2026, 11, 15, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
# Spend windows for the mid-cycle member: 27.81376 before the pack, 0.624698 after.
|
||||||
|
def fake_spend(team_id, start, end):
|
||||||
|
if team_id == "t-mid":
|
||||||
|
if end.day == 12 and end.month == 11:
|
||||||
|
return 27.81376
|
||||||
|
if start == CS and end == CE:
|
||||||
|
return 28.438458
|
||||||
|
if team_id == "t-partial" and start == CS and end == datetime(2026, 10, 20, 12, tzinfo=timezone.utc):
|
||||||
|
return 5.0
|
||||||
|
return None
|
||||||
|
|
||||||
|
m.cycle_spend_from_ledger = fake_spend
|
||||||
|
|
||||||
|
# mid-cycle pack: only spend after the pack is eligible
|
||||||
|
got = m.credit_eligible_overage("midcycle@example.com", "t-mid", CS, CE, 15.0, 28.438458)
|
||||||
|
check_near("mid-cycle pack is not charged for earlier spend", got, 0.624698)
|
||||||
|
|
||||||
|
# pack carried in: whole overage is eligible
|
||||||
|
got = m.credit_eligible_overage("carried@example.com", "t-carry", CS, CE, 15.0, 28.438458)
|
||||||
|
check_near("credits at cycle start cover the whole overage", got, 13.438458)
|
||||||
|
|
||||||
|
# no credits: nothing eligible
|
||||||
|
got = m.credit_eligible_overage("none@example.com", "t-none", CS, CE, 15.0, 28.438458)
|
||||||
|
check_near("no credits means no eligible draw", got, 0.0)
|
||||||
|
|
||||||
|
# partial allowance left: overage above what remains is eligible
|
||||||
|
got = m.credit_eligible_overage("partial@example.com", "t-partial", CS, CE, 15.0, 20.0)
|
||||||
|
check_near("allowance is consumed before credits", got, 5.0)
|
||||||
|
|
||||||
|
# the eligible figure drives the draw, and the replay still draws nothing
|
||||||
|
drawn = m.apply_cycle_draw("midcycle@example.com", "2026-10-15", 28.438458, 15.0, eligible=0.624698)
|
||||||
|
check_near("draw uses the credit-eligible overage", drawn, 0.624698)
|
||||||
|
check_near("credits_drawn records only that amount", m.get_credits_drawn("midcycle@example.com"), 0.624698)
|
||||||
|
check_near("purchased total is unchanged", m.get_credit_balance("midcycle@example.com"), 10.0)
|
||||||
|
check_near("replay draws nothing",
|
||||||
|
m.apply_cycle_draw("midcycle@example.com", "2026-10-15", 28.438458, 15.0, eligible=0.624698), 0.0)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if failures:
|
||||||
|
print(f"{failures} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("all checks passed")
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import os, sys
|
import os, sys
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
import app.main as m
|
import app.main as m
|
||||||
v=m._fx_verdict(1.16); assert v["alert"] is False, v
|
v=m._fx_verdict(1.0975); assert v["alert"] is False, v
|
||||||
v=m._fx_verdict(1.20); assert v["alert"] is True and v["drift_pct"] > 0, v
|
v=m._fx_verdict(1.13); assert v["alert"] is True and v["drift_pct"] > 0, v
|
||||||
v=m._fx_verdict(1.10); assert v["alert"] is True and v["drift_pct"] < 0, v
|
v=m._fx_verdict(1.07); assert v["alert"] is True and v["drift_pct"] < 0, v
|
||||||
v=m._fx_verdict(1.157); assert v["alert"] is False, v # 0.26% drift
|
v=m._fx_verdict(1.0995); assert v["alert"] is False, v # 0.18% drift
|
||||||
print("FX VERDICT OK: thresholds and signs behave")
|
print("FX VERDICT OK: thresholds and signs behave")
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests: guest conversion carries only UNSPENT credit.
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_guest_conversion_draw.py
|
||||||
|
* from the repo root, on a host that has the app's dependencies
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
A guest has no monthly cycle, so nothing ever drew their spend against the
|
||||||
|
$2 pack. Converting a guest kept the full $2 credit_balance, handing back
|
||||||
|
credits already used — while guest-access.md promises only the UNSPENT
|
||||||
|
credit carries over. record_guest_conversion_draw() records the consumed
|
||||||
|
part as a draw, deduped on a ledger reference.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="guestdraw-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
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 ( # noqa: E402
|
||||||
|
compute_max_budget, get_credit_balance, get_credits_drawn, get_db,
|
||||||
|
record_guest_conversion_draw,
|
||||||
|
)
|
||||||
|
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|
||||||
|
def check_near(name, got, want):
|
||||||
|
global failures
|
||||||
|
ok = round(float(got), 6) == round(float(want), 6)
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|
||||||
|
conn = get_db()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||||
|
"VALUES ('g1@example.com', '', 1, 'guest', 0.0, 2.0)")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||||
|
"VALUES ('g2@example.com', '', 1, 'guest', 0.0, 2.0)")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
used = record_guest_conversion_draw("g1@example.com", 1.9)
|
||||||
|
check_near("consumed guest spend is drawn", used, 1.9)
|
||||||
|
check_near("credits_drawn records it", get_credits_drawn("g1@example.com"), 1.9)
|
||||||
|
check_near("credit_balance stays the purchased total", get_credit_balance("g1@example.com"), 2.0)
|
||||||
|
check_near("only the unspent credit is available",
|
||||||
|
compute_max_budget(15, 2, 0.0, get_credits_drawn("g1@example.com"))["credits_remaining"], 0.1)
|
||||||
|
|
||||||
|
check_near("a replay draws nothing", record_guest_conversion_draw("g1@example.com", 1.9), 0.0)
|
||||||
|
check_near("credits_drawn unchanged by replay", get_credits_drawn("g1@example.com"), 1.9)
|
||||||
|
|
||||||
|
check_near("spend above the pack is capped", record_guest_conversion_draw("g2@example.com", 5.0), 2.0)
|
||||||
|
check_near("pack fully drawn", get_credits_drawn("g2@example.com"), 2.0)
|
||||||
|
check_near("no credit left", compute_max_budget(15, 2, 0.0, 2.0)["credits_remaining"], 0.0)
|
||||||
|
|
||||||
|
check_near("zero spend draws nothing", record_guest_conversion_draw("g1@example.com", 0.0), 0.0)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if failures:
|
||||||
|
print(f"{failures} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("all checks passed")
|
||||||
+86
-10
@@ -51,6 +51,7 @@ deletes = [] # every b3 membership DELETE url
|
|||||||
ROSTER = {} # email -> membership id currently in the group
|
ROSTER = {} # email -> membership id currently in the group
|
||||||
GET_FAILS = False # exercise fail-closed
|
GET_FAILS = False # exercise fail-closed
|
||||||
DELETE_STATUS = 200 # toggle to prove 404 tolerance
|
DELETE_STATUS = 200 # toggle to prove 404 tolerance
|
||||||
|
ADDED_OMIT = set() # emails the fake Loomio accepts but does NOT add
|
||||||
|
|
||||||
|
|
||||||
class FakeResp:
|
class FakeResp:
|
||||||
@@ -88,7 +89,8 @@ class FakeClient:
|
|||||||
|
|
||||||
async def post(self, url, headers=None, json=None):
|
async def post(self, url, headers=None, json=None):
|
||||||
posts.append({"url": url, "json": json or {}})
|
posts.append({"url": url, "json": json or {}})
|
||||||
return FakeResp(200, {"added_emails": (json or {}).get("emails", [])})
|
sent = (json or {}).get("emails", [])
|
||||||
|
return FakeResp(200, {"added_emails": [e for e in sent if e not in ADDED_OMIT]})
|
||||||
|
|
||||||
async def delete(self, url, headers=None):
|
async def delete(self, url, headers=None):
|
||||||
deletes.append(url)
|
deletes.append(url)
|
||||||
@@ -119,7 +121,7 @@ def check(name, ok):
|
|||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
global GET_FAILS, ROSTER, DELETE_STATUS
|
global GET_FAILS, ROSTER, DELETE_STATUS, ADDED_OMIT
|
||||||
m.get_db().close() # create + migrate the fixture schema
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
conn = m.get_db()
|
conn = m.get_db()
|
||||||
for e in ("new@x.org", "old@x.org", "member@x.org"):
|
for e in ("new@x.org", "old@x.org", "member@x.org"):
|
||||||
@@ -130,6 +132,7 @@ async def main():
|
|||||||
cols = [r[1] for r in m.get_db().execute("PRAGMA table_info(members)").fetchall()]
|
cols = [r[1] for r in m.get_db().execute("PRAGMA table_info(members)").fetchall()]
|
||||||
m.get_db().close()
|
m.get_db().close()
|
||||||
check("migration: members.loomio_invited_at exists", "loomio_invited_at" in cols)
|
check("migration: members.loomio_invited_at exists", "loomio_invited_at" in cols)
|
||||||
|
check("migration: members.loomio_opt_out exists", "loomio_opt_out" in cols)
|
||||||
|
|
||||||
m.get_active_member_emails = fake_active
|
m.get_active_member_emails = fake_active
|
||||||
m.filter_loomio_activated = fake_activated
|
m.filter_loomio_activated = fake_activated
|
||||||
@@ -156,17 +159,30 @@ async def main():
|
|||||||
check("add: remove_absent is NEVER sent (no re-add path)", "remove_absent" not in body)
|
check("add: remove_absent is NEVER sent (no re-add path)", "remove_absent" not in body)
|
||||||
check("add: the newly-invited address is recorded",
|
check("add: the newly-invited address is recorded",
|
||||||
m.get_loomio_invited_at("new@x.org") is not None)
|
m.get_loomio_invited_at("new@x.org") is not None)
|
||||||
|
check("reconcile: a stamped-but-absent member's stamp is cleared (not yet re-invited)",
|
||||||
|
m.get_loomio_invited_at("old@x.org") is None)
|
||||||
check("add: nothing removed when nobody has lapsed", deletes == [])
|
check("add: nothing removed when nobody has lapsed", deletes == [])
|
||||||
|
|
||||||
# --- 2. Second run adds nobody again. ---
|
# --- 2. Second run: the cleared member is invited once, then recorded. ---
|
||||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # Loomio now has new@
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # Loomio now has new@
|
||||||
posts.clear(); deletes.clear()
|
posts.clear(); deletes.clear()
|
||||||
await m.sync_loomio_memberships()
|
await m.sync_loomio_memberships()
|
||||||
|
body = posts[0]["json"] if posts else {}
|
||||||
|
check("reconcile: the cleared member is re-invited on the next pass",
|
||||||
|
body.get("emails") == ["old@x.org"])
|
||||||
|
check("reconcile: the re-invite is recorded", m.get_loomio_invited_at("old@x.org") is not None)
|
||||||
|
check("reconcile: a present member is never re-invited",
|
||||||
|
"member@x.org" not in (body.get("emails") or []))
|
||||||
|
|
||||||
|
# --- 2b. Third run: nothing left to invite. ---
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88}
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
check("double-run: no second invite", posts == [])
|
check("double-run: no second invite", posts == [])
|
||||||
check("double-run: no removals", deletes == [])
|
check("double-run: no removals", deletes == [])
|
||||||
|
|
||||||
# --- 3. REMOVE path: a lapsed member is removed exactly once. ---
|
# --- 3. REMOVE path: a lapsed member is removed exactly once. ---
|
||||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "lapsed@x.org": 77}
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88, "lapsed@x.org": 77}
|
||||||
posts.clear(); deletes.clear()
|
posts.clear(); deletes.clear()
|
||||||
await m.sync_loomio_memberships()
|
await m.sync_loomio_memberships()
|
||||||
check("remove: the lapsed member is removed exactly once",
|
check("remove: the lapsed member is removed exactly once",
|
||||||
@@ -180,7 +196,7 @@ async def main():
|
|||||||
all("keep@x.org" not in (p["json"].get("emails") or []) for p in posts))
|
all("keep@x.org" not in (p["json"].get("emails") or []) for p in posts))
|
||||||
|
|
||||||
# --- 4. Second run after the removal changes nothing. ---
|
# --- 4. Second run after the removal changes nothing. ---
|
||||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # lapsed gone
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88} # lapsed gone
|
||||||
posts.clear(); deletes.clear()
|
posts.clear(); deletes.clear()
|
||||||
await m.sync_loomio_memberships()
|
await m.sync_loomio_memberships()
|
||||||
check("remove double-run: nothing removed again", deletes == [])
|
check("remove double-run: nothing removed again", deletes == [])
|
||||||
@@ -188,7 +204,7 @@ async def main():
|
|||||||
|
|
||||||
# --- 5. A re-run against a STALE roster (member already gone) must not error:
|
# --- 5. A re-run against a STALE roster (member already gone) must not error:
|
||||||
# Loomio answers 404 for an absent membership, which is success. ---
|
# Loomio answers 404 for an absent membership, which is success. ---
|
||||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "lapsed@x.org": 77}
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "old@x.org": 88, "lapsed@x.org": 77}
|
||||||
DELETE_STATUS = 404
|
DELETE_STATUS = 404
|
||||||
posts.clear(); deletes.clear()
|
posts.clear(); deletes.clear()
|
||||||
err = None
|
err = None
|
||||||
@@ -201,7 +217,7 @@ async def main():
|
|||||||
DELETE_STATUS = 200
|
DELETE_STATUS = 200
|
||||||
|
|
||||||
# --- 6. FAIL CLOSED: an unreadable roster stops BOTH phases. ---
|
# --- 6. FAIL CLOSED: an unreadable roster stops BOTH phases. ---
|
||||||
ROSTER = {"lapsed@x.org": 77}
|
ROSTER = {"lapsed@x.org": 77, "old@x.org": 88}
|
||||||
GET_FAILS = True
|
GET_FAILS = True
|
||||||
posts.clear(); deletes.clear()
|
posts.clear(); deletes.clear()
|
||||||
await m.sync_loomio_memberships()
|
await m.sync_loomio_memberships()
|
||||||
@@ -218,10 +234,10 @@ async def main():
|
|||||||
m.LOOMIO_SYNC_ENABLED = True
|
m.LOOMIO_SYNC_ENABLED = True
|
||||||
|
|
||||||
# --- 8. Recording is idempotent — an existing timestamp is never overwritten. ---
|
# --- 8. Recording is idempotent — an existing timestamp is never overwritten. ---
|
||||||
first = m.get_loomio_invited_at("old@x.org")
|
first = m.get_loomio_invited_at("member@x.org")
|
||||||
m.mark_loomio_invited("old@x.org")
|
m.mark_loomio_invited("member@x.org")
|
||||||
check("mark_loomio_invited never overwrites an existing timestamp",
|
check("mark_loomio_invited never overwrites an existing timestamp",
|
||||||
m.get_loomio_invited_at("old@x.org") == first)
|
m.get_loomio_invited_at("member@x.org") == first)
|
||||||
|
|
||||||
# --- 9. remove_loomio_membership status handling (200/204/404 ok, 500 not). ---
|
# --- 9. remove_loomio_membership status handling (200/204/404 ok, 500 not). ---
|
||||||
async with FakeClient() as c:
|
async with FakeClient() as c:
|
||||||
@@ -231,6 +247,66 @@ async def main():
|
|||||||
check("remove_loomio_membership: 500 is a failure", not await m.remove_loomio_membership(c, 1))
|
check("remove_loomio_membership: 500 is a failure", not await m.remove_loomio_membership(c, 1))
|
||||||
DELETE_STATUS = 200
|
DELETE_STATUS = 200
|
||||||
|
|
||||||
|
# --- 10. OPT-OUT: a member who deliberately left is never re-invited. ---
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active, loomio_opt_out) VALUES (?, 1, 1)",
|
||||||
|
("left@x.org",))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
m.mark_loomio_invited("left@x.org")
|
||||||
|
|
||||||
|
async def active_with_left():
|
||||||
|
return ["member@x.org", "left@x.org"]
|
||||||
|
|
||||||
|
m.get_active_member_emails = active_with_left
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
check("opt-out: a member who left is not re-invited", posts == [])
|
||||||
|
check("opt-out: their stamp is left intact", m.get_loomio_invited_at("left@x.org") is not None)
|
||||||
|
|
||||||
|
# --- 11. RECONCILE CAP: many stamped-but-absent members mean a bad roster
|
||||||
|
# read, not a mass re-invite. Nothing is cleared. ---
|
||||||
|
many = [f"miss{n}@x.org" for n in range(1, m.LOOMIO_RECONCILE_MAX + 2)]
|
||||||
|
conn = m.get_db()
|
||||||
|
for e in many:
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (e,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
for e in many:
|
||||||
|
m.mark_loomio_invited(e)
|
||||||
|
|
||||||
|
async def active_with_many():
|
||||||
|
return ["member@x.org"] + many
|
||||||
|
|
||||||
|
m.get_active_member_emails = active_with_many
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
check("cap: an over-cap stamp reconciliation sends no invites", posts == [])
|
||||||
|
check("cap: stamps are untouched when the cap is exceeded",
|
||||||
|
all(m.get_loomio_invited_at(e) is not None for e in many))
|
||||||
|
|
||||||
|
# --- 12. NOT ADDED: if Loomio accepts the payload but adds nothing for an
|
||||||
|
# address, it must stay unstamped and eligible. ---
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", ("lost@x.org",))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
async def active_with_lost():
|
||||||
|
return ["member@x.org", "lost@x.org"]
|
||||||
|
|
||||||
|
m.get_active_member_emails = active_with_lost
|
||||||
|
ADDED_OMIT = {"lost@x.org"}
|
||||||
|
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
|
||||||
|
posts.clear(); deletes.clear()
|
||||||
|
await m.sync_loomio_memberships()
|
||||||
|
check("not-added: the address is sent", posts and posts[0]["json"]["emails"] == ["lost@x.org"])
|
||||||
|
check("not-added: an address Loomio did not add stays unstamped",
|
||||||
|
m.get_loomio_invited_at("lost@x.org") is None)
|
||||||
|
ADDED_OMIT = set()
|
||||||
|
|
||||||
|
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
fails = sum(not ok for _, ok in results)
|
fails = sum(not ok for _, ok in results)
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: Loomio handle collisions are resolved, not left mangled.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
Loomio usernames are unique per INSTANCE, not per group. The rename pass
|
||||||
|
derives a target from the Cloudron username (the OAuth uid) or, before first
|
||||||
|
SSO login, from the email local part. Both can collide with a handle someone
|
||||||
|
else already holds:
|
||||||
|
* a plain Cloudron username — "matt" is held by another member;
|
||||||
|
* Open Collective aliases — every OC member's address starts
|
||||||
|
"opencollective@", so the local part resolves to "opencollective" and
|
||||||
|
collides with whichever OC member took it first.
|
||||||
|
A 422 "username has already been taken" must fall back to the member's portal
|
||||||
|
slug (name-based, e.g. "matt-h"), never leave the member on an autogenerated
|
||||||
|
handle.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_loomio_usernames.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["LOOMIO_API_KEY"] = "test-user-key"
|
||||||
|
os.environ["LOOMIO_B3_KEY"] = "test-server-key"
|
||||||
|
os.environ["LOOMIO_GROUP_ID"] = "1"
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
TAKEN = {"matt", "opencollective"}
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResp:
|
||||||
|
def __init__(self, status=200, payload=None):
|
||||||
|
self.status_code = status
|
||||||
|
self._payload = payload or {}
|
||||||
|
self.text = str(payload or {})
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
if self.status_code >= 400:
|
||||||
|
raise RuntimeError(f"HTTP {self.status_code}")
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._payload
|
||||||
|
|
||||||
|
|
||||||
|
USERS = [
|
||||||
|
{"id": 300, "username": "matthiehnouk8f", "email": "matt@mattharwood.com",
|
||||||
|
"identities": [{"identity_type": "oauth", "uid": "matt"}]},
|
||||||
|
{"id": 313, "username": "opencollectivewbvgr", "email": "opencollective@jeremiahlee.com",
|
||||||
|
"identities": []},
|
||||||
|
{"id": 9, "username": "joshuaztanxk2", "email": "joshua.z.tan@example.org",
|
||||||
|
"identities": [{"identity_type": "oauth", "uid": "joshua.z.tan"}]},
|
||||||
|
{"id": 5, "username": "amarino", "email": "amarino@solo.ist",
|
||||||
|
"identities": [{"identity_type": "oauth", "uid": "amarino"}]},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
self.patches = []
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, url, headers=None, params=None):
|
||||||
|
return FakeResp(200, {"users": USERS})
|
||||||
|
|
||||||
|
async def patch(self, url, headers=None, json=None):
|
||||||
|
uid = int(url.rsplit("/", 1)[-1])
|
||||||
|
name = (json or {}).get("username")
|
||||||
|
self.patches.append((uid, name))
|
||||||
|
if name in TAKEN:
|
||||||
|
return FakeResp(422, {"errors": {"username": ["has already been taken"]}})
|
||||||
|
return FakeResp(200, {"user": {"id": uid, "username": name}})
|
||||||
|
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, ok))
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
conn = m.get_db() # create + migrate
|
||||||
|
for email, slug in (
|
||||||
|
("matt@mattharwood.com", "matt-h"),
|
||||||
|
("opencollective@jeremiahlee.com", "jeremiah-lee"),
|
||||||
|
("joshua.z.tan@example.org", "joshua-z-tan"),
|
||||||
|
("amarino@solo.ist", "amarino"),
|
||||||
|
):
|
||||||
|
conn.execute("INSERT OR REPLACE INTO members (email, slug) VALUES (?, ?)", (email, slug))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
client = FakeClient()
|
||||||
|
out = await m.loomio_fix_usernames(client)
|
||||||
|
by_uid = {}
|
||||||
|
for uid, name in client.patches:
|
||||||
|
by_uid.setdefault(uid, []).append(name)
|
||||||
|
|
||||||
|
# Matt Harwood: Cloudron uid "matt" is taken -> portal slug "matt-h".
|
||||||
|
check("collision: the taken Cloudron username is tried first",
|
||||||
|
by_uid.get(300, [])[0] == "matt")
|
||||||
|
check("collision: falls back to the portal slug",
|
||||||
|
by_uid.get(300) == ["matt", "matt-h"])
|
||||||
|
|
||||||
|
# Jeremiah Lee: OC alias local part "opencollective" is taken -> slug.
|
||||||
|
check("collision: an OC alias local part is tried first",
|
||||||
|
by_uid.get(313, [])[0] == "opencollective")
|
||||||
|
check("collision: an OC alias collision falls back to the slug",
|
||||||
|
by_uid.get(313) == ["opencollective", "jeremiah-lee"])
|
||||||
|
|
||||||
|
# Joshua Tan: a dot-containing uid is sanitized, not passed through.
|
||||||
|
check("sanitize: a dotted uid becomes a legal handle",
|
||||||
|
by_uid.get(9) == ["joshua_z_tan"])
|
||||||
|
|
||||||
|
# A human-chosen handle is out of scope and never renamed.
|
||||||
|
check("skip: a hand-chosen handle is never renamed", 5 not in by_uid)
|
||||||
|
check("summary: three handled, one skipped",
|
||||||
|
out == {"fixed": 3, "skipped": 1})
|
||||||
|
|
||||||
|
# No patch ever sends an illegal character.
|
||||||
|
check("sanitize: every attempted handle is Loomio-legal",
|
||||||
|
all(n and n == m._loomio_safe_username(n) for _, names in by_uid.items() for n in names))
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Membership events — the durable record of who lapsed and who returned.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
Before this table, a lapse was only members.active = 0: no date, no reason,
|
||||||
|
no source. A former member was indistinguishable from someone who had never
|
||||||
|
paid, and a returning payer silently erased the fact that they had lapsed.
|
||||||
|
Every deactivation/reactivation transition now writes one row, and the admin
|
||||||
|
overview carries the log plus the latest deactivation per member.
|
||||||
|
|
||||||
|
The tests pin:
|
||||||
|
1. deactivate_member logs ONE row on the active -> inactive transition;
|
||||||
|
a repeated call (OC re-delivery / second sweep pass) does not duplicate.
|
||||||
|
2. store_member logs `reactivated` when it flips an inactive member back on.
|
||||||
|
3. backfill gives a pre-existing inactive member one row with occurred_at
|
||||||
|
NULL and a reason derived from allowance_log; it runs once.
|
||||||
|
4. the overview helper returns the newest-first log and maps the latest
|
||||||
|
deactivation to the member's email (None date for a backfilled row).
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_membership_events.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "events-fixture.db")
|
||||||
|
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
FAILS = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(cond, msg):
|
||||||
|
print((" ok " if cond else " FAIL ") + msg)
|
||||||
|
if not cond:
|
||||||
|
FAILS.append(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def rows(q, args=()):
|
||||||
|
conn = m.get_db()
|
||||||
|
try:
|
||||||
|
return conn.execute(q, args).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
print("1. deactivation logs exactly one transition")
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn)
|
||||||
|
conn.execute("DELETE FROM members")
|
||||||
|
conn.execute("DELETE FROM membership_events")
|
||||||
|
conn.execute("DELETE FROM portal_state")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, active, account_type) VALUES (?, 1, 'member')",
|
||||||
|
("lapse@example.org",),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
m.deactivate_member(
|
||||||
|
"lapse@example.org",
|
||||||
|
reason="Membership lapsed: no longer on the live Open Collective member list",
|
||||||
|
source="sweep",
|
||||||
|
)
|
||||||
|
ev = rows(
|
||||||
|
"SELECT email, event, reason, source, occurred_at, account_type "
|
||||||
|
"FROM membership_events WHERE email = ?",
|
||||||
|
("lapse@example.org",),
|
||||||
|
)
|
||||||
|
check(len(ev) == 1, "one deactivation row written")
|
||||||
|
check(ev[0][1] == "deactivated", "event is 'deactivated'")
|
||||||
|
check(ev[0][3] == "sweep", "source records the calling path")
|
||||||
|
check("Open Collective" in ev[0][2], "reason records why")
|
||||||
|
check(bool(ev[0][4]), "live transition carries occurred_at")
|
||||||
|
check(ev[0][5] == "member", "account_type is carried onto the event")
|
||||||
|
|
||||||
|
# A re-delivered webhook / second sweep pass must not append another lapse.
|
||||||
|
m.deactivate_member(
|
||||||
|
"lapse@example.org",
|
||||||
|
reason="duplicate delivery",
|
||||||
|
source="webhook-opencollective",
|
||||||
|
)
|
||||||
|
ev = rows(
|
||||||
|
"SELECT event FROM membership_events WHERE email = ?",
|
||||||
|
("lapse@example.org",),
|
||||||
|
)
|
||||||
|
check(len(ev) == 1, "a repeated deactivation writes no duplicate row")
|
||||||
|
|
||||||
|
print("2. a returning payer is logged as reactivated")
|
||||||
|
m.store_member("lapse@example.org", "sk-fixture", "uid-fixture")
|
||||||
|
ev = rows(
|
||||||
|
"SELECT event, source FROM membership_events WHERE email = ? ORDER BY id",
|
||||||
|
("lapse@example.org",),
|
||||||
|
)
|
||||||
|
check([r[0] for r in ev] == ["deactivated", "reactivated"],
|
||||||
|
"deactivated then reactivated, in order")
|
||||||
|
check(ev[-1][1] == "provision", "reactivation source is provisioning")
|
||||||
|
active = rows("SELECT active FROM members WHERE email = ?", ("lapse@example.org",))
|
||||||
|
check(active[0][0] == 1, "member is active again")
|
||||||
|
|
||||||
|
print("3. backfill gives a pre-existing inactive member a dated-unknown row")
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute("DELETE FROM membership_events")
|
||||||
|
conn.execute("DELETE FROM portal_state")
|
||||||
|
conn.execute("DELETE FROM members")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, active, account_type, welcome_sent_at) "
|
||||||
|
"VALUES (?, 0, 'member', ?)",
|
||||||
|
("old@example.org", "2026-11-11 19:00:47"),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO allowance_log (email, cycle, decision, evidence, decided_at) "
|
||||||
|
"VALUES (?, ?, ?, ?, ?)",
|
||||||
|
("old@example.org", "2026-11-16", "in_grace",
|
||||||
|
"no recurring (monthly) contribution on Open Collective; reminder sent 2026-11-16 (grace 7d)",
|
||||||
|
"2026-11-18 11:02:37"),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
m._backfill_membership_events(conn)
|
||||||
|
conn.commit()
|
||||||
|
ev = conn.execute(
|
||||||
|
"SELECT event, reason, source, occurred_at, detail FROM membership_events "
|
||||||
|
"WHERE email = ?", ("old@example.org",),
|
||||||
|
).fetchall()
|
||||||
|
conn.close()
|
||||||
|
check(len(ev) == 1, "one backfilled row")
|
||||||
|
check(ev[0][0] == "deactivated" and ev[0][2] == "backfill",
|
||||||
|
"backfill event/source are explicit")
|
||||||
|
check(ev[0][3] is None, "backfilled occurred_at stays NULL (unknown date)")
|
||||||
|
check("in_grace" in ev[0][1] and "2026-11-18" in ev[0][1],
|
||||||
|
"backfill reason quotes the allowance decision and date")
|
||||||
|
check("exact" in ev[0][4].lower(), "detail says the exact date is unknown")
|
||||||
|
|
||||||
|
# Re-running the backfill must not duplicate the row (the marker gates it).
|
||||||
|
conn = m.get_db()
|
||||||
|
m._backfill_membership_events(conn)
|
||||||
|
conn.commit()
|
||||||
|
n = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM membership_events WHERE email = ?", ("old@example.org",),
|
||||||
|
).fetchone()[0]
|
||||||
|
conn.close()
|
||||||
|
check(n == 1, "backfill is idempotent")
|
||||||
|
|
||||||
|
print("4. the overview helper returns the log and the latest deactivation")
|
||||||
|
conn = m.get_db()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO membership_events (email, account_type, event, reason, source, occurred_at) "
|
||||||
|
"VALUES (?, 'member', 'reactivated', ?, 'provision', ?)",
|
||||||
|
("old@example.org", "Returned to active membership", "2026-11-24 12:00:00"),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
events, latest = m._membership_events_for_overview(conn)
|
||||||
|
conn.close()
|
||||||
|
check(len(events) == 2, "both events are in the log")
|
||||||
|
check(events[0]["event"] == "reactivated", "newest event sorts first")
|
||||||
|
check("old@example.org" in latest, "latest deactivation is keyed by email")
|
||||||
|
check(latest["old@example.org"]["at"] is None,
|
||||||
|
"backfilled latest deactivation reports an unknown date")
|
||||||
|
check(latest["old@example.org"]["source"] == "backfill",
|
||||||
|
"latest deactivation keeps its source")
|
||||||
|
|
||||||
|
print()
|
||||||
|
if FAILS:
|
||||||
|
print(f"FAILED: {len(FAILS)} check(s) red")
|
||||||
|
sys.exit(1)
|
||||||
|
print("all membership-event checks green")
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: the OC order reads must PAGE, not stop at a fixed limit.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
fetch_member_orders() asked OC for `orders(limit: 200)` in ONE request. The
|
||||||
|
collective passed 200 orders on 2026-11-23 (203), and the orders beyond the
|
||||||
|
window are the OLDEST ones — exactly where a long-standing member's recurring
|
||||||
|
contribution lives. Those members read as "no recurring (monthly)
|
||||||
|
contribution on Open Collective", so the allowance sweep sent them a
|
||||||
|
payment reminder for a contribution that was LIVE and charged days earlier.
|
||||||
|
Three paying members (ntnsndr, elizabeth-barry1, guest-0f6d98ac) got that
|
||||||
|
wrong email at 03:02 UTC on 2026-11-23.
|
||||||
|
|
||||||
|
fetch_oc_monthly_order_charges() had the same fixed window; an order missing
|
||||||
|
from it is a truncated paid cycle the shortfall credit pass cannot see.
|
||||||
|
|
||||||
|
WHAT IS PINNED HERE
|
||||||
|
* every order is read across pages (203 orders -> two pages, oldest included),
|
||||||
|
* a member whose ONLY recurring order is the oldest one is still matched,
|
||||||
|
* an INCOMPLETE read (OC reports more than it served) raises instead of
|
||||||
|
returning a short list, because a short list reads as "nobody is paying",
|
||||||
|
* the charge ladder for the oldest monthly orders is read too.
|
||||||
|
|
||||||
|
Runnable from the repo root: python3 tests/test_order_pagination.py
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import asyncio
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
m.OC_PERSONAL_TOKEN = "test-token"
|
||||||
|
m.OC_COLLECTIVE_SLUG = "inference-cooperative"
|
||||||
|
|
||||||
|
# The three slugs whose live monthly orders were the OLDEST in production and
|
||||||
|
# therefore fell outside the fixed 200-order window.
|
||||||
|
OLDEST = ["ntnsndr", "elizabeth-barry1", "guest-0f6d98ac"]
|
||||||
|
|
||||||
|
TOTAL_ORDERS = 203
|
||||||
|
SERVED: dict[str, int | None] = {"n": None} # None = serve everything; an int = pretend truncation
|
||||||
|
REQUESTS = []
|
||||||
|
|
||||||
|
|
||||||
|
def make_nodes(n=TOTAL_ORDERS):
|
||||||
|
"""Newest-first list; the OLDEST three are our live monthly members."""
|
||||||
|
nodes = []
|
||||||
|
for i in range(n):
|
||||||
|
oldest_rank = n - 1 - i # 0 for the newest, n-1 for the oldest
|
||||||
|
slug = OLDEST[oldest_rank] if oldest_rank < len(OLDEST) else f"member{oldest_rank}"
|
||||||
|
nodes.append({
|
||||||
|
"id": f"or_{slug}",
|
||||||
|
"frequency": "MONTHLY",
|
||||||
|
"status": "ACTIVE",
|
||||||
|
"createdAt": f"2026-{9 + oldest_rank // 30:02d}-{(oldest_rank % 28) + 1:02d}T10:00:00Z",
|
||||||
|
"lastChargedAt": "2026-11-02T17:06:25.000Z",
|
||||||
|
"nextChargeDate": "2026-12-01T00:00:00.000Z",
|
||||||
|
"fromAccount": {"slug": slug},
|
||||||
|
"amount": {"value": 15, "currency": "USD"},
|
||||||
|
"totalAmount": {"value": 15.75, "currency": "USD"},
|
||||||
|
"transactions": [
|
||||||
|
{"publicId": f"txn_{slug}_a", "createdAt": "2026-10-02T10:00:00Z",
|
||||||
|
"type": "CREDIT", "kind": "CONTRIBUTION", "isRefund": False},
|
||||||
|
{"publicId": f"txn_{slug}_b", "createdAt": "2026-11-02T10:00:00Z",
|
||||||
|
"type": "CREDIT", "kind": "CONTRIBUTION", "isRefund": False},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
return nodes
|
||||||
|
|
||||||
|
|
||||||
|
NODES = make_nodes()
|
||||||
|
|
||||||
|
|
||||||
|
class Resp:
|
||||||
|
def __init__(self, body, status_code=200):
|
||||||
|
self._body = body
|
||||||
|
self.status_code = status_code
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._body
|
||||||
|
|
||||||
|
|
||||||
|
def _int_arg(query, name):
|
||||||
|
"""Read `name: <int>` out of the GraphQL query string."""
|
||||||
|
for part in query.split("orders(")[1].split(")")[0].split(","):
|
||||||
|
k, _, v = part.strip().partition(":")
|
||||||
|
if k.strip() == name:
|
||||||
|
return int(v)
|
||||||
|
raise AssertionError(f"query carries no {name}: {query}")
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
"""Async httpx stand-in: serves OC's orders connection page by page."""
|
||||||
|
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *exc):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def post(self, url, headers=None, json=None):
|
||||||
|
q = (json or {}).get("query", "")
|
||||||
|
REQUESTS.append(q)
|
||||||
|
limit = _int_arg(q, "limit")
|
||||||
|
offset = _int_arg(q, "offset")
|
||||||
|
served = SERVED["n"] if SERVED["n"] is not None else len(NODES)
|
||||||
|
page = NODES[offset:offset + limit] if offset < served else []
|
||||||
|
return Resp({"data": {"collective": {"orders": {
|
||||||
|
"totalCount": len(NODES), "nodes": page}}}})
|
||||||
|
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = FakeClient
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, bool(ok)))
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
# --- fetch_member_orders: every order read, oldest members matched ---------
|
||||||
|
REQUESTS.clear()
|
||||||
|
by_slug = await m.fetch_member_orders()
|
||||||
|
check(f"orders read across pages (got {len(REQUESTS)} requests)", len(REQUESTS) == 3)
|
||||||
|
check(f"all 203 payers grouped (got {len(by_slug)})", len(by_slug) == TOTAL_ORDERS)
|
||||||
|
for slug in OLDEST:
|
||||||
|
orders = by_slug.get(slug) or []
|
||||||
|
check(f"oldest member {slug} is matched ({len(orders)} order)",
|
||||||
|
len(orders) == 1 and orders[0].get("status") == "ACTIVE")
|
||||||
|
# the fixed-limit bug's exact reading: these three used to be absent
|
||||||
|
check("no member is dropped by a 200-entry window",
|
||||||
|
all(s in by_slug for s in OLDEST))
|
||||||
|
|
||||||
|
# --- a partial read must RAISE, never answer short ------------------------
|
||||||
|
REQUESTS.clear()
|
||||||
|
SERVED["n"] = 200 # OC says 203, serves 200
|
||||||
|
raised = None
|
||||||
|
try:
|
||||||
|
await m.fetch_member_orders()
|
||||||
|
except RuntimeError as e:
|
||||||
|
raised = str(e)
|
||||||
|
SERVED["n"] = None
|
||||||
|
check(f"incomplete read raises (got {raised!r})",
|
||||||
|
raised is not None and "incomplete" in raised)
|
||||||
|
|
||||||
|
# --- fetch_oc_monthly_order_charges: paginated too -----------------------
|
||||||
|
REQUESTS.clear()
|
||||||
|
records = await m.fetch_oc_monthly_order_charges()
|
||||||
|
check(f"charge pass pages (got {len(REQUESTS)} requests)", len(REQUESTS) == 3)
|
||||||
|
check(f"charge pass covers every monthly order (got {len(records)})",
|
||||||
|
len(records) == TOTAL_ORDERS)
|
||||||
|
oldest_ids = {f"or_{s}" for s in OLDEST}
|
||||||
|
check("oldest orders' charge ladders present",
|
||||||
|
oldest_ids <= {r.get("order_id") for r in records})
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression tests for org-backed anchor days.
|
||||||
|
|
||||||
|
Runnable:
|
||||||
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_org_anchors.py
|
||||||
|
* from the repo root, on a host that has the app's dependencies
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
The allowance reconcile SKIPS rows with `org_slug` (dues are paid by an OC
|
||||||
|
Organization, not an individual order), so org-backed members never got an
|
||||||
|
`anchor_day` — and close_credit_cycles skipped them forever, restoring their
|
||||||
|
credit packs every month. The fix infers the anchor from the ORGANIZATION's
|
||||||
|
OC membership createdAt. Covered:
|
||||||
|
- anchor = org join day, clamped to 28
|
||||||
|
- the team reset is pinned to the next occurrence
|
||||||
|
- idempotent: a second pass touches nothing
|
||||||
|
- an org with no OC membership record is reported, never guessed
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="organchor-test-"), "members.db")
|
||||||
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|
||||||
|
pins = []
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_org_joins():
|
||||||
|
return {
|
||||||
|
"cosmos": datetime(2026, 10, 15, 23, 52, tzinfo=timezone.utc),
|
||||||
|
"late": datetime(2026, 1, 31, 12, 0, tzinfo=timezone.utc),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_team_id(email):
|
||||||
|
return f"team:{email}"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_pin(team_id, reset_at):
|
||||||
|
pins.append((team_id, reset_at.isoformat()))
|
||||||
|
|
||||||
|
|
||||||
|
m.fetch_org_join_days = fake_org_joins
|
||||||
|
m.litellm_team_id_for_email = fake_team_id
|
||||||
|
m.litellm_pin_reset_date = fake_pin
|
||||||
|
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn) # creates allowance_log and adds anchor_day
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||||
|
"VALUES ('tech@cosmos.coop', '', 1, 'member', 'cosmos')")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||||
|
"VALUES ('ops@late.org', '', 1, 'member', 'late')")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||||
|
"VALUES ('x@unknown.org', '', 1, 'member', 'unknown-org')")
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, active, account_type, org_slug, anchor_day) "
|
||||||
|
"VALUES ('already@set.org', '', 1, 'member', 'cosmos', 7)")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
first = asyncio.run(m.reconcile_org_anchors())
|
||||||
|
anchors = {r["email"]: r["anchor_day"] for r in first["anchored"]}
|
||||||
|
check("org join day 15 -> anchor 15", anchors.get("tech@cosmos.coop"), 15)
|
||||||
|
check("org join day 31 -> clamped to 28", anchors.get("ops@late.org"), 28)
|
||||||
|
check("an org with no OC record is reported, not guessed",
|
||||||
|
[u["email"] for u in first["unresolved"]], ["x@unknown.org"])
|
||||||
|
check("an already-anchored row is untouched", "already@set.org" not in anchors, True)
|
||||||
|
|
||||||
|
reset = dict((t, r) for t, r in pins)
|
||||||
|
check("reset pinned to the next occurrence of the anchor day (Dec 15)",
|
||||||
|
reset.get("team:tech@cosmos.coop", "")[:10], "2026-12-15")
|
||||||
|
|
||||||
|
second = asyncio.run(m.reconcile_org_anchors())
|
||||||
|
check("second pass leaves only the unresolved org to report", second["checked"], 1)
|
||||||
|
check("second pass writes no anchors", second["anchored"], [])
|
||||||
|
check("the unresolved org is reported again, not silently dropped",
|
||||||
|
[u["email"] for u in second["unresolved"]], ["x@unknown.org"])
|
||||||
|
|
||||||
|
row = m.get_db().execute(
|
||||||
|
"SELECT anchor_day FROM members WHERE email = 'tech@cosmos.coop'").fetchone()
|
||||||
|
check("anchor persisted", row[0], 15)
|
||||||
|
|
||||||
|
print()
|
||||||
|
if failures:
|
||||||
|
print(f"{failures} FAILURE(S)")
|
||||||
|
sys.exit(1)
|
||||||
|
print("all checks passed")
|
||||||
@@ -74,6 +74,7 @@ UNREADABLE = set() # rooms whose joined_members 500s
|
|||||||
invites_sent = [] # (room, mxid)
|
invites_sent = [] # (room, mxid)
|
||||||
INVITE_429_FOR = set() # mxids whose invite comes back 429
|
INVITE_429_FOR = set() # mxids whose invite comes back 429
|
||||||
INVITE_TIMEOUT_FOR = set() # mxids whose invite POST raises httpx.ReadTimeout
|
INVITE_TIMEOUT_FOR = set() # mxids whose invite POST raises httpx.ReadTimeout
|
||||||
|
TIMEOUT_ATTEMPTS = [] # (room, mxid) for every POST that timed out
|
||||||
POSTS = [] # Loomio POST payloads
|
POSTS = [] # Loomio POST payloads
|
||||||
|
|
||||||
ROSTER = {} # Loomio roster: email -> membership id
|
ROSTER = {} # Loomio roster: email -> membership id
|
||||||
@@ -129,6 +130,7 @@ class FakeClient:
|
|||||||
if "/invite" in url:
|
if "/invite" in url:
|
||||||
mxid = (json or {}).get("user_id")
|
mxid = (json or {}).get("user_id")
|
||||||
if mxid in INVITE_TIMEOUT_FOR:
|
if mxid in INVITE_TIMEOUT_FOR:
|
||||||
|
TIMEOUT_ATTEMPTS.append((url, mxid))
|
||||||
raise httpx.ReadTimeout("timed out")
|
raise httpx.ReadTimeout("timed out")
|
||||||
if mxid in INVITE_429_FOR:
|
if mxid in INVITE_429_FOR:
|
||||||
return FakeResp(429, {"retry_after_ms": 300000},
|
return FakeResp(429, {"retry_after_ms": 300000},
|
||||||
@@ -165,6 +167,7 @@ def reset():
|
|||||||
global invites_sent
|
global invites_sent
|
||||||
invites_sent = []
|
invites_sent = []
|
||||||
POSTS.clear()
|
POSTS.clear()
|
||||||
|
TIMEOUT_ATTEMPTS.clear()
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
@@ -209,8 +212,8 @@ async def main():
|
|||||||
not any(mx == "@amember:inference.coop" for _, mx in invites_sent))
|
not any(mx == "@amember:inference.coop" for _, mx in invites_sent))
|
||||||
check("per-room: two members can be pending on different rooms",
|
check("per-room: two members can be pending on different rooms",
|
||||||
not any(mx == "@cmember:inference.coop" for _, mx in invites_sent))
|
not any(mx == "@cmember:inference.coop" for _, mx in invites_sent))
|
||||||
check("return shape: the result carries invited + rate_limited",
|
check("return shape: the result carries invited + rate_limited + transport_skipped",
|
||||||
set(r) == {"invited", "rate_limited"} and r["rate_limited"] is False)
|
set(r) == {"invited", "rate_limited", "transport_skipped"} and r["rate_limited"] is False)
|
||||||
|
|
||||||
# --- 2. IDEMPOTENCE: a second pass sends nothing ----------------------
|
# --- 2. IDEMPOTENCE: a second pass sends nothing ----------------------
|
||||||
reset()
|
reset()
|
||||||
@@ -325,6 +328,10 @@ async def main():
|
|||||||
{room for room, _ in invites_sent} == set(ROOMS)
|
{room for room, _ in invites_sent} == set(ROOMS)
|
||||||
and all(mx == "@umember:inference.coop" for _, mx in invites_sent))
|
and all(mx == "@umember:inference.coop" for _, mx in invites_sent))
|
||||||
check("timeout: the timed-out member is not counted as invited", r["invited"] == 1)
|
check("timeout: the timed-out member is not counted as invited", r["invited"] == 1)
|
||||||
|
check("timeout: a timed-out member is attempted ONCE, not once per room",
|
||||||
|
len(TIMEOUT_ATTEMPTS) == 1)
|
||||||
|
check("timeout: the pass reports the member whose rooms it skipped",
|
||||||
|
r.get("transport_skipped") == 1)
|
||||||
|
|
||||||
# The next pass retries the timed-out member (invites are idempotent).
|
# The next pass retries the timed-out member (invites are idempotent).
|
||||||
INVITE_TIMEOUT_FOR = set()
|
INVITE_TIMEOUT_FOR = set()
|
||||||
|
|||||||
Reference in new issue
Block a user