credits: only charge spend incurred while credits were available (#12 follow-up)
ci/woodpecker/push/woodpecker Pipeline was canceled
ci/woodpecker/push/woodpecker Pipeline was canceled
close_credit_cycles drew max(0, cycle_spend - allowance) capped by the pack's current balance, so a pack bought mid-cycle was charged for spend that predated it. Split the cycle at the first grant: allowance is consumed first, then credits cover only the spend after they became available. apply_cycle_draw takes the eligible figure; the ledger reason records it. Correction rows for the six over-drawn clawback cycles are separate.
This commit is contained in:
1 parent
122824fd99
commit
ca336a3115
3 files changed
+225
-12
No files matched your search
+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
|
||||||
|
|||||||
@@ -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