gift cancel: self-service cancellation with credit return and full audit trail
POST /broker/cancel-gift (dashboard broker identity, gift accounts only, idempotent) + GET /broker/gift-status for the ended-state view. Semantics match the gift lapse: row deactivated, account kept for a clean resume, gateway budget zeroed, newsletter off — plus the return a lapse does not do: unspent credit back to the co-op as a NEGATIVE credit_ledger row whose reason names the cancellation and the original gift reference, deduped on its own reference. Gifts ledger records inviter → recipient → 'cancelled by recipient'. The user leaves the guests group for GUESTS_ENDED_GROUP_ID (dashboard-only visibility for the ended state); the reaching-limits notice is pre-marked so a self-cancelled guest is never told their credits were spent. Tests: tests/test_gift_cancel.py (19 fixture checks, network-guarded).
This commit is contained in:
1 parent
9c441dc0aa
commit
40fb75a34b
2 files changed
+538
No files matched your search
+255
@@ -357,6 +357,16 @@ GIFT_PER_INVITER_DAYS = float(os.environ.get("GIFT_PER_INVITER_DAYS", "30"))
|
||||
# exactly those two apps — nothing else is granted by group membership.
|
||||
GUESTS_GROUP_ID = os.environ.get("GUESTS_GROUP_ID", "")
|
||||
|
||||
# Where a SELF-CANCELLED guest's Cloudron user goes: out of the guests group,
|
||||
# so chat (and every other app gated to members+guests) stops admitting them —
|
||||
# but INTO a group the dashboard app lists in its access restriction, so the
|
||||
# ended state ("your access has ended", data kept, Become-a-member) stays
|
||||
# reachable. Gateway access is revoked separately (team budget zeroed), so the
|
||||
# dashboard view is read-only by construction. Falls back to the shared
|
||||
# inactive group when unset — then the dashboard itself is also closed off and
|
||||
# the ended state is visible only in the cancellation response.
|
||||
GUESTS_ENDED_GROUP_ID = os.environ.get("GUESTS_ENDED_GROUP_ID", "")
|
||||
|
||||
# Where a guest's "Become a member" button and email point (the contribution
|
||||
# page — what actually starts a membership). Deliberately NOT the portal's
|
||||
# credit-pack URL: a guest needs a membership, not a credit pack.
|
||||
@@ -2981,6 +2991,146 @@ async def reconcile_gift_lifecycles() -> dict:
|
||||
return {"expired": expired, "depleted": depleted, "lapse_notices": notified}
|
||||
|
||||
|
||||
async def cancel_gift_account(email: str) -> dict:
|
||||
"""End a gift account at the recipient's own request (self-service cancel).
|
||||
|
||||
The guest-side counterpart to reconcile_gift_lifecycles: the recipient
|
||||
cancels from their dashboard instead of waiting out the time box. Same
|
||||
deactivation semantics as a gift lapse — the account and its data are
|
||||
KEPT so a re-invite (or the guest → member conversion) resumes cleanly —
|
||||
plus the one thing a lapse does not do: the unspent credit returns to
|
||||
the co-op.
|
||||
|
||||
* LiteLLM team budget zeroed (every key under it stops working);
|
||||
* the Cloudron user leaves the guests group (chat access ends) and
|
||||
moves to GUESTS_ENDED_GROUP_ID, which the dashboard app still admits
|
||||
so the ended state and the Become-a-member path stay visible;
|
||||
* newsletter unsubscribed;
|
||||
* unspent credit returned: a credit_ledger row with a NEGATIVE delta,
|
||||
its reason naming the cancellation and the original gift reference
|
||||
(traceable), its reference deduping the return so a repeated cancel
|
||||
can never double-credit the accounting;
|
||||
* the gifts ledger records the full trail: inviter → recipient →
|
||||
'cancelled by recipient' (rows are never deleted or rewritten);
|
||||
* the reaching-limits bookkeeping is pre-marked when that subsystem is
|
||||
deployed: someone who cancelled themselves must never be told their
|
||||
credits were spent.
|
||||
|
||||
Idempotent: a second call is a no-op that reports the recorded outcome.
|
||||
Refuses (403) anything that is not a gift account — a paying member can
|
||||
never end a membership through this path, and there is deliberately no
|
||||
member analogue: cancelling a membership means ending the Open Collective
|
||||
contribution.
|
||||
"""
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT active, account_type, cloudron_user_id, balance, credit_balance "
|
||||
"FROM members WHERE email = ?",
|
||||
(email,),
|
||||
).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
raise HTTPException(403, "No active membership")
|
||||
active, account_type, user_id, balance, credits = row
|
||||
if (account_type or "member") != "gift":
|
||||
# The hard member guard: this endpoint only ever ends GIFT access.
|
||||
# A membership is ended by ending its Open Collective contribution.
|
||||
raise HTTPException(403, "Only gift accounts can be cancelled here")
|
||||
|
||||
gift_status = _gift_ledger_status(email)
|
||||
if not active:
|
||||
# Already ended (a previous cancel, or the sweep's lapse). No-op —
|
||||
# and never a second return of credit.
|
||||
return {
|
||||
"status": "already_ended",
|
||||
"gift_status": gift_status or "inactive",
|
||||
"credits_returned": _gift_returned_credits(email),
|
||||
}
|
||||
|
||||
# Unspent credit = the credits bucket minus what this cycle's spend
|
||||
# already drew (a gift row holds NO allowance — balance is 0 — so the
|
||||
# credits model's remaining figure IS the unspent gift).
|
||||
allowance = float(balance) if balance is not None else 0.0
|
||||
credit_total = float(credits or 0.0)
|
||||
spend = None
|
||||
team_id = await litellm_team_id_for_email(email)
|
||||
if team_id:
|
||||
team = get_team_budget_from_db(team_id)
|
||||
if team:
|
||||
spend = team.get("spend")
|
||||
unspent = round(compute_max_budget(allowance, credit_total, spend)["credits_remaining"], 2)
|
||||
|
||||
return_ref = f"gift-return:{email}"
|
||||
# The ledger is the accounting record: when a return row already exists
|
||||
# (a cancel that failed part-way through), report what IT recorded and
|
||||
# never write a second one — dedupe lives on the reference.
|
||||
credits_returned = _gift_returned_credits(email) if credit_reference_exists(return_ref) else 0.0
|
||||
if credits_returned == 0.0 and unspent > 0:
|
||||
add_credits(
|
||||
email, -unspent,
|
||||
reason=(f"gift cancelled by recipient — unspent credit returned to the "
|
||||
f"co-op (original gift: gift:{email})"),
|
||||
reference=return_ref,
|
||||
)
|
||||
credits_returned = unspent
|
||||
|
||||
# Deactivation, gift-lapse semantics: row inactive, group out of guests,
|
||||
# gateway budget zeroed, newsletter off.
|
||||
deactivate_member(email)
|
||||
ended_group = GUESTS_ENDED_GROUP_ID or INACTIVE_GROUP_ID
|
||||
if ended_group and user_id:
|
||||
await cloudron_set_group(user_id, ended_group)
|
||||
await revoke_member_litellm_access(email)
|
||||
await listmonk_sync(email, subscribe=False)
|
||||
|
||||
conn = get_db()
|
||||
conn.execute(
|
||||
"UPDATE gifts SET status = 'cancelled by recipient' "
|
||||
"WHERE recipient_email = ? AND status = 'active'",
|
||||
(email,),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# Pre-mark the reaching-limits notice: the sweep's catch-up must not
|
||||
# email a "your credits were spent" notice to someone who cancelled
|
||||
# themselves — they were told by doing it.
|
||||
mark_gift_lapse_notice_sent(email, "cancelled by recipient")
|
||||
|
||||
logger.info("Gift cancel: %s cancelled by recipient (returned %.2f)", email, credits_returned)
|
||||
return {
|
||||
"status": "cancelled",
|
||||
"gift_status": "cancelled by recipient",
|
||||
"credits_returned": credits_returned,
|
||||
}
|
||||
|
||||
|
||||
def _gift_ledger_status(email: str) -> str | None:
|
||||
"""The latest gifts-ledger status for a recipient, or None."""
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT status FROM gifts WHERE recipient_email = ? ORDER BY id DESC LIMIT 1",
|
||||
(email,),
|
||||
).fetchone()
|
||||
conn.close()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
def _gift_returned_credits(email: str) -> float:
|
||||
"""Credit returned to the co-op for this gift (0 when there was none).
|
||||
|
||||
Read back from the ledger — the return row IS the accounting record, so
|
||||
the reported amount always matches what was actually written.
|
||||
"""
|
||||
conn = get_db()
|
||||
rows = conn.execute(
|
||||
"SELECT delta FROM credit_ledger WHERE reference = ?",
|
||||
(f"gift-return:{email}",),
|
||||
).fetchall()
|
||||
conn.close()
|
||||
return round(sum(-float(r[0] or 0.0) for r in rows), 2)
|
||||
|
||||
|
||||
async def litellm_get_or_create_team(email: str, budget: float,
|
||||
budget_duration: str | None = "30d") -> str:
|
||||
"""Return the team_id for a member's budget team, creating it if needed.
|
||||
@@ -5279,6 +5429,45 @@ def resolve_member_email(identity: str) -> str:
|
||||
raise HTTPException(403, f"No Cloudron user for identity {identity!r}")
|
||||
|
||||
|
||||
def _verify_broker_gift_identity(request: Request) -> str:
|
||||
"""Broker auth that also admits ENDED gift accounts.
|
||||
|
||||
Same shared-secret + identity contract as _verify_broker_secret, with one
|
||||
widening scoped to gift accounts only: a guest is admitted in ANY state,
|
||||
because the self-service cancel must stay a no-op after it takes effect
|
||||
and the ended state must render on a later page load. Members (and only
|
||||
members) still require an active row, so this never widens what a member
|
||||
identity can reach — the routes on top enforce the gift-only rule again.
|
||||
"""
|
||||
if not BROKER_SECRET:
|
||||
raise HTTPException(503, "Broker secret not configured")
|
||||
provided = request.headers.get("x-broker-secret", "")
|
||||
if not secrets.compare_digest(provided, BROKER_SECRET):
|
||||
raise HTTPException(401, "Invalid broker secret")
|
||||
identity = (
|
||||
request.headers.get("x-member-email")
|
||||
or request.headers.get("x-member-user")
|
||||
or ""
|
||||
).strip()
|
||||
if not identity:
|
||||
raise HTTPException(401, "Missing member identity")
|
||||
email = resolve_member_email(identity)
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT account_type, active FROM members WHERE email = ?", (email,)
|
||||
).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
raise HTTPException(403, "No active membership")
|
||||
account_type, active = (row[0] or "member"), row[1]
|
||||
if account_type == "gift":
|
||||
return email # any state — the cancel/gift-status route decides
|
||||
if not active or not get_member_key(email):
|
||||
raise HTTPException(403, "No active membership")
|
||||
maybe_first_login_service_sync(email)
|
||||
return email
|
||||
|
||||
|
||||
@app.get("/broker/keys")
|
||||
@limiter.limit("30/minute")
|
||||
async def broker_list(request: Request):
|
||||
@@ -5589,6 +5778,72 @@ async def broker_usage(request: Request, days: int = 0):
|
||||
return await broker_get_usage(email, days=days)
|
||||
|
||||
|
||||
@app.get("/broker/gift-status")
|
||||
@limiter.limit("30/minute")
|
||||
async def broker_gift_status(request: Request):
|
||||
"""What became of the caller's gift account (self-service cancel support).
|
||||
|
||||
Served through the broker like every dashboard route. The one broker read
|
||||
that answers for an ENDED gift too (see _verify_broker_gift_identity): a
|
||||
cancelled or lapsed guest's dashboard loads this so it can say, plainly,
|
||||
that access ended — the data is kept — and a membership is still one
|
||||
contribution away. For an active gift it reports what the cancel button
|
||||
needs (guest, active, ledger status); for a member it simply says
|
||||
guest: false.
|
||||
"""
|
||||
email = _verify_broker_gift_identity(request)
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT active, balance, credit_balance FROM members WHERE email = ?",
|
||||
(email,),
|
||||
).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
raise HTTPException(403, "No active membership")
|
||||
active, balance, credits = row
|
||||
if not is_gift_account(email):
|
||||
return {"guest": False, "active": bool(active)}
|
||||
gift_status = _gift_ledger_status(email) or ("active" if active else "inactive")
|
||||
if active:
|
||||
# Same remaining-credit figure the usage view shows.
|
||||
spend = None
|
||||
team_id = await litellm_team_id_for_email(email)
|
||||
if team_id:
|
||||
team = get_team_budget_from_db(team_id)
|
||||
if team:
|
||||
spend = team.get("spend")
|
||||
eff = compute_max_budget(
|
||||
float(balance) if balance is not None else 0.0,
|
||||
float(credits or 0.0),
|
||||
spend,
|
||||
)
|
||||
credits_remaining = round(eff["credits_remaining"], 2)
|
||||
else:
|
||||
credits_remaining = 0.0
|
||||
return {
|
||||
"guest": True,
|
||||
"active": bool(active),
|
||||
"ended": not active,
|
||||
"gift_status": gift_status,
|
||||
"cancelled": gift_status == "cancelled by recipient",
|
||||
"credits_remaining": credits_remaining,
|
||||
"credits_returned": _gift_returned_credits(email),
|
||||
}
|
||||
|
||||
|
||||
@app.post("/broker/cancel-gift")
|
||||
@limiter.limit("10/minute")
|
||||
async def broker_cancel_gift(request: Request):
|
||||
"""End the caller's own gift account (self-service cancellation).
|
||||
|
||||
Authenticated with the member-dashboard broker identity, gift accounts
|
||||
only (see cancel_gift_account for the semantics and the idempotence).
|
||||
A paying member calling this gets a 403, never a cancellation.
|
||||
"""
|
||||
email = _verify_broker_gift_identity(request)
|
||||
return await cancel_gift_account(email)
|
||||
|
||||
|
||||
@app.get("/broker/metrics")
|
||||
@limiter.limit("30/minute")
|
||||
async def broker_metrics(request: Request, days: int = 90):
|
||||
|
||||
Reference in new issue
Block a user