guests: only UNSPENT credit carries into membership
ci/woodpecker/push/woodpecker Pipeline was canceled
ci/woodpecker/push/woodpecker Pipeline was canceled
A guest has no monthly cycle, so nothing ever drew their spend against the $2 pack. Conversion kept the full credit_balance, handing back credits already used — guest-access.md promises only the unspent credit carries over. record_guest_conversion_draw() writes the consumed part as a negative ledger row (reference guest-convert-draw:<email>) and bumps credits_drawn, capped by the row's credit and idempotent on replay. Tests cover draw, replay, cap, and the resulting remaining figure.
This commit is contained in:
1 parent
cfb767dd4f
commit
a70dd6ab4c
2 files changed
+140
No files matched your search
+54
@@ -3729,6 +3729,42 @@ async def provision_guest_member(
|
|||||||
return user_id
|
return user_id
|
||||||
|
|
||||||
|
|
||||||
|
def record_guest_conversion_draw(email: str, spend: float) -> float:
|
||||||
|
"""Record guest usage consumed before conversion; only the unspent part carries.
|
||||||
|
|
||||||
|
A guest has no monthly cycle, so nothing ever drew their spend against the
|
||||||
|
$2 pack. Converting without this would hand back credits already used
|
||||||
|
(guest-access.md promises only the UNSPENT credit carries over). The draw
|
||||||
|
is capped by the row's current credit and deduped on a ledger reference.
|
||||||
|
Returns the amount recorded (0.0 when nothing owed or already recorded).
|
||||||
|
"""
|
||||||
|
purchased = get_credit_balance(email)
|
||||||
|
used = round(min(max(0.0, float(spend or 0.0)), purchased), 6)
|
||||||
|
if used <= 0:
|
||||||
|
return 0.0
|
||||||
|
ref = f"guest-convert-draw:{email}"
|
||||||
|
if credit_reference_exists(ref):
|
||||||
|
return 0.0
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO credit_ledger (email, delta, reason, reference) "
|
||||||
|
"VALUES (?, ?, ?, ?)",
|
||||||
|
(email, -used,
|
||||||
|
"guest credit used before conversion — only unspent credit carries over",
|
||||||
|
ref),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE members SET credits_drawn = COALESCE(credits_drawn, 0) + ? "
|
||||||
|
"WHERE email = ?",
|
||||||
|
(used, email),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return used
|
||||||
|
|
||||||
|
|
||||||
async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str:
|
async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str:
|
||||||
"""Convert a GUEST account into a full member (the automatic transition).
|
"""Convert a GUEST account into a full member (the automatic transition).
|
||||||
|
|
||||||
@@ -3775,6 +3811,24 @@ async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str:
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
# Guest usage has already consumed part of the $2; only the UNSPENT credit
|
||||||
|
# may carry into membership (guest-access.md). record_guest_conversion_draw
|
||||||
|
# writes the consumed part as a draw so it cannot be spent twice.
|
||||||
|
try:
|
||||||
|
guest_spend = None
|
||||||
|
team_id = await litellm_team_id_for_email(email)
|
||||||
|
if team_id:
|
||||||
|
team = get_team_budget_from_db(team_id)
|
||||||
|
if team:
|
||||||
|
guest_spend = float(team.get("spend") or 0.0)
|
||||||
|
if guest_spend is not None:
|
||||||
|
used = record_guest_conversion_draw(email, guest_spend)
|
||||||
|
if used > 0:
|
||||||
|
logger.info("Guest convert: %.2f of guest credit already used for %s; "
|
||||||
|
"the rest carries over", used, email)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
logger.warning("Guest convert: guest-draw accounting failed for %s: %s", email, e)
|
||||||
|
|
||||||
# 3. Lift the LiteLLM cap to allowance + credits and pin the reset to
|
# 3. Lift the LiteLLM cap to allowance + credits and pin the reset to
|
||||||
# their anchor day, exactly as the webhook does for any member.
|
# their anchor day, exactly as the webhook does for any member.
|
||||||
await sync_team_budget_from_balance(email)
|
await sync_team_budget_from_balance(email)
|
||||||
|
|||||||
@@ -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")
|
||||||
Reference in new issue
Block a user