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:
inference-bot committed 2026-11-08 02:05:37 +00:00
1 parent 73d8c61aa7
commit 6d9074eefe
4 files changed
+1159 -32

No files matched your search

+340
View File
@@ -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())