Compare commits
5
Commits
122824fd99
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b7a74d891 | ||
|
|
205c695556 | ||
|
|
3db67e54f3 | ||
|
|
bbd8115058 | ||
|
|
ca336a3115 |
No files matched your search
@@ -29,11 +29,15 @@
|
|||||||
"credit_cycle_close": {
|
"credit_cycle_close": {
|
||||||
"schedule": "*/10 * * * *",
|
"schedule": "*/10 * * * *",
|
||||||
"command": "/app/code/credit_cycle_close.sh"
|
"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:20261128-1191bcd"
|
"dockerImage": "registry.inference.coop/code/member-portal:20261203-3db67e5"
|
||||||
}
|
}
|
||||||
+2
-1
@@ -12,7 +12,8 @@ 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 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/credit_cycle_close.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)
|
||||||
|
|||||||
+104
-12
@@ -4416,21 +4416,105 @@ def cycle_spend_from_ledger(team_id: str, start: datetime, end: datetime) -> flo
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float) -> float:
|
def credit_available_at_start(email: str, when: datetime) -> float:
|
||||||
|
"""Credit balance the member already had when a cycle began.
|
||||||
|
|
||||||
|
The ledger is the full history (purchases positive, draws negative), so its
|
||||||
|
running sum is the spendable balance at any timestamp. A pack bought while
|
||||||
|
the previous cycle was open is available at the next boundary.
|
||||||
|
"""
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT COALESCE(SUM(delta), 0) FROM credit_ledger "
|
||||||
|
"WHERE email = ? AND created_at < ?",
|
||||||
|
(email, when.strftime("%Y-%m-%d %H:%M:%S")),
|
||||||
|
).fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return float(row[0] or 0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def first_credit_available(email: str, start: datetime, end: datetime) -> datetime | None:
|
||||||
|
"""First moment inside [start, end) when the member's credit balance is > 0.
|
||||||
|
|
||||||
|
Returns `start` when credits were already available at the boundary, None
|
||||||
|
when the cycle never had credits, and the purchase timestamp when a pack
|
||||||
|
arrived mid-cycle.
|
||||||
|
"""
|
||||||
|
running = credit_available_at_start(email, start)
|
||||||
|
if running > 0:
|
||||||
|
return start
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT created_at, delta FROM credit_ledger "
|
||||||
|
"WHERE email = ? AND created_at >= ? AND created_at < ? "
|
||||||
|
"ORDER BY created_at, id",
|
||||||
|
(email, start.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
end.strftime("%Y-%m-%d %H:%M:%S")),
|
||||||
|
).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
for created_at, delta in rows:
|
||||||
|
running += float(delta or 0.0)
|
||||||
|
if running > 0:
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(created_at).replace(tzinfo=timezone.utc)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def credit_eligible_overage(email: str, team_id: str, cycle_start: datetime,
|
||||||
|
cycle_end: datetime, allowance: float,
|
||||||
|
total_spend: float | None = None) -> float | None:
|
||||||
|
"""The part of a cycle's overage that credits could actually have covered.
|
||||||
|
|
||||||
|
Spend before the pack existed is not credit spend. With credits available
|
||||||
|
from the boundary, the whole overage is eligible. Otherwise split the cycle
|
||||||
|
at the first grant: allowance is consumed first, then credits cover the
|
||||||
|
spend after that point. Returns None when SpendLogs cannot be read.
|
||||||
|
"""
|
||||||
|
if total_spend is None:
|
||||||
|
total_spend = cycle_spend_from_ledger(team_id, cycle_start, cycle_end)
|
||||||
|
if total_spend is None:
|
||||||
|
return None
|
||||||
|
available_from_start = credit_available_at_start(email, cycle_start)
|
||||||
|
if available_from_start > 0:
|
||||||
|
return round(max(0.0, total_spend - allowance), 6)
|
||||||
|
grant_at = first_credit_available(email, cycle_start, cycle_end)
|
||||||
|
if grant_at is None:
|
||||||
|
return 0.0
|
||||||
|
if grant_at <= cycle_start:
|
||||||
|
return round(max(0.0, total_spend - allowance), 6)
|
||||||
|
spend_before = cycle_spend_from_ledger(team_id, cycle_start, grant_at)
|
||||||
|
if spend_before is None:
|
||||||
|
return None
|
||||||
|
spend_after = max(0.0, total_spend - spend_before)
|
||||||
|
allowance_left = max(0.0, allowance - spend_before)
|
||||||
|
return round(max(0.0, spend_after - allowance_left), 6)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float,
|
||||||
|
eligible: float | None = None) -> float:
|
||||||
"""Draw a closed cycle's credit overage from a member's pack (idempotent).
|
"""Draw a closed cycle's credit overage from a member's pack (idempotent).
|
||||||
|
|
||||||
The overage is `max(0, spend − allowance)`, capped by the credits still
|
The overage is `max(0, spend − allowance)` — or the caller's
|
||||||
available. Records a NEGATIVE ledger row and bumps `credits_drawn` in one
|
`credit-eligible` figure when credits arrived mid-cycle — capped by the
|
||||||
transaction; the reference `cycle-close:<email>:<cycle>` is the dedupe key,
|
credits still available. Records a NEGATIVE ledger row and bumps
|
||||||
so a repeat call for the same cycle applies nothing. Returns the amount
|
`credits_drawn` in one transaction; the reference
|
||||||
drawn (0.0 when nothing was owed or the draw already happened).
|
`cycle-close:<email>:<cycle>` is the dedupe key, so a repeat call for the
|
||||||
|
same cycle applies nothing. Returns the amount drawn (0.0 when nothing was
|
||||||
|
owed or the draw already happened).
|
||||||
"""
|
"""
|
||||||
ref = f"cycle-close:{email}:{cycle_key}"
|
ref = f"cycle-close:{email}:{cycle_key}"
|
||||||
if credit_reference_exists(ref):
|
if credit_reference_exists(ref):
|
||||||
return 0.0
|
return 0.0
|
||||||
purchased = get_credit_balance(email)
|
purchased = get_credit_balance(email)
|
||||||
available = max(0.0, purchased - get_credits_drawn(email))
|
available = max(0.0, purchased - get_credits_drawn(email))
|
||||||
draw = round(min(max(0.0, spend - allowance), available), 6)
|
overage = max(0.0, spend - allowance) if eligible is None else eligible
|
||||||
|
draw = round(min(max(0.0, overage), available), 6)
|
||||||
if draw <= 0:
|
if draw <= 0:
|
||||||
return 0.0
|
return 0.0
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
@@ -4440,7 +4524,8 @@ def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float)
|
|||||||
"VALUES (?, ?, ?, ?)",
|
"VALUES (?, ?, ?, ?)",
|
||||||
(email, -draw,
|
(email, -draw,
|
||||||
f"credits used in cycle {cycle_key} "
|
f"credits used in cycle {cycle_key} "
|
||||||
f"(${spend:.2f} spend, ${allowance:.2f} allowance)",
|
f"(${spend:.2f} spend, ${allowance:.2f} allowance, "
|
||||||
|
f"${overage:.2f} credit-eligible)",
|
||||||
ref),
|
ref),
|
||||||
)
|
)
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -4532,15 +4617,22 @@ async def close_credit_cycles() -> dict:
|
|||||||
break
|
break
|
||||||
|
|
||||||
available = max(0.0, purchased - get_credits_drawn(email))
|
available = max(0.0, purchased - get_credits_drawn(email))
|
||||||
overage = max(0.0, spend - allowance)
|
eligible = credit_eligible_overage(email, team_id, cycle_start,
|
||||||
draw = round(min(overage, available), 6)
|
cycle_end, allowance, spend)
|
||||||
|
if eligible is None:
|
||||||
|
errors.append(f"{email}/{cycle_key}: eligibility read failed")
|
||||||
|
break
|
||||||
|
draw = round(min(eligible, available), 6)
|
||||||
if draw > 0:
|
if draw > 0:
|
||||||
drawn = apply_cycle_draw(email, cycle_key, spend, allowance)
|
drawn = apply_cycle_draw(email, cycle_key, spend, allowance,
|
||||||
|
eligible=eligible)
|
||||||
if drawn > 0:
|
if drawn > 0:
|
||||||
closed += 1
|
closed += 1
|
||||||
drawn_total += drawn
|
drawn_total += drawn
|
||||||
details.append({"email": email, "cycle": cycle_key,
|
details.append({"email": email, "cycle": cycle_key,
|
||||||
"spend": round(spend, 2), "drawn": round(drawn, 2)})
|
"spend": round(spend, 2),
|
||||||
|
"eligible": round(eligible, 2),
|
||||||
|
"drawn": round(drawn, 2)})
|
||||||
cycle_end = cycle_start
|
cycle_end = cycle_start
|
||||||
|
|
||||||
# Re-sync the cap only when it will not put the member under their
|
# Re-sync the cap only when it will not put the member under their
|
||||||
|
|||||||
@@ -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())
|
||||||
@@ -158,6 +158,9 @@ m._ensure_allowance_tables(conn) # adds anchor_day
|
|||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance, anchor_day) "
|
"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,))
|
"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.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|||||||
@@ -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")
|
||||||
Reference in new issue
Block a user