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()
|
||||
|
||||
|
||||
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).
|
||||
|
||||
The overage is `max(0, spend − allowance)`, capped by the credits still
|
||||
available. Records a NEGATIVE ledger row and bumps `credits_drawn` in one
|
||||
transaction; the reference `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).
|
||||
The overage is `max(0, spend − allowance)` — or the caller's
|
||||
`credit-eligible` figure when credits arrived mid-cycle — capped by the
|
||||
credits still available. Records a NEGATIVE ledger row and bumps
|
||||
`credits_drawn` in one transaction; the reference
|
||||
`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}"
|
||||
if credit_reference_exists(ref):
|
||||
return 0.0
|
||||
purchased = get_credit_balance(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:
|
||||
return 0.0
|
||||
conn = get_db()
|
||||
@@ -4440,7 +4524,8 @@ def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float)
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
(email, -draw,
|
||||
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),
|
||||
)
|
||||
conn.execute(
|
||||
@@ -4532,15 +4617,22 @@ async def close_credit_cycles() -> dict:
|
||||
break
|
||||
|
||||
available = max(0.0, purchased - get_credits_drawn(email))
|
||||
overage = max(0.0, spend - allowance)
|
||||
draw = round(min(overage, available), 6)
|
||||
eligible = credit_eligible_overage(email, team_id, cycle_start,
|
||||
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:
|
||||
drawn = apply_cycle_draw(email, cycle_key, spend, allowance)
|
||||
drawn = apply_cycle_draw(email, cycle_key, spend, allowance,
|
||||
eligible=eligible)
|
||||
if drawn > 0:
|
||||
closed += 1
|
||||
drawn_total += drawn
|
||||
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
|
||||
|
||||
# Re-sync the cap only when it will not put the member under their
|
||||
|
||||
Reference in new issue
Block a user