Rename gift to guest throughout: routes, ledger table, account_type values, env names, emails, tests

Pure rename, no behaviour change, matching the renamed panel and dashboard
builds. Includes one-time idempotent migrations for existing databases
(gifts->guests table, gift_expires_at->guest_expires_at column,
account_type 'gift'->'guest' values, gift_lapse_notices->guest_lapse_notices)
and four transitional alias routes (admin/provision-gift, admin/gift-convert,
broker/gift-status, broker/cancel-gift) so pre-rename dashboard/panel builds
keep working until they are redeployed.
This commit is contained in:
inference-bot committed 2026-11-08 02:41:05 +00:00
1 parent 8af8e39c0b
commit 27f9cc06b2
5 files changed
+493 -447

No files matched your search

@@ -1,13 +1,13 @@
#!/usr/bin/env python3
"""Gift-account SELF-CANCEL tests — structurally isolated from live services.
"""Guest-account SELF-CANCEL tests — structurally isolated from live services.
Same harness contract as test_gift_lifecycle.py: a FIXTURE database with the
Same harness contract as test_guest_lifecycle.py: a FIXTURE database with the
network layer REPLACED BY A RAISING GUARD, so any code path that tries to
reach Cloudron, LiteLLM, OC, Listmonk or SMTP outside the stubs fails the
test loudly instead of acting on live systems.
GUARD
1. A paying member can NEVER cancel through the gift path (403).
1. A paying member can NEVER cancel through the guest path (403).
2. An unknown identity is refused.
CANCEL (the full self-service flow)
3. The row deactivates (active=0) and the account is KEPT.
@@ -15,9 +15,9 @@ test loudly instead of acting on live systems.
5. The gateway budget is zeroed (revoke path called).
6. The newsletter unsubscribe fires.
7. The credit RETURN is written: a NEGATIVE ledger delta whose reason
names the cancellation and the original gift reference, deduped on
names the cancellation and the original guest reference, deduped on
its own reference; the member's credit_balance goes to 0.
8. The gifts ledger records inviter → recipient → 'cancelled by
8. The guests ledger records inviter → recipient → 'cancelled by
recipient' (rows appended, never rewritten).
IDEMPOTENCE
9. A second cancel is a NO-OP: no second ledger row, no re-deactivation
@@ -26,12 +26,12 @@ test loudly instead of acting on live systems.
10. A cancel whose return row already exists (deactivation failed
mid-way last time) reports the recorded amount and writes no second
ledger row.
ENDED-STATE READBACK (GET /broker/gift-status payload pieces)
11. The cancelled gift reports ended + cancelled + the returned amount;
a live gift reports active with its remaining credits; a member
ENDED-STATE READBACK (GET /broker/guest-status payload pieces)
11. The cancelled guest reports ended + cancelled + the returned amount;
a live guest reports active with its remaining credits; a member
reports guest: false.
Runnable: python3 tests/test_gift_cancel.py (from the repo root)
Runnable: python3 tests/test_guest_cancel.py (from the repo root)
"""
import asyncio
import base64
@@ -115,13 +115,13 @@ m.send_email = rec_email
def seed_gift(conn, email, active=1, credits=5.0, balance=0.0):
conn.execute(
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
"balance, credit_balance, account_type, gift_expires_at) "
"VALUES (?, 'enc', 'uid-' || ?, '', ?, ?, ?, 'gift', "
"balance, credit_balance, account_type, guest_expires_at) "
"VALUES (?, 'enc', 'uid-' || ?, '', ?, ?, ?, 'guest', "
"datetime('now', '+30 days'))",
(email, email, active, balance, credits),
)
conn.execute(
"INSERT INTO gifts (inviter_email, recipient_email, created_at, status) "
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
"VALUES ('member-one@x.org', ?, datetime('now'), 'active')", (email,)
)
@@ -147,55 +147,55 @@ def main():
# --- 1/2. the member guard ----------------------------------------------
try:
asyncio.run(m.cancel_gift_account("member-one@x.org"))
check("guard: paying member cannot cancel via the gift path", False, "no 403 raised")
asyncio.run(m.cancel_guest_account("member-one@x.org"))
check("guard: paying member cannot cancel via the guest path", False, "no 403 raised")
except m.HTTPException as e:
check("guard: paying member cannot cancel via the gift path", e.status_code == 403,
check("guard: paying member cannot cancel via the guest path", e.status_code == 403,
str(e.status_code))
try:
asyncio.run(m.cancel_gift_account("nobody@x.org"))
asyncio.run(m.cancel_guest_account("nobody@x.org"))
check("guard: unknown identity refused", False, "no 403 raised")
except m.HTTPException as e:
check("guard: unknown identity refused", e.status_code == 403, str(e.status_code))
# --- 3-8. the full cancel flow ------------------------------------------
conn = m.get_db()
seed_gift(conn, "gifted@x.org", active=1, credits=5.0)
seed_gift(conn, "invited@x.org", active=1, credits=5.0)
# the grant row production writes at provisioning (add_credits on the
# gift reference) — the return is audited against it
# guest reference) — the return is audited against it
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference) "
"VALUES ('gifted@x.org', 5.0, 'gift account — $5 credit from a member', "
"'gift:gifted@x.org')")
"VALUES ('invited@x.org', 5.0, 'guest account — $5 credit from a member', "
"'guest:invited@x.org')")
conn.commit()
conn.close()
out = asyncio.run(m.cancel_gift_account("gifted@x.org"))
out = asyncio.run(m.cancel_guest_account("invited@x.org"))
conn = m.get_db()
row = conn.execute("SELECT active, account_type, credit_balance FROM members "
"WHERE email = 'gifted@x.org'").fetchone()
"WHERE email = 'invited@x.org'").fetchone()
check("cancel: row deactivated, account kept",
row[0] == 0 and row[1] == "gift", str(row))
row[0] == 0 and row[1] == "guest", str(row))
check("cancel: credit balance drawn to 0", row[2] == 0.0, str(row))
check("cancel: group moved guests → ended-guests",
any(u == "uid-gifted@x.org" and g == m.GUESTS_ENDED_GROUP_ID
any(u == "uid-invited@x.org" and g == m.GUESTS_ENDED_GROUP_ID
for u, g in calls["group"]), str(calls["group"]))
check("cancel: gateway budget zeroed (revoke called)",
"gifted@x.org" in calls["revoke"], str(calls["revoke"]))
"invited@x.org" in calls["revoke"], str(calls["revoke"]))
check("cancel: newsletter unsubscribed",
("gifted@x.org", False) in calls["listmonk"], str(calls["listmonk"]))
led = ledger_rows(conn, "gifted@x.org")
grants = [r for r in led if r[2] == "gift:gifted@x.org"]
returns = [r for r in led if r[2] == "gift-return:gifted@x.org"]
("invited@x.org", False) in calls["listmonk"], str(calls["listmonk"]))
led = ledger_rows(conn, "invited@x.org")
grants = [r for r in led if r[2] == "guest:invited@x.org"]
returns = [r for r in led if r[2] == "guest-return:invited@x.org"]
check("cancel: ledger holds the $5 grant and ONE negative return row",
len(grants) == 1 and grants[0][0] == 5.0 and len(returns) == 1
and returns[0][0] == -5.0, str(led))
check("cancel: return reason names the cancellation and the gift reference",
check("cancel: return reason names the cancellation and the guest reference",
len(returns) == 1 and "cancelled by recipient" in returns[0][1]
and "gift:gifted@x.org" in returns[0][1], str(returns))
g = conn.execute("SELECT inviter_email, recipient_email, status FROM gifts "
"WHERE recipient_email = 'gifted@x.org'").fetchone()
check("cancel: gifts ledger shows inviter → recipient → cancelled by recipient",
g and g[0] == "member-one@x.org" and g[1] == "gifted@x.org"
and "guest:invited@x.org" in returns[0][1], str(returns))
g = conn.execute("SELECT inviter_email, recipient_email, status FROM guests "
"WHERE recipient_email = 'invited@x.org'").fetchone()
check("cancel: guests ledger shows inviter → recipient → cancelled by recipient",
g and g[0] == "member-one@x.org" and g[1] == "invited@x.org"
and g[2] == "cancelled by recipient", str(g))
check("cancel: result reports the returned amount",
out.get("status") == "cancelled" and out.get("credits_returned") == 5.0, str(out))
@@ -203,14 +203,14 @@ def main():
# --- 9. idempotence: the second cancel is a no-op -----------------------
calls["group"].clear(); calls["revoke"].clear(); calls["listmonk"].clear()
out2 = asyncio.run(m.cancel_gift_account("gifted@x.org"))
out2 = asyncio.run(m.cancel_guest_account("invited@x.org"))
conn = m.get_db()
led2 = ledger_rows(conn, "gifted@x.org")
led2 = ledger_rows(conn, "invited@x.org")
check("idempotent: second cancel reports already_ended",
out2.get("status") == "already_ended"
and out2.get("gift_status") == "cancelled by recipient", str(out2))
and out2.get("guest_status") == "cancelled by recipient", str(out2))
check("idempotent: no second return row",
len([r for r in led2 if r[2] == "gift-return:gifted@x.org"]) == 1, str(led2))
len([r for r in led2 if r[2] == "guest-return:invited@x.org"]) == 1, str(led2))
check("idempotent: no re-deactivation side effects",
not calls["group"] and not calls["revoke"] and not calls["listmonk"],
str(calls))
@@ -222,23 +222,23 @@ def main():
# simulate the ledger row written before a crash: return recorded, row still active
conn.execute("UPDATE members SET credit_balance = 0.0 WHERE email = 'halfway@x.org'")
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference) "
"VALUES ('halfway@x.org', -4.0, 'gift cancelled by recipient — "
"unspent credit returned to the co-op (original gift: "
"gift:halfway@x.org)', 'gift-return:halfway@x.org')")
"VALUES ('halfway@x.org', -4.0, 'guest cancelled by recipient — "
"unspent credit returned to the co-op (original guest: "
"guest:halfway@x.org)', 'guest-return:halfway@x.org')")
conn.commit()
conn.close()
out3 = asyncio.run(m.cancel_gift_account("halfway@x.org"))
out3 = asyncio.run(m.cancel_guest_account("halfway@x.org"))
conn = m.get_db()
led3 = ledger_rows(conn, "halfway@x.org")
check("replay: the recorded return is reported, not re-written",
len([r for r in led3 if r[2] == "gift-return:halfway@x.org"]) == 1
len([r for r in led3 if r[2] == "guest-return:halfway@x.org"]) == 1
and out3.get("credits_returned") == 4.0, str(led3) + " / " + str(out3))
check("replay: deactivation still completed",
conn.execute("SELECT active FROM members WHERE email='halfway@x.org'"
).fetchone()[0] == 0)
conn.close()
# --- 11. the gift-status payload pieces ---------------------------------
# --- 11. the guest-status payload pieces ---------------------------------
# member: guest false
conn = m.get_db()
ok_member = conn.execute("SELECT 1 FROM members WHERE email='member-one@x.org'").fetchone()
@@ -250,29 +250,29 @@ def main():
"WHERE email = 'member-one@x.org'").fetchone()
conn.close()
check("status: a member is not a guest (payload contract)",
not m.is_gift_account("member-one@x.org"))
not m.is_guest_account("member-one@x.org"))
# cancelled gift: ended + cancelled + returned amount
# cancelled guest: ended + cancelled + returned amount
st_cancelled = {
"ended": True, "gift_status": m._gift_ledger_status("gifted@x.org"),
"cancelled": m._gift_ledger_status("gifted@x.org") == "cancelled by recipient",
"credits_returned": m._gift_returned_credits("gifted@x.org"),
"ended": True, "guest_status": m._guest_ledger_status("invited@x.org"),
"cancelled": m._guest_ledger_status("invited@x.org") == "cancelled by recipient",
"credits_returned": m._guest_returned_credits("invited@x.org"),
}
check("status: cancelled gift reads ended + cancelled + amount returned",
check("status: cancelled guest reads ended + cancelled + amount returned",
st_cancelled["ended"] and st_cancelled["cancelled"]
and st_cancelled["credits_returned"] == 5.0, str(st_cancelled))
# live gift: active with remaining credits
# live guest: active with remaining credits
conn = m.get_db()
seed_gift(conn, "live@x.org", active=1, credits=5.0)
conn.commit()
conn.close()
st_live = {
"active": bool(conn_active := 1),
"gift_status": m._gift_ledger_status("live@x.org"),
"guest_status": m._guest_ledger_status("live@x.org"),
}
check("status: live gift reads active with an 'active' ledger row",
st_live["active"] and st_live["gift_status"] == "active", str(st_live))
check("status: live guest reads active with an 'active' ledger row",
st_live["active"] and st_live["guest_status"] == "active", str(st_live))
failed = [r for r in results if not r[1]]
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
@@ -1,37 +1,37 @@
#!/usr/bin/env python3
"""Gift-account lifecycle tests — structurally isolated from live services.
"""Guest-account lifecycle tests — structurally isolated from live services.
WHY THIS EXISTS
Gift accounts (operator feature, 2026-11-08) touch money ($5 of credits),
Guest 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)
GUARDS (abuse protection — one guest 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
2. A SECOND guest by the same inviter within the window is refused.
3. A recipient who already received a guest (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.
4. The full guest pipeline marks the row (account_type='guest', balance 0,
credit_balance 5, guest_expires_at set, anchor day kept), records
inviter → recipient in the guests ledger, subscribes the newsletter,
and sends the guest 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
unspent guest 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.
guests-ledger row becomes 'converted'; Loomio + Matrix syncs fire.
LIFECYCLE (sweep pass)
6. An EXPIRED gift (past gift_expires_at, credits remaining) is
6. An EXPIRED guest (past guest_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,
7. A DEPLETED guest (spend reached the credits) is deactivated likewise,
status 'depleted'.
8. A healthy gift (not expired, credits left) is left untouched.
8. A healthy guest (not expired, credits left) is left untouched.
Runnable: python3 tests/test_gift_lifecycle.py (from the repo root)
Runnable: python3 tests/test_guest_lifecycle.py (from the repo root)
"""
import asyncio
import base64
@@ -178,7 +178,7 @@ 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) "
"balance, credit_balance, account_type, anchor_day, guest_expires_at) "
"VALUES (?, 'enc', 'uid-' || ?, ?, ?, ?, ?, ?, ?, ?)",
(email, email, slug, active,
balance if balance is not None else m.MEMBER_BUDGET,
@@ -205,40 +205,40 @@ def main():
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)
m.guest_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 -------------------------------
m.guest_provision_guard(conn, inviter, "friend@x.org") is None)
# --- 2. one guest per inviter per 30 days -------------------------------
conn.execute(
"INSERT INTO gifts (inviter_email, recipient_email, created_at, status) "
"INSERT INTO guests (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,
refusal = m.guest_provision_guard(conn, inviter, "friend2@x.org")
check("guard: second guest 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'")
# backdate the ledger row: outside the window the inviter may guest again
conn.execute("UPDATE guests SET created_at = datetime('now', '-31 days')")
check("guard: guest allowed again after the window",
m.guest_provision_guard(conn, inviter, "friend2@x.org") is None)
# --- 3. one guest per recipient ever ------------------------------------
conn.execute("UPDATE guests SET recipient_email = 'friend2@x.org'")
conn.commit()
refusal = m.gift_provision_guard(conn, inviter, "friend2@x.org")
refusal = m.guest_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)
m.guest_provision_guard(conn, inviter, "existing@x.org") is not None)
conn.close()
# --- 4. the full gift pipeline (provision_gift_member) ------------------
# --- 4. the full guest pipeline (provision_guest_member) ------------------
reset_calls()
asyncio.run(m.provision_gift_member("gifted@x.org", "Gifted Friend", inviter))
asyncio.run(m.provision_guest_member("invited@x.org", "Invited 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: row marked guest", row_of(conn, "invited@x.org", "account_type") == "guest")
check("provision: allowance balance 0", row_of(conn, "invited@x.org", "balance") == 0.0)
check("provision: $5 credit", row_of(conn, "invited@x.org", "credit_balance") == 5.0)
check("provision: guest_expires_at set", bool(row_of(conn, "invited@x.org", "guest_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)",
@@ -246,77 +246,77 @@ def main():
check("provision: invitation email sent (merged invite + welcome)",
any("invited to the Inference Cooperative" in s for _, s in calls["email"]), str(calls["email"]))
check("provision: newsletter subscribed",
("gifted@x.org", True) in calls["listmonk"], str(calls["listmonk"]))
("invited@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))
g = conn.execute("SELECT inviter_email, recipient_email, status FROM guests "
"WHERE recipient_email = 'invited@x.org'").fetchone()
check("provision: guests ledger records inviter→recipient",
bool(g) and g[0] == inviter and g[1] == "invited@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"))
anchor_before = row_of(m.get_db(), "invited@x.org", "anchor_day")
asyncio.run(m.convert_guest_to_member("invited@x.org", "Invited Friend", "invitedfriend"))
conn = m.get_db()
check("convert: account_type back to member",
row_of(conn, "gifted@x.org", "account_type") == "member")
row_of(conn, "invited@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)
row_of(conn, "invited@x.org", "balance") == m.MEMBER_BUDGET)
check("convert: unspent guest credit carried",
row_of(conn, "invited@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: anchor day kept", row_of(conn, "invited@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'"
check("convert: guests ledger status converted",
conn.execute("SELECT status FROM guests WHERE recipient_email='invited@x.org'"
).fetchone()[0] == "converted")
check("convert: expiry cleared", row_of(conn, "gifted@x.org", "gift_expires_at") is None)
check("convert: expiry cleared", row_of(conn, "invited@x.org", "guest_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,
seed_member(conn, "expired@x.org", account_type="guest", 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,
seed_member(conn, "healthy@x.org", account_type="guest", 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,
seed_member(conn, "depleted@x.org", account_type="guest", active=1, balance=0.0,
credits=5.0, anchor=8, expires=future)
# A guest whose gift ended BEFORE the reaching-limits email shipped: the
# A guest whose guest ended BEFORE the reaching-limits email shipped: the
# sweep's catch-up pass must tell them exactly once.
seed_member(conn, "already-gone@x.org", account_type="gift", active=0, balance=0.0,
seed_member(conn, "already-gone@x.org", account_type="guest", active=0, balance=0.0,
credits=5.0, anchor=8, expires=past)
for e in ("expired@x.org", "healthy@x.org", "depleted@x.org", "already-gone@x.org"):
conn.execute("INSERT INTO gifts (inviter_email, recipient_email, gift_expires_at, status) "
conn.execute("INSERT INTO guests (inviter_email, recipient_email, guest_expires_at, status) "
"VALUES (?, ?, ?, 'active')", (inviter, e, future))
conn.execute("UPDATE gifts SET status = 'expired' WHERE recipient_email = 'already-gone@x.org'")
conn.execute("UPDATE guests SET status = 'expired' WHERE recipient_email = 'already-gone@x.org'")
conn.commit()
conn.close()
TEAM_SPEND.clear() # healthy + expired have unspent credits
reset_calls()
out = asyncio.run(m.reconcile_gift_lifecycles())
out = asyncio.run(m.reconcile_guest_lifecycles())
conn = m.get_db()
check("lifecycle: expired gift deactivated by the sweep",
check("lifecycle: expired guest deactivated by the sweep",
row_of(conn, "expired@x.org", "active") == 0)
check("lifecycle: expired gift group → inactive",
check("lifecycle: expired guest 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)",
check("lifecycle: expired guest budget zeroed (revoke path called)",
"expired@x.org" in calls["revoke"], str(calls["revoke"]))
check("lifecycle: expired gift unsubscribed",
check("lifecycle: expired guest 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'"
conn.execute("SELECT status FROM guests WHERE recipient_email='expired@x.org'"
).fetchone()[0] == "expired")
check("lifecycle: healthy gift untouched",
check("lifecycle: healthy guest 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",
@@ -335,14 +335,14 @@ def main():
TEAM_SPEND["team-depleted@x.org"] = 5.5 # depleted: spend reached the credits
reset_calls()
out = asyncio.run(m.reconcile_gift_lifecycles())
out = asyncio.run(m.reconcile_guest_lifecycles())
conn = m.get_db()
check("lifecycle: depleted gift deactivated",
check("lifecycle: depleted guest 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'"
conn.execute("SELECT status FROM guests WHERE recipient_email='depleted@x.org'"
).fetchone()[0] == "depleted")
check("lifecycle: healthy gift STILL untouched on second pass",
check("lifecycle: healthy guest 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))
check("lifecycle: depleted guest also told once",
@@ -351,8 +351,8 @@ def main():
str(calls["email"]))
check("lifecycle: ONCE per guest — second sweep sent no repeat notices",
sum(1 for to, s in calls["email"] if "guest access has ended" in s) == 1
and m.gift_lapse_notice_sent("expired@x.org")
and m.gift_lapse_notice_sent("already-gone@x.org"),
and m.guest_lapse_notice_sent("expired@x.org")
and m.guest_lapse_notice_sent("already-gone@x.org"),
str(calls["email"]))
check("lifecycle: healthy guest never emailed",
not any(to == "healthy@x.org" for to, _ in calls["email"]), str(calls["email"]))