gift accounts: $5 guest passes with time box, inviter ledger, auto member conversion
Operator feature: a member gives a friend access with $5 of credits, no OC membership. Cloudron user lands in the guests group (chat + dashboard only), LiteLLM team capped at GIFT_BUDGET with NO monthly reset, portal row marked account_type='gift' with gift_expires_at set, gift welcome email, newsletter subscription, and a gifts ledger recording inviter -> recipient (one gift per inviter per 30 days, one per recipient ever). Sweep safety: reconcile_memberships never deactivates a gift for lacking an OC contribution; reconcile_gift_lifecycles lapses gifts by their own rules (credits spent out, or the GIFT_DAYS time box) with member-deactivation semantics. Guests are excluded from Loomio/Matrix invite lists, the reinvite path, budget notices, the allowance reconciliation and the metrics member counts. Conversion: a gift whose OC identity appears under its own email converts automatically (webhook + sweep + /admin/provision all funnel through provision_member): group guests->members, cap lifted to allowance + carried credits, anchor day kept, congrats email, full member onboarding. /admin/gift-convert links a membership paid under a different OC email (members.oc_email, matched by the sweep and webhook). Fixture test: tests/test_gift_lifecycle.py (37 checks, network replaced by a raising guard).
This commit is contained in:
1 parent
73d8c61aa7
commit
6d9074eefe
4 files changed
+1159
-32
No files matched your search
@@ -50,6 +50,50 @@ LibreChat ──→ Member Portal ──→ LiteLLM ──→ backend
|
|||||||
| `ALLOWANCE_POLICY` | `report` (default) \| `on`. `report` computes every allowance decision and changes nothing; `on` performs renewals and sends the one reminder. Deactivation is gated separately by `ALLOWANCE_DEACTIVATE`. |
|
| `ALLOWANCE_POLICY` | `report` (default) \| `on`. `report` computes every allowance decision and changes nothing; `on` performs renewals and sends the one reminder. Deactivation is gated separately by `ALLOWANCE_DEACTIVATE`. |
|
||||||
| `ALLOWANCE_DEACTIVATE` | `off` (default) \| `on`. When `on`, a member who was reminded and is still unpaid after the grace window is moved to the inactive group. **Defaults off so renewals/reminders can run before anyone loses access.** |
|
| `ALLOWANCE_DEACTIVATE` | `off` (default) \| `on`. When `on`, a member who was reminded and is still unpaid after the grace window is moved to the inactive group. **Defaults off so renewals/reminders can run before anyone loses access.** |
|
||||||
| `PAYMENT_GRACE_DAYS` | Days after the single reminder before an unpaid member is deactivated (default `7`). |
|
| `PAYMENT_GRACE_DAYS` | Days after the single reminder before an unpaid member is deactivated (default `7`). |
|
||||||
|
| `GIFT_BUDGET` | Gift-account credit in USD (default `5.0`). |
|
||||||
|
| `GIFT_DAYS` | Gift-account time box in days from provisioning (default `60`). The sweep deactivates an expired gift even with credits left. |
|
||||||
|
| `GIFT_PER_INVITER_DAYS` | Rolling window for the one-gift-per-inviter limit (default `30`). |
|
||||||
|
| `GUESTS_GROUP_ID` | Cloudron group ID for gift accounts. The chat and dashboard apps' access restrictions list BOTH the members and guests groups, so a guest reaches exactly those two apps. |
|
||||||
|
|
||||||
|
## Gift accounts
|
||||||
|
|
||||||
|
A member can give a friend access to the co-op with $5 of credits — no Open
|
||||||
|
Collective membership required. `POST /admin/provision-gift` (X-Admin-Token)
|
||||||
|
with `{"email", "name", "inviter": "<the gifting member's email>"}` runs the
|
||||||
|
gift pipeline: Cloudron user in the **guests** group, a LiteLLM team capped at
|
||||||
|
`GIFT_BUDGET` with **no monthly reset** (the cap is the gift's whole life), the
|
||||||
|
portal row marked `account_type='gift'` with the $5 held as non-expiring
|
||||||
|
credit, `gift_expires_at` set to now + `GIFT_DAYS`, the gift welcome email
|
||||||
|
(setup link, what they can use, Become-a-member, newsletter note), and a
|
||||||
|
**gifts ledger** row (`gifts` table: inviter → recipient, expiry, status) for
|
||||||
|
the abuse audit. Guards: one gift per inviter per `GIFT_PER_INVITER_DAYS`; one
|
||||||
|
gift per recipient ever; the inviter must be an active member; an existing
|
||||||
|
portal row under the recipient address is refused. Guests are subscribed to
|
||||||
|
the newsletter and invited to NOTHING else (no Loomio, no Matrix).
|
||||||
|
|
||||||
|
**Sweep safety.** `reconcile_memberships()` never deactivates a gift for
|
||||||
|
lacking an OC contribution. A gift lapses only by its own rules, handled by
|
||||||
|
`reconcile_gift_lifecycles()` inside the sweep: credits spent out (LiteLLM's
|
||||||
|
cap enforces the limit; the sweep retires the row) or the `GIFT_DAYS` time box.
|
||||||
|
Deactivation is the same semantics as a member's — guests group → inactive,
|
||||||
|
budget zeroed, row `active=0`, newsletter unsubscribed — and the account is
|
||||||
|
KEPT so a returning payer resumes cleanly.
|
||||||
|
|
||||||
|
**Guest → member conversion (automatic).** When a gift's OC identity appears as
|
||||||
|
a live BACKER/ADMIN with the account's own email — via the webhook or the
|
||||||
|
nightly sweep — `provision_member()` routes the call to
|
||||||
|
`convert_gift_to_member()`: the Cloudron user moves guests → members, the
|
||||||
|
LiteLLM cap lifts to the member allowance + credits (unspent gift credit is
|
||||||
|
carried — it already lives in `credit_balance`), the row becomes a normal
|
||||||
|
member with the standard `MEMBER_BUDGET`, the anchor day (the gift's start
|
||||||
|
date) is kept and the reset pinned to it, the congratulations email goes out,
|
||||||
|
and the normal member onboarding runs (newsletter, Loomio + Matrix syncs,
|
||||||
|
docs-RAG group, held-credit grants). When the contribution arrives under a
|
||||||
|
DIFFERENT OC email it cannot auto-match: the operator links it with
|
||||||
|
`POST /admin/gift-convert` `{"email": "<gift account>", "oc_email": "<the OC
|
||||||
|
email the contribution is under>"}` — the row records `members.oc_email`, and
|
||||||
|
the sweep and webhook treat that address as an additional matcher from then on.
|
||||||
|
|
||||||
|
|
||||||
## Budget model
|
## Budget model
|
||||||
|
|
||||||
|
|||||||
+765
-30
File diff suppressed because it is too large.
Load diff
+10
-2
@@ -207,13 +207,21 @@ def from_sqlite() -> dict:
|
|||||||
"""Members, plus the provisioning dates that give the growth curve.
|
"""Members, plus the provisioning dates that give the growth curve.
|
||||||
|
|
||||||
Operator/utility accounts are excluded, matching the panel's member count.
|
Operator/utility accounts are excluded, matching the panel's member count.
|
||||||
|
GIFT accounts are excluded too: they are $5 guest passes, not members —
|
||||||
|
counting them would move the growth curve the co-op publishes.
|
||||||
"""
|
"""
|
||||||
conn = connect()
|
conn = connect()
|
||||||
try:
|
try:
|
||||||
rows = conn.execute("SELECT email, active, welcome_sent_at FROM members").fetchall()
|
cols = {r[1] for r in conn.execute("PRAGMA table_info(members)").fetchall()}
|
||||||
|
sel = "SELECT email, active, welcome_sent_at" + (
|
||||||
|
", account_type" if "account_type" in cols else "") + " FROM members"
|
||||||
|
has_acct = "account_type" in cols
|
||||||
|
rows = conn.execute(sel).fetchall()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
real = [r for r in rows if (r[0] or "").strip().lower() not in OPERATOR_EMAILS]
|
real = [r for r in rows
|
||||||
|
if (r[0] or "").strip().lower() not in OPERATOR_EMAILS
|
||||||
|
and not (has_acct and len(r) > 3 and (r[3] or "") == "gift")]
|
||||||
return {
|
return {
|
||||||
"active": sum(1 for r in real if r[1]),
|
"active": sum(1 for r in real if r[1]),
|
||||||
"total": len(real),
|
"total": len(real),
|
||||||
|
|||||||
@@ -0,0 +1,340 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Gift-account lifecycle tests — structurally isolated from live services.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
Gift accounts (operator feature, 2026-11-08) touch money ($5 of credits),
|
||||||
|
Cloudron groups and email. Every path proven here runs against a FIXTURE
|
||||||
|
database with the network layer REPLACED BY A RAISING GUARD: any code path
|
||||||
|
that tries to reach Cloudron, LiteLLM, OC, Listmonk, Loomio, Matrix or SMTP
|
||||||
|
outside the stubs fails the test loudly instead of acting on live systems.
|
||||||
|
|
||||||
|
GUARDS (abuse protection — one gift per inviter per 30d, one per recipient)
|
||||||
|
1. An inviter who is not an active member is refused.
|
||||||
|
2. A SECOND gift by the same inviter within the window is refused.
|
||||||
|
3. A recipient who already received a gift (ledger) or already has a
|
||||||
|
portal row is refused.
|
||||||
|
PROVISION
|
||||||
|
4. The full gift pipeline marks the row (account_type='gift', balance 0,
|
||||||
|
credit_balance 5, gift_expires_at set, anchor day kept), records
|
||||||
|
inviter → recipient in the gifts ledger, subscribes the newsletter,
|
||||||
|
and sends the gift welcome email — no Loomio/Matrix calls.
|
||||||
|
CONVERT (guest → member)
|
||||||
|
5. Group moves guests → members; allowance set to MEMBER_BUDGET; the
|
||||||
|
unspent gift credit carries; the cap lifts to allowance + credits
|
||||||
|
(15 + 5); the anchor day is KEPT; the congrats email goes out; the
|
||||||
|
gifts-ledger row becomes 'converted'; Loomio + Matrix syncs fire.
|
||||||
|
LIFECYCLE (sweep pass)
|
||||||
|
6. An EXPIRED gift (past gift_expires_at, credits remaining) is
|
||||||
|
deactivated by the sweep: row active=0, group → inactive, budget
|
||||||
|
zeroed, newsletter unsubscribed, ledger status 'expired'.
|
||||||
|
7. A DEPLETED gift (spend reached the credits) is deactivated likewise,
|
||||||
|
status 'depleted'.
|
||||||
|
8. A healthy gift (not expired, credits left) is left untouched.
|
||||||
|
|
||||||
|
Runnable: python3 tests/test_gift_lifecycle.py (from the repo root)
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
|
||||||
|
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
|
||||||
|
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
|
||||||
|
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok, detail=""):
|
||||||
|
results.append((name, bool(ok), detail))
|
||||||
|
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
|
||||||
|
|
||||||
|
|
||||||
|
class _NoNetwork:
|
||||||
|
"""Guard: ANY httpx client construction inside the test is a failure."""
|
||||||
|
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
def __call__(self, *a, **k): # pragma: no cover
|
||||||
|
raise AssertionError("live network attempted during fixture test")
|
||||||
|
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = _NoNetwork
|
||||||
|
|
||||||
|
# --- recorders -------------------------------------------------------------- #
|
||||||
|
calls = {"group": [], "budget": [], "pin": [], "email": [], "listmonk": [],
|
||||||
|
"loomio": 0, "matrix": 0, "revoke": [], "owui": [], "subscribe": []}
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_group(user_id, group_id=None):
|
||||||
|
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_budget(team_id, budget):
|
||||||
|
calls["budget"].append((team_id, round(float(budget), 2)))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_pin(team_id, reset_at):
|
||||||
|
calls["pin"].append((team_id, str(reset_at)))
|
||||||
|
|
||||||
|
|
||||||
|
def rec_email(to, subject, text_body, html_body=None):
|
||||||
|
calls["email"].append((to, subject))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_listmonk(email, subscribe):
|
||||||
|
calls["listmonk"].append((email, bool(subscribe)))
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_loomio():
|
||||||
|
calls["loomio"] += 1
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_matrix():
|
||||||
|
calls["matrix"] += 1
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_revoke(email):
|
||||||
|
calls["revoke"].append(email)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def rec_owui(uid):
|
||||||
|
calls["owui"].append(uid)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
CALL_KEYS = ("group", "budget", "pin", "email", "listmonk", "loomio", "matrix",
|
||||||
|
"revoke", "owui", "subscribe")
|
||||||
|
|
||||||
|
|
||||||
|
def reset_calls():
|
||||||
|
for k in CALL_KEYS:
|
||||||
|
calls[k] = 0 if k in ("loomio", "matrix") else []
|
||||||
|
|
||||||
|
|
||||||
|
TEAM_SPEND = {} # team_id -> cycle spend (default 0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def fake_team_db(team_id):
|
||||||
|
return {"max_budget": None, "spend": TEAM_SPEND.get(team_id, 0.0),
|
||||||
|
"budget_reset_at": None}
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_team_id(email):
|
||||||
|
return "team-" + email
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_get_or_create_team(email, budget, budget_duration="30d"):
|
||||||
|
return "team-fixture"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_create_key(email, budget, team_id):
|
||||||
|
return "sk-fixture-key"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_user_create(email, name):
|
||||||
|
return "uid-fixture"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_invite_link(user_id):
|
||||||
|
return "https://my.example/setupaccount.html?inviteToken=x"
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_activated(user_id):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
m.cloudron_set_group = rec_group
|
||||||
|
m.cloudron_set_active = rec_group # same signature (uid, bool); recorded nowhere critical
|
||||||
|
m.cloudron_create_user = fake_user_create
|
||||||
|
m.cloudron_get_invite_link = fake_invite_link
|
||||||
|
m.cloudron_is_activated = fake_activated
|
||||||
|
m.litellm_get_or_create_team = fake_get_or_create_team
|
||||||
|
m.litellm_create_key = fake_create_key
|
||||||
|
m.litellm_team_id_for_email = fake_team_id
|
||||||
|
m.litellm_update_team_budget = rec_budget
|
||||||
|
m.litellm_pin_reset_date = rec_pin
|
||||||
|
m.get_team_budget_from_db = fake_team_db
|
||||||
|
m.send_email = rec_email
|
||||||
|
m.listmonk_sync = rec_listmonk
|
||||||
|
m.sync_loomio_memberships = rec_loomio
|
||||||
|
m.sync_matrix_space = rec_matrix
|
||||||
|
m.revoke_member_litellm_access = rec_revoke
|
||||||
|
m.owui_add_to_members_group = rec_owui
|
||||||
|
|
||||||
|
|
||||||
|
def seed_member(conn, email, account_type="member", active=1, balance=None,
|
||||||
|
credits=None, anchor=None, expires=None, slug=""):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
|
||||||
|
"balance, credit_balance, account_type, anchor_day, gift_expires_at) "
|
||||||
|
"VALUES (?, 'enc', 'uid-' || ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
(email, email, slug, active,
|
||||||
|
balance if balance is not None else m.MEMBER_BUDGET,
|
||||||
|
credits if credits is not None else 0.0,
|
||||||
|
account_type, anchor, expires),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def row_of(conn, email, col):
|
||||||
|
return conn.execute(f"SELECT {col} FROM members WHERE email = ?", (email,)).fetchone()[0]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
m.get_db().close() # create + migrate the fixture schema
|
||||||
|
conn = m.get_db()
|
||||||
|
m._ensure_allowance_tables(conn) # anchor_day column (as production does)
|
||||||
|
conn.close()
|
||||||
|
inviter = "member-one@x.org"
|
||||||
|
|
||||||
|
# --- 1. inviter must be an active member -------------------------------
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_member(conn, inviter, active=1)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
conn = m.get_db()
|
||||||
|
check("guard: non-member inviter refused",
|
||||||
|
m.gift_provision_guard(conn, "stranger@x.org", "friend@x.org") is not None)
|
||||||
|
check("guard: active member inviter allowed",
|
||||||
|
m.gift_provision_guard(conn, inviter, "friend@x.org") is None)
|
||||||
|
# --- 2. one gift per inviter per 30 days -------------------------------
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO gifts (inviter_email, recipient_email, created_at, status) "
|
||||||
|
"VALUES (?, 'friend@x.org', datetime('now'), 'active')", (inviter,))
|
||||||
|
conn.commit()
|
||||||
|
refusal = m.gift_provision_guard(conn, inviter, "friend2@x.org")
|
||||||
|
check("guard: second gift within 30 days refused", refusal is not None and "30 days" in refusal,
|
||||||
|
str(refusal))
|
||||||
|
# backdate the ledger row: outside the window the inviter may gift again
|
||||||
|
conn.execute("UPDATE gifts SET created_at = datetime('now', '-31 days')")
|
||||||
|
check("guard: gift allowed again after the window",
|
||||||
|
m.gift_provision_guard(conn, inviter, "friend2@x.org") is None)
|
||||||
|
# --- 3. one gift per recipient ever ------------------------------------
|
||||||
|
conn.execute("UPDATE gifts SET recipient_email = 'friend2@x.org'")
|
||||||
|
conn.commit()
|
||||||
|
refusal = m.gift_provision_guard(conn, inviter, "friend2@x.org")
|
||||||
|
check("guard: recipient already in ledger refused", refusal is not None, str(refusal))
|
||||||
|
seed_member(conn, "existing@x.org", account_type="member", active=1)
|
||||||
|
conn.commit()
|
||||||
|
check("guard: existing member as recipient refused",
|
||||||
|
m.gift_provision_guard(conn, inviter, "existing@x.org") is not None)
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 4. the full gift pipeline (provision_gift_member) ------------------
|
||||||
|
reset_calls()
|
||||||
|
asyncio.run(m.provision_gift_member("gifted@x.org", "Gifted Friend", inviter))
|
||||||
|
conn = m.get_db()
|
||||||
|
check("provision: row marked gift", row_of(conn, "gifted@x.org", "account_type") == "gift")
|
||||||
|
check("provision: allowance balance 0", row_of(conn, "gifted@x.org", "balance") == 0.0)
|
||||||
|
check("provision: $5 credit", row_of(conn, "gifted@x.org", "credit_balance") == 5.0)
|
||||||
|
check("provision: gift_expires_at set", bool(row_of(conn, "gifted@x.org", "gift_expires_at")))
|
||||||
|
check("provision: group = guests group",
|
||||||
|
calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"]))
|
||||||
|
check("provision: cap set to 5.00 (one-time)",
|
||||||
|
(calls["budget"] and calls["budget"][0][1] == 5.0), str(calls["budget"]))
|
||||||
|
check("provision: welcome email sent",
|
||||||
|
any("gifted access" in s for _, s in calls["email"]), str(calls["email"]))
|
||||||
|
check("provision: newsletter subscribed",
|
||||||
|
("gifted@x.org", True) in calls["listmonk"], str(calls["listmonk"]))
|
||||||
|
check("provision: NO loomio/matrix calls", calls["loomio"] == 0 and calls["matrix"] == 0)
|
||||||
|
g = conn.execute("SELECT inviter_email, recipient_email, status FROM gifts "
|
||||||
|
"WHERE recipient_email = 'gifted@x.org'").fetchone()
|
||||||
|
check("provision: gifts ledger records inviter→recipient",
|
||||||
|
bool(g) and g[0] == inviter and g[1] == "gifted@x.org" and g[2] == "active", str(g))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 5. conversion (guest → member) -------------------------------------
|
||||||
|
reset_calls()
|
||||||
|
anchor_before = row_of(m.get_db(), "gifted@x.org", "anchor_day")
|
||||||
|
asyncio.run(m.convert_gift_to_member("gifted@x.org", "Gifted Friend", "giftedfriend"))
|
||||||
|
conn = m.get_db()
|
||||||
|
check("convert: account_type back to member",
|
||||||
|
row_of(conn, "gifted@x.org", "account_type") == "member")
|
||||||
|
check("convert: allowance lifted to MEMBER_BUDGET",
|
||||||
|
row_of(conn, "gifted@x.org", "balance") == m.MEMBER_BUDGET)
|
||||||
|
check("convert: unspent gift credit carried",
|
||||||
|
row_of(conn, "gifted@x.org", "credit_balance") == 5.0)
|
||||||
|
check("convert: group moved to members",
|
||||||
|
calls["group"] and calls["group"][0][1] == m.MEMBERS_GROUP_ID, str(calls["group"]))
|
||||||
|
check("convert: cap lifted to 20.00 (15 + 5 credits)",
|
||||||
|
(calls["budget"] and calls["budget"][0][1] == m.MEMBER_BUDGET + 5.0), str(calls["budget"]))
|
||||||
|
check("convert: anchor day kept", row_of(conn, "gifted@x.org", "anchor_day") == anchor_before)
|
||||||
|
check("convert: congrats email sent",
|
||||||
|
any("member now" in s for _, s in calls["email"]), str(calls["email"]))
|
||||||
|
check("convert: Loomio + Matrix syncs fired", calls["loomio"] == 1 and calls["matrix"] == 1)
|
||||||
|
check("convert: gifts ledger status converted",
|
||||||
|
conn.execute("SELECT status FROM gifts WHERE recipient_email='gifted@x.org'"
|
||||||
|
).fetchone()[0] == "converted")
|
||||||
|
check("convert: expiry cleared", row_of(conn, "gifted@x.org", "gift_expires_at") is None)
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
# --- 6/7/8. lifecycle sweep: expired / depleted / healthy ---------------
|
||||||
|
past = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
|
||||||
|
future = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat()
|
||||||
|
conn = m.get_db()
|
||||||
|
seed_member(conn, "expired@x.org", account_type="gift", active=1, balance=0.0,
|
||||||
|
credits=5.0, anchor=8, expires=past)
|
||||||
|
seed_member(conn, "healthy@x.org", account_type="gift", active=1, balance=0.0,
|
||||||
|
credits=5.0, anchor=8, expires=future)
|
||||||
|
seed_member(conn, "depleted@x.org", account_type="gift", active=1, balance=0.0,
|
||||||
|
credits=5.0, anchor=8, expires=future)
|
||||||
|
for e in ("expired@x.org", "healthy@x.org", "depleted@x.org"):
|
||||||
|
conn.execute("INSERT INTO gifts (inviter_email, recipient_email, gift_expires_at, status) "
|
||||||
|
"VALUES (?, ?, ?, 'active')", (inviter, e, future))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
TEAM_SPEND.clear() # healthy + expired have unspent credits
|
||||||
|
reset_calls()
|
||||||
|
out = asyncio.run(m.reconcile_gift_lifecycles())
|
||||||
|
conn = m.get_db()
|
||||||
|
check("lifecycle: expired gift deactivated by the sweep",
|
||||||
|
row_of(conn, "expired@x.org", "active") == 0)
|
||||||
|
check("lifecycle: expired gift group → inactive",
|
||||||
|
any(e == "uid-expired@x.org" and g == m.INACTIVE_GROUP_ID
|
||||||
|
for e, g in calls["group"]), str(calls["group"]))
|
||||||
|
check("lifecycle: expired gift budget zeroed (revoke path called)",
|
||||||
|
"expired@x.org" in calls["revoke"], str(calls["revoke"]))
|
||||||
|
check("lifecycle: expired gift unsubscribed",
|
||||||
|
("expired@x.org", False) in calls["listmonk"], str(calls["listmonk"]))
|
||||||
|
check("lifecycle: ledger status 'expired'",
|
||||||
|
conn.execute("SELECT status FROM gifts WHERE recipient_email='expired@x.org'"
|
||||||
|
).fetchone()[0] == "expired")
|
||||||
|
check("lifecycle: healthy gift untouched",
|
||||||
|
row_of(conn, "healthy@x.org", "active") == 1 and
|
||||||
|
not any(e == "uid-healthy@x.org" for e, _ in calls["group"]))
|
||||||
|
check("lifecycle: counts report expired=1 depleted=0",
|
||||||
|
out.get("expired") == 1 and out.get("depleted") == 0, str(out))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
TEAM_SPEND["team-depleted@x.org"] = 5.5 # depleted: spend reached the credits
|
||||||
|
reset_calls()
|
||||||
|
out = asyncio.run(m.reconcile_gift_lifecycles())
|
||||||
|
conn = m.get_db()
|
||||||
|
check("lifecycle: depleted gift deactivated",
|
||||||
|
row_of(conn, "depleted@x.org", "active") == 0)
|
||||||
|
check("lifecycle: depleted ledger status",
|
||||||
|
conn.execute("SELECT status FROM gifts WHERE recipient_email='depleted@x.org'"
|
||||||
|
).fetchone()[0] == "depleted")
|
||||||
|
check("lifecycle: healthy gift STILL untouched on second pass",
|
||||||
|
row_of(conn, "healthy@x.org", "active") == 1)
|
||||||
|
check("lifecycle: counts report depleted=1", out.get("depleted") == 1, str(out))
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
failed = [r for r in results if not r[1]]
|
||||||
|
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
Reference in new issue
Block a user