From 27f9cc06b2ef5f50b97cf017a5d96521928fb2c0 Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Sun, 8 Nov 2026 02:40:51 +0000 Subject: [PATCH] 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. --- README.md | 60 +- app/main.py | 624 ++++++++++-------- metrics_snapshot.py | 4 +- ...st_gift_cancel.py => test_guest_cancel.py} | 110 +-- ...t_lifecycle.py => test_guest_lifecycle.py} | 142 ++-- 5 files changed, 493 insertions(+), 447 deletions(-) rename tests/{test_gift_cancel.py => test_guest_cancel.py} (70%) rename tests/{test_gift_lifecycle.py => test_guest_lifecycle.py} (68%) diff --git a/README.md b/README.md index 29a4ecc..9387ba5 100644 --- a/README.md +++ b/README.md @@ -50,64 +50,64 @@ 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_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`). | -| `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. | +| `GUEST_BUDGET` | Guest-account credit in USD (default `5.0`). | +| `GUEST_DAYS` | Guest-account time box in days from provisioning (default `60`). The sweep deactivates an expired guest even with credits left. | +| `GUEST_PER_INVITER_DAYS` | Rolling window for the one-guest-per-inviter limit (default `30`). | +| `GUESTS_GROUP_ID` | Cloudron group ID for guest accounts. The chat and dashboard apps' access restrictions list BOTH the members and guests groups, so a guest reaches exactly those two apps. | | `GUESTS_ENDED_GROUP_ID` | Cloudron group a SELF-CANCELLED guest's user lands in: out of guests (chat access ends) but still admitted by the dashboard app, so the ended state and Become-a-member stay visible. Unset → the shared inactive group (dashboard access ends too). | -## Gift accounts +## Guest 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": ""}` 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 +Collective membership required. `POST /admin/provision-guest` (X-Admin-Token) +with `{"email", "name", "inviter": ""}` runs the +guest pipeline: Cloudron user in the **guests** group, a LiteLLM team capped at +`GUEST_BUDGET` with **no monthly reset** (the cap is the guest's whole life), the +portal row marked `account_type='guest'` with the $5 held as non-expiring +credit, `guest_expires_at` set to now + `GUEST_DAYS`, the guest 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 +**guests ledger** row (`guests` table: inviter → recipient, expiry, status) for +the abuse audit. Guards: one guest per inviter per `GUEST_PER_INVITER_DAYS`; one +guest 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. +**Sweep safety.** `reconcile_memberships()` never deactivates a guest for +lacking an OC contribution. A guest lapses only by its own rules, handled by +`reconcile_guest_lifecycles()` inside the sweep: credits spent out (LiteLLM's +cap enforces the limit; the sweep retires the row) or the `GUEST_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. -**Self-service cancellation (recipient-initiated).** `POST /broker/cancel-gift` -(dashboard broker identity) ends a gift at the recipient's own request: -deactivation with the same kept-account semantics, the newsletter +**Self-service cancellation (recipient-initiated).** `POST /broker/cancel-guest` +(dashboard broker identity) ends a guest account at the recipient's own +request: deactivation with the same kept-account semantics, the newsletter unsubscribed, and — the part a lapse does not do — any UNSPENT credit returned to the co-op as a negative `credit_ledger` row whose reason names -the cancellation and the original gift reference (`gift-return:` is +the cancellation and the original guest reference (`guest-return:` is the dedupe reference, so a repeat cancel can never double-return). The -gifts-ledger row records the full trail: inviter → recipient → 'cancelled +guests-ledger row records the full trail: inviter → recipient → 'cancelled by recipient'. The Cloudron user leaves the guests group for `GUESTS_ENDED_GROUP_ID` — chat and API access end, while the dashboard app (which lists that group in its access restriction) still admits them, so -`GET /broker/gift-status` can show the ended state: access ended, data +`GET /broker/guest-status` can show the ended state: access ended, data kept, Become-a-member still one contribution away. A paying member calling either route gets a 403 — cancelling a membership means ending the Open -Collective contribution, and this endpoint is deliberately gift-only. +Collective contribution, and this endpoint is deliberately guest-only. -**Guest → member conversion (automatic).** When a gift's OC identity appears as +**Guest → member conversion (automatic).** When a guest'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 +`convert_guest_to_member()`: the Cloudron user moves guests → members, the +LiteLLM cap lifts to the member allowance + credits (unspent guest 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 +member with the standard `MEMBER_BUDGET`, the anchor day (the guest'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": "", "oc_email": "", "oc_email": ""}` — the row records `members.oc_email`, and the sweep and webhook treat that address as an additional matcher from then on. diff --git a/app/main.py b/app/main.py index 2e4e511..2f87a91 100644 --- a/app/main.py +++ b/app/main.py @@ -335,24 +335,24 @@ OC_PERSONAL_TOKEN = os.environ.get("OC_PERSONAL_TOKEN", "") # regardless of their $10/15/20 contribution. Governance decision (Loomio). MEMBER_BUDGET = float(os.environ.get("MEMBER_BUDGET", "15.0")) -# --- Gift accounts (operator decisions, 2026-11-08) -------------------------- # +# --- Guest accounts (operator decisions, 2026-11-08) -------------------------- # # A member can give a friend access to the co-op with $5 of credits, no Open -# Collective membership required. The gift is a ONE-TIME non-expiring credit +# Collective membership required. The guest is a ONE-TIME non-expiring credit # balance held in the credits model (credit_balance), hard-capped by the # LiteLLM team budget. Two lapse triggers, both handled by the sweep: # * the $5 is spent (the cap enforces the limit; the sweep deactivates the # row once spend reaches the credit balance), and -# * GIFT_DAYS elapse from provisioning — a time box, even with credits left. +# * GUEST_DAYS elapse from provisioning — a time box, even with credits left. # Deactivation is the same semantics as a member's: guests group → inactive, # team budget zeroed, row active=0, newsletter unsubscribed. The account is # KEPT so a returning payer resumes cleanly (and the guest→member conversion # still fires if their OC membership appears later). -GIFT_BUDGET = float(os.environ.get("GIFT_BUDGET", "5.0")) -GIFT_DAYS = float(os.environ.get("GIFT_DAYS", "60")) -# One gift per inviting member per rolling 30 days (abuse protection). -GIFT_PER_INVITER_DAYS = float(os.environ.get("GIFT_PER_INVITER_DAYS", "30")) +GUEST_BUDGET = float(os.environ.get("GUEST_BUDGET", "5.0")) +GUEST_DAYS = float(os.environ.get("GUEST_DAYS", "60")) +# One guest per inviting member per rolling 30 days (abuse protection). +GUEST_PER_INVITER_DAYS = float(os.environ.get("GUEST_PER_INVITER_DAYS", "30")) -# The Cloudron "guests" group: gift accounts land here. The chat and dashboard +# The Cloudron "guests" group: guest accounts land here. The chat and dashboard # apps' access restrictions list BOTH members and guests, so a guest reaches # exactly those two apps — nothing else is granted by group membership. GUESTS_GROUP_ID = os.environ.get("GUESTS_GROUP_ID", "") @@ -911,36 +911,52 @@ def get_db() -> sqlite3.Connection: # invited) can never be sent a Loomio invite a second time. if "loomio_invited_at" not in cols: conn.execute("ALTER TABLE members ADD COLUMN loomio_invited_at TEXT") - # Migration: account_type — 'member' (default) or 'gift'. Gift accounts are - # provisioned by /admin/provision-gift with $5 of non-expiring credit, live + # Migration: account_type — 'member' (default) or 'guest'. Guest accounts are + # provisioned by /admin/provision-guest with $5 of non-expiring credit, live # in the Cloudron "guests" group, and sit outside every membership # obligation: the sweep never deactivates one for lacking an OC # contribution, they are invited to no Loomio/Matrix rooms, and they lapse - # only by their own rules (credit exhausted, or the GIFT_DAYS time box). + # only by their own rules (credit exhausted, or the GUEST_DAYS time box). if "account_type" not in cols: conn.execute("ALTER TABLE members ADD COLUMN account_type TEXT DEFAULT 'member'") # Migration: oc_email — the Open Collective email a member's contribution # arrives under when it differs from their account email (set via - # POST /admin/gift-convert when a gifted friend joins under another + # POST /admin/guest-convert when a invited friend joins under another # address). The sweep and the webhook treat it as an additional matcher so # renewals under that address keep the account active. if "oc_email" not in cols: conn.execute("ALTER TABLE members ADD COLUMN oc_email TEXT") - # Migration: gift_expires_at — when a gift account's GIFT_DAYS time box - # elapses (set at gift provisioning). The sweep deactivates the account + # Migration: guest naming (2026-11-08). The ledger table, the members + # expiry column, the lapse-notice table and the account_type VALUES all + # carried 'gift' before the feature was renamed to guest access. Every + # database that predates the rename moves once, here — idempotent, and a + # no-op on any database created after it. Runs BEFORE the + # guest_expires_at ADD COLUMN below so an old database renames its + # populated column instead of gaining an empty twin. + _tables = [r[0] for r in conn.execute( + "SELECT name FROM sqlite_master WHERE type='table'").fetchall()] + if "gifts" in _tables and "guests" not in _tables: + conn.execute("ALTER TABLE gifts RENAME TO guests") + if "gift_lapse_notices" in _tables and "guest_lapse_notices" not in _tables: + conn.execute("ALTER TABLE gift_lapse_notices RENAME TO guest_lapse_notices") + if "gift_expires_at" in cols and "guest_expires_at" not in cols: + conn.execute("ALTER TABLE members RENAME COLUMN gift_expires_at TO guest_expires_at") + conn.execute("UPDATE members SET account_type = 'guest' WHERE account_type = 'gift'") + # Migration: guest_expires_at — when a guest account's GUEST_DAYS time box + # elapses (set at guest provisioning). The sweep deactivates the account # after this instant even if credits remain. - if "gift_expires_at" not in cols: - conn.execute("ALTER TABLE members ADD COLUMN gift_expires_at TEXT") - # Gifts ledger — the abuse-protection audit trail: WHO invited WHOM, when, - # and what became of the gift. One row per gift ever sent. + if "guest_expires_at" not in cols: + conn.execute("ALTER TABLE members ADD COLUMN guest_expires_at TEXT") + # Guests ledger — the abuse-protection audit trail: WHO invited WHOM, when, + # and what became of the guest. One row per guest ever sent. conn.execute( - "CREATE TABLE IF NOT EXISTS gifts (" + "CREATE TABLE IF NOT EXISTS guests (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "inviter_email TEXT NOT NULL, " "recipient_email TEXT NOT NULL, " "oc_reference TEXT, " "created_at TEXT DEFAULT (datetime('now')), " - "gift_expires_at TEXT, " + "guest_expires_at TEXT, " "status TEXT DEFAULT 'active')" ) # Credit ledger: audit trail for every credit movement (purchases via the @@ -1058,7 +1074,7 @@ def get_credit_balance(email: str) -> float: def get_member_account_type(email: str) -> str: - """Return the row's account type: 'member' (default) or 'gift'.""" + """Return the row's account type: 'member' (default) or 'guest'.""" conn = get_db() row = conn.execute( "SELECT account_type FROM members WHERE email = ?", (email,) @@ -1067,22 +1083,22 @@ def get_member_account_type(email: str) -> str: return (row[0] or "member") if row else "member" -def is_gift_account(email: str) -> bool: - """True when the row is a gift account (operator gifting feature).""" - return get_member_account_type(email) == "gift" +def is_guest_account(email: str) -> bool: + """True when the row is a guest account (operator guest access feature).""" + return get_member_account_type(email) == "guest" -def gift_provision_guard(conn, inviter_email: str, recipient_email: str) -> str | None: - """Decide whether a gift may be sent (pure — runs on any connection). +def guest_provision_guard(conn, inviter_email: str, recipient_email: str) -> str | None: + """Decide whether a guest may be sent (pure — runs on any connection). Abuse-protection rules (operator decision, 2026-11-08): * the inviter must be an ACTIVE member row (account_type 'member'); - * one gift per inviter per rolling GIFT_PER_INVITER_DAYS (default 30 days); - * one gift per recipient EVER — any prior gifts-ledger row for the + * one guest per inviter per rolling GUEST_PER_INVITER_DAYS (default 30 days); + * one guest per recipient EVER — any prior guests-ledger row for the recipient refuses, as does an existing portal row under that email - (they already have/had a gift account or are a member). + (they already have/had a guest account or are a member). - Returns None when the gift may proceed, else a human-readable refusal. + Returns None when the guest may proceed, else a human-readable refusal. """ inviter = (inviter_email or "").strip().lower() recipient = (recipient_email or "").strip().lower() @@ -1091,32 +1107,32 @@ def gift_provision_guard(conn, inviter_email: str, recipient_email: str) -> str if not recipient or "@" not in recipient: return "A valid recipient email is required" if inviter == recipient: - return "You cannot gift the account you are gifting from" + return "You cannot guest the account you are guest access from" row = conn.execute( "SELECT active, account_type FROM members WHERE email = ?", (inviter,) ).fetchone() - if not row or not row[0] or (row[1] or "member") == "gift": + if not row or not row[0] or (row[1] or "member") == "guest": return f"Inviter {inviter} is not an active member account" recent = conn.execute( - "SELECT COUNT(*) FROM gifts WHERE inviter_email = ? AND " + "SELECT COUNT(*) FROM guests WHERE inviter_email = ? AND " "created_at >= datetime('now', ?)", - (inviter, f"-{int(GIFT_PER_INVITER_DAYS)} days"), + (inviter, f"-{int(GUEST_PER_INVITER_DAYS)} days"), ).fetchone()[0] if recent: - return (f"{inviter} already sent a gift in the last " - f"{int(GIFT_PER_INVITER_DAYS)} days — one gift per member per month") + return (f"{inviter} already sent a guest in the last " + f"{int(GUEST_PER_INVITER_DAYS)} days — one guest per member per month") ever = conn.execute( - "SELECT COUNT(*) FROM gifts WHERE recipient_email = ?", (recipient,) + "SELECT COUNT(*) FROM guests WHERE recipient_email = ?", (recipient,) ).fetchone()[0] if ever: - return f"{recipient} has already received a gift account" + return f"{recipient} has already received a guest account" existing = conn.execute( "SELECT account_type FROM members WHERE email = ?", (recipient,) ).fetchone() if existing: acct = existing[0] or "member" - return (f"{recipient} already has a portal row ({acct}) — gifts are for " - "new addresses; existing members and past gift accounts are refused") + return (f"{recipient} already has a portal row ({acct}) — guests are for " + "new addresses; existing members and past guest accounts are refused") return None @@ -1463,7 +1479,7 @@ async def get_active_member_emails() -> list[str]: The local `members` table is the authoritative source of member emails (populated during provisioning). Used for the Loomio sync and the Matrix - invite pass. GIFT accounts are excluded: they are not members — they hold + invite pass. GUEST accounts are excluded: they are not members — they hold $5 credits, live in the Cloudron guests group, and must never be invited to Loomio, Matrix or (via these lists) any member service. """ @@ -1472,7 +1488,7 @@ async def get_active_member_emails() -> list[str]: "SELECT email, account_type FROM members WHERE active = 1" ).fetchall() conn.close() - return [r[0] for r in rows if (r[1] or "member") != "gift"] + return [r[0] for r in rows if (r[1] or "member") != "guest"] def get_loomio_invited_at(email: str) -> str | None: @@ -2020,14 +2036,14 @@ def store_member(email: str, key_token: str, cloudron_user_id: str, slug: str = if row and row[0]: slug = row[0] # account_type: None (every normal path) preserves whatever the row holds — - # re-provisioning a gift via the member pipeline must not un-gift it. Only - # an explicit value (provision_gift_member passes 'gift') writes the column. + # re-provisioning a guest via the member pipeline must not un-guest it. Only + # an explicit value (provision_guest_member passes 'guest') writes the column. conn.execute( "INSERT INTO members (email, key_token, cloudron_user_id, slug, active, account_type) " "VALUES (?, ?, ?, ?, 1, COALESCE(?, 'member')) " "ON CONFLICT(email) DO UPDATE SET key_token=excluded.key_token, " "cloudron_user_id=excluded.cloudron_user_id, slug=excluded.slug, active=1, " - "account_type=CASE WHEN excluded.account_type='gift' THEN 'gift' " + "account_type=CASE WHEN excluded.account_type='guest' THEN 'guest' " "ELSE COALESCE(members.account_type, 'member') END", (email, encrypt_key(key_token), cloudron_user_id, slug, account_type), ) @@ -2354,13 +2370,13 @@ async def provision_member(email: str, name: str, slug: str = "") -> str: fail). Re-sending this way also re-sends the welcome email, so it doubles as the manual "re-invite" path. - GIFT accounts: every provisioning entry point (webhook, sweep, - /admin/provision) funnels through here. When a gift's OC identity appears + GUEST accounts: every provisioning entry point (webhook, sweep, + /admin/provision) funnels through here. When a guest's OC identity appears as a live backer, this call CONVERTS the account instead of provisioning — the automatic guest→member transition. """ - if is_gift_account(email): - return await convert_gift_to_member(email, name, slug) + if is_guest_account(email): + return await convert_guest_to_member(email, name, slug) user_id = await cloudron_create_user(email, name) await cloudron_set_group(user_id) await cloudron_set_active(user_id, True) @@ -2413,18 +2429,18 @@ async def provision_member(email: str, name: str, slug: str = "") -> str: return user_id -# --- Gift accounts (operator feature, 2026-11-08) --------------------------- # +# --- Guest accounts (operator feature, 2026-11-08) --------------------------- # # A member gives a friend access with $5 of credits: Cloudron user in the # guests group (chat + dashboard only), a one-time LiteLLM budget with NO -# monthly reset, the portal row marked account_type='gift', the gift welcome +# monthly reset, the portal row marked account_type='guest', the guest welcome # email, and the newsletter subscription. NO Loomio/Matrix invites. See the -# constants block for the lapse rules (credit exhaustion + GIFT_DAYS time box). +# constants block for the lapse rules (credit exhaustion + GUEST_DAYS time box). -def gift_invitation_email(name: str, setup_url: str, inviter_name: str = "") -> tuple[str, str, str]: - """Build the gift INVITATION email — the one email a gift sends. +def guest_invitation_email(name: str, setup_url: str, inviter_name: str = "") -> tuple[str, str, str]: + """Build the guest INVITATION email — the one email a guest sends. - This is the gift-time email AND the guest welcome in one: the recipient is - invited in (the inviter named), told what the gift gives ($5 of credits, + This is the guest-time email AND the guest welcome in one: the recipient is + invited in (the inviter named), told what the guest gives ($5 of credits, how long access runs), and given the account-setup link. The guest welcome content lives here rather than in a second email — one coherent invitation, not two mails at once. Same branded shell as welcome_email(): cream @@ -2444,7 +2460,7 @@ def gift_invitation_email(name: str, setup_url: str, inviter_name: str = "") -> "It's a member-governed AI cooperative that runs open models on\n" "renewable energy.\n\n" "Your invitation comes with $5 of credits for the co-op's chat and\n" - f"API. Access runs for {int(GIFT_DAYS)} days from today; the credits\n" + f"API. Access runs for {int(GUEST_DAYS)} days from today; the credits\n" "themselves don't expire early.\n\n" "To accept, create your account — it takes about a minute:\n\n" f"{setup_url}\n\n" @@ -2473,7 +2489,7 @@ def gift_invitation_email(name: str, setup_url: str, inviter_name: str = "") ->

You're invited, {name}

{html_invited} — a member-governed AI cooperative running open models on renewable energy.

-

Your invitation comes with $5 of credits for the co-op's chat and API. Access runs for {int(GIFT_DAYS)} days from today; the credits themselves don't expire early.

+

Your invitation comes with $5 of credits for the co-op's chat and API. Access runs for {int(GUEST_DAYS)} days from today; the credits themselves don't expire early.

Create your account

This takes about a minute.

If you like it, become a member.

@@ -2498,10 +2514,10 @@ def gift_invitation_email(name: str, setup_url: str, inviter_name: str = "") -> return subject, text, html -def gift_member_congrats_email(name: str, setup_url: str | None) -> tuple[str, str, str]: - """Short congratulations email for a gift account converting to a member. +def guest_member_congrats_email(name: str, setup_url: str | None) -> tuple[str, str, str]: + """Short congratulations email for a guest account converting to a member. - Their account, login and any unspent gift credit carry over unchanged; + Their account, login and any unspent guest credit carry over unchanged; they gain the monthly allowance and the member services (Loomio, Matrix invites follow from the normal syncs). """ @@ -2512,8 +2528,8 @@ def gift_member_congrats_email(name: str, setup_url: str | None) -> tuple[str, s f"{setup_url}\n\n") text = ( f"Hi {name},\n\n" - "Great news: your gift account is now a full membership. Nothing about\n" - "your login, dashboard or API keys changes — and any gift credit you\n" + "Great news: your guest account is now a full membership. Nothing about\n" + "your login, dashboard or API keys changes — and any guest credit you\n" "hadn't spent yet stays on your account on top of your allowance.\n\n" "As a member you now get:\n" " • a $15 monthly allowance (renews on your join day)\n" @@ -2533,7 +2549,7 @@ def gift_member_congrats_email(name: str, setup_url: str | None) -> tuple[str, s

You're a member now, {name}

-

Your gift account has become a full membership. Nothing about your login, dashboard or API keys changes — any unspent gift credit stays on your account, on top of your new $15 monthly allowance.

+

Your guest account has become a full membership. Nothing about your login, dashboard or API keys changes — any unspent guest credit stays on your account, on top of your new $15 monthly allowance.

Invites to the co-op forum (Loomio) and chat space (Matrix) are on their way.

{'Finish account setup' if setup_url else 'Open your dashboard'}

Questions? Reply to this email — it reaches the co-op directly.

@@ -2549,24 +2565,24 @@ def gift_member_congrats_email(name: str, setup_url: str | None) -> tuple[str, s return subject, text, html -def gift_limits_email(name: str, reason: str) -> tuple[str, str, str]: - """Build the reaching-limits email for a gift account hitting its limit. +def guest_limits_email(name: str, reason: str) -> tuple[str, str, str]: + """Build the reaching-limits email for a guest account hitting its limit. - Sent ONCE per guest when the sweep deactivates the gift — either the $5 - of credits are spent or the GIFT_DAYS time box has run out. Says plainly: - the gift access has ended, the account and data are kept, and becoming a + Sent ONCE per guest when the sweep deactivates the guest — either the $5 + of credits are spent or the GUEST_DAYS time box has run out. Says plainly: + the guest access has ended, the account and data are kept, and becoming a member ($15/month via Open Collective) restores access with a full - monthly allowance and the community spaces. Same shell as the other gift + monthly allowance and the community spaces. Same shell as the other guest emails; matter-of-fact and welcoming — no guilt, no upsell. """ subject = "Your guest access has ended — become a member to continue" if reason == "depleted": - ended = f"Your ${GIFT_BUDGET:g} of gift credits are spent." + ended = f"Your ${GUEST_BUDGET:g} of guest credits are spent." else: - ended = f"The gift's {int(GIFT_DAYS)} days are up." + ended = f"The guest's {int(GUEST_DAYS)} days are up." text = ( f"Hi {name},\n\n" - f"{ended} Your gift access to the Inference Cooperative has ended.\n\n" + f"{ended} Your guest access to the Inference Cooperative has ended.\n\n" "Your account and data are kept. If you'd like to continue, become a\n" "member: $15/month through Open Collective restores full access, with\n" "a full monthly allowance and the co-op's community spaces.\n\n" @@ -2585,8 +2601,8 @@ def gift_limits_email(name: str, reason: str) -> tuple[str, str, str]: {PINE_LOGO_SVG}
-

Your gift access has ended

-

{ended} Your gift access to the Inference Cooperative has ended.

+

Your guest access has ended

+

{ended} Your guest access to the Inference Cooperative has ended.

Your account and data are kept. If you'd like to continue, become a member — $15/month through Open Collective restores full access, with a full monthly allowance and the co-op's community spaces.

Become a member

Questions? Reply to this email — it reaches the co-op directly.

@@ -2602,28 +2618,28 @@ def gift_limits_email(name: str, reason: str) -> tuple[str, str, str]: return subject, text, html -async def provision_gift_member(email: str, name: str, inviter_email: str) -> str: - """Provision a GIFT account end-to-end (operator gifting feature). +async def provision_guest_member(email: str, name: str, inviter_email: str) -> str: + """Provision a GUEST account end-to-end (operator guest access feature). - A gift gives a friend $5 of credits with no Open Collective membership: + A guest gives a friend $5 of credits with no Open Collective membership: * Cloudron user in the GUESTS group (chat + dashboard only — the two apps' access restrictions list both groups); - * a LiteLLM team hard-capped at GIFT_BUDGET with NO monthly reset - (budget_duration None — the cap is the gift's whole life); - * the portal row marked account_type='gift' with the $5 held as - non-expiring credit (the credits model) and gift_expires_at set; - * the gift INVITATION email (inviter named, the $5 credits, the setup + * a LiteLLM team hard-capped at GUEST_BUDGET with NO monthly reset + (budget_duration None — the cap is the guest's whole life); + * the portal row marked account_type='guest' with the $5 held as + non-expiring credit (the credits model) and guest_expires_at set; + * the guest INVITATION email (inviter named, the $5 credits, the setup link — the invitation and the guest welcome in one) and the newsletter subscription; - * a gifts-ledger row recording inviter → recipient; + * a guests-ledger row recording inviter → recipient; * NO Loomio/Matrix invites, no docs-RAG members group. Reuses provision_member's internals (user create, team, key, store) rather - than duplicating them. Guards (gift_provision_guard) enforce one gift per - inviter per 30 days and one gift per recipient ever. + than duplicating them. Guards (guest_provision_guard) enforce one guest per + inviter per 30 days and one guest per recipient ever. """ conn = get_db() - refusal = gift_provision_guard(conn, inviter_email, email) + refusal = guest_provision_guard(conn, inviter_email, email) conn.close() if refusal: raise HTTPException(429, refusal) @@ -2635,29 +2651,29 @@ async def provision_gift_member(email: str, name: str, inviter_email: str) -> st await cloudron_set_active(user_id, True) # One-time $5 team: budget_duration None means LiteLLM never resets it. - team_id = await litellm_get_or_create_team(email, GIFT_BUDGET, budget_duration=None) + team_id = await litellm_get_or_create_team(email, GUEST_BUDGET, budget_duration=None) key_token = get_stored_key(email) if not key_token: - key_token = await litellm_create_key(email, GIFT_BUDGET, team_id) + key_token = await litellm_create_key(email, GUEST_BUDGET, team_id) # The row FIRST (the credits model updates a row that must exist), then - # the gift credit — non-expiring, ledger-audited, deduped on the gift + # the guest credit — non-expiring, ledger-audited, deduped on the guest # reference. - store_member(email, key_token, user_id, "", account_type="gift") - gift_ref = f"gift:{email}" - if not credit_reference_exists(gift_ref): - add_credits(email, GIFT_BUDGET, - reason="gift account — $5 credit from a member", - reference=gift_ref) - # Gift rows hold NO allowance (balance 0 — the $5 is all credit) and - # anchor their join day at the gift date (kept if they later convert). + store_member(email, key_token, user_id, "", account_type="guest") + guest_ref = f"guest:{email}" + if not credit_reference_exists(guest_ref): + add_credits(email, GUEST_BUDGET, + reason="guest account — $5 credit from a member", + reference=guest_ref) + # Guest rows hold NO allowance (balance 0 — the $5 is all credit) and + # anchor their join day at the guest date (kept if they later convert). conn = get_db() conn.execute( "UPDATE members SET balance = 0.0, " - "gift_expires_at = datetime('now', ?), " + "guest_expires_at = datetime('now', ?), " "anchor_day = COALESCE(anchor_day, ?) " "WHERE email = ?", - (f"+{int(GIFT_DAYS)} days", _clamp_anchor_day(datetime.now(timezone.utc).day), email), + (f"+{int(GUEST_DAYS)} days", _clamp_anchor_day(datetime.now(timezone.utc).day), email), ) conn.commit() conn.close() @@ -2674,9 +2690,9 @@ async def provision_gift_member(email: str, name: str, inviter_email: str) -> st conn.close() if row and row[0]: inviter_name = row[0] - # ONE email at gift time: the invitation is also the guest welcome (merged, + # ONE email at guest time: the invitation is also the guest welcome (merged, # not two mails to the same person at once). - subject, text, html = gift_invitation_email(name, setup_url, inviter_name) + subject, text, html = guest_invitation_email(name, setup_url, inviter_name) send_email(email, subject, text, html) touch_welcome_sent(email) @@ -2686,35 +2702,35 @@ async def provision_gift_member(email: str, name: str, inviter_email: str) -> st conn = get_db() conn.execute( - "INSERT INTO gifts (inviter_email, recipient_email, oc_reference, gift_expires_at, status) " - "VALUES (?, ?, NULL, (SELECT gift_expires_at FROM members WHERE email = ?), 'active')", + "INSERT INTO guests (inviter_email, recipient_email, oc_reference, guest_expires_at, status) " + "VALUES (?, ?, NULL, (SELECT guest_expires_at FROM members WHERE email = ?), 'active')", (inviter_email.strip().lower(), email, email), ) conn.commit() conn.close() - logger.info("Provisioned GIFT account %s (user_id=%s, inviter=%s, budget=%.2f, " - "expires per GIFT_DAYS=%d)", email, user_id, inviter_email, - GIFT_BUDGET, GIFT_DAYS) + logger.info("Provisioned GUEST account %s (user_id=%s, inviter=%s, budget=%.2f, " + "expires per GUEST_DAYS=%d)", email, user_id, inviter_email, + GUEST_BUDGET, GUEST_DAYS) return user_id -async def convert_gift_to_member(email: str, name: str, slug: str = "") -> str: - """Convert a GIFT account into a full member (the automatic transition). +async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str: + """Convert a GUEST account into a full member (the automatic transition). Fires when the guest's OC identity appears as a live BACKER/ADMIN with the SAME email (reconcile_memberships or the webhook) — or by the operator via - POST /admin/gift-convert when the contribution arrived under a different + POST /admin/guest-convert when the contribution arrived under a different OC email (that path records members.oc_email so later renewals match). What converts: * the Cloudron user moves guests → members (regaining Loomio/Matrix eligibility through the normal syncs); - * the LiteLLM cap lifts from the $5 gift to the member allowance + - credits — any UNSPENT gift credit stays (it already lives in the + * the LiteLLM cap lifts from the $5 guest to the member allowance + + credits — any UNSPENT guest credit stays (it already lives in the non-expiring credit_balance bucket); * the portal row becomes account_type='member' with the standard - MEMBER_BUDGET allowance; anchor_day (their join day = the gift day) is + MEMBER_BUDGET allowance; anchor_day (their join day = the guest day) is KEPT, and the reset is pinned to it like any member's; * a short congratulations email goes out, then the normal member onboarding (newsletter, Loomio + Matrix syncs, docs-RAG group, @@ -2732,14 +2748,14 @@ async def convert_gift_to_member(email: str, name: str, slug: str = "") -> str: # 1. Group move: guests → members (idempotent PUT; default = members group). await cloudron_set_group(user_id) - # 2. Row: full member with the standard allowance. Unspent gift credits + # 2. Row: full member with the standard allowance. Unspent guest credits # simply stay in credit_balance. anchor_day is untouched: their join - # day is the day the gift started. + # day is the day the guest started. conn = get_db() conn.execute( "UPDATE members SET balance = ?, account_type = 'member', active = 1, " "slug = CASE WHEN ? != '' THEN ? ELSE slug END, " - "gift_expires_at = NULL WHERE email = ?", + "guest_expires_at = NULL WHERE email = ?", (MEMBER_BUDGET, slug, slug, email), ) conn.commit() @@ -2754,13 +2770,13 @@ async def convert_gift_to_member(email: str, name: str, slug: str = "") -> str: anchor = await anchor_day_for_member(email, slug) await litellm_pin_reset_date(team_id, next_reset_for_anchor_day(anchor)) except Exception as e: - logger.warning("Gift convert: reset pin failed for %s: %s", email, e) + logger.warning("Guest convert: reset pin failed for %s: %s", email, e) - # 4. Full member onboarding — the pieces the gift path skipped. + # 4. Full member onboarding — the pieces the guest path skipped. try: await owui_add_to_members_group(user_id) except Exception as e: - logger.warning("Gift convert: OWUI group add skipped for %s: %s", email, e) + logger.warning("Guest convert: OWUI group add skipped for %s: %s", email, e) await listmonk_sync(email, subscribe=True) try: conn = get_db() @@ -2768,9 +2784,9 @@ async def convert_gift_to_member(email: str, name: str, slug: str = "") -> str: conn.close() if granted > 0: await sync_team_budget_from_balance(email) - logger.info("Gift convert: granted %.2f held credits to %s", granted, email) + logger.info("Guest convert: granted %.2f held credits to %s", granted, email) except Exception as e: - logger.warning("Gift convert: held-credit grant for %s failed: %s", email, e) + logger.warning("Guest convert: held-credit grant for %s failed: %s", email, e) await sync_loomio_memberships() await sync_matrix_space() @@ -2782,40 +2798,40 @@ async def convert_gift_to_member(email: str, name: str, slug: str = "") -> str: setup_url = await cloudron_get_invite_link(user_id) except Exception: setup_url = None - subject, text, html = gift_member_congrats_email(name or email.split("@")[0], setup_url) + subject, text, html = guest_member_congrats_email(name or email.split("@")[0], setup_url) send_email(email, subject, text, html) touch_welcome_sent(email) conn = get_db() - conn.execute("UPDATE gifts SET status = 'converted' WHERE recipient_email = ? AND status = 'active'", + conn.execute("UPDATE guests SET status = 'converted' WHERE recipient_email = ? AND status = 'active'", (email,)) conn.commit() conn.close() - logger.info("Converted GIFT account %s to member (slug=%s)", email, slug) + logger.info("Converted GUEST account %s to member (slug=%s)", email, slug) return user_id -def gift_lapse_notice_sent(email: str) -> bool: +def guest_lapse_notice_sent(email: str) -> bool: """True when the reaching-limits email has already gone out for this guest. The once-only gate (same shape as shortfall_notice_sent): one row per - guest, ever. The gifts ledger records what became of a gift; this table + guest, ever. The guests ledger records what became of a guest; this table records what actually left the building. """ conn = get_db() - _ensure_gift_notice_table(conn) + _ensure_guest_notice_table(conn) row = conn.execute( - "SELECT 1 FROM gift_lapse_notices WHERE email = ? LIMIT 1", (email,) + "SELECT 1 FROM guest_lapse_notices WHERE email = ? LIMIT 1", (email,) ).fetchone() conn.close() return bool(row) -def mark_gift_lapse_notice_sent(email: str, reason: str) -> None: +def mark_guest_lapse_notice_sent(email: str, reason: str) -> None: conn = get_db() - _ensure_gift_notice_table(conn) + _ensure_guest_notice_table(conn) conn.execute( - "INSERT OR REPLACE INTO gift_lapse_notices (email, reason, sent_at)" + "INSERT OR REPLACE INTO guest_lapse_notices (email, reason, sent_at)" " VALUES (?, ?, datetime('now'))", (email, reason), ) @@ -2823,22 +2839,22 @@ def mark_gift_lapse_notice_sent(email: str, reason: str) -> None: conn.close() -def _ensure_gift_notice_table(conn) -> None: - """Records which guests have been told their gift access ended. +def _ensure_guest_notice_table(conn) -> None: + """Records which guests have been told their guest access ended. - Kept apart from the gifts ledger on purpose: the ledger answers "what was - gifted and what became of it", this answers "what left the building". A + Kept apart from the guests ledger on purpose: the ledger answers "what was + invited and what became of it", this answers "what left the building". A guest is notified at most once, ever. """ conn.execute( - "CREATE TABLE IF NOT EXISTS gift_lapse_notices (" + "CREATE TABLE IF NOT EXISTS guest_lapse_notices (" " email TEXT PRIMARY KEY, reason TEXT NOT NULL," " sent_at TEXT NOT NULL DEFAULT (datetime('now')))" ) conn.commit() -async def send_gift_lapse_notice(email: str, user_id: str | None, reason: str) -> bool: +async def send_guest_lapse_notice(email: str, user_id: str | None, reason: str) -> bool: """Send the reaching-limits email ONCE per guest. Checks the sent-state row before sending and marks it only after the send @@ -2846,7 +2862,7 @@ async def send_gift_lapse_notice(email: str, user_id: str | None, reason: str) - shipped) is retried by the sweep's catch-up pass, never double-sent. Returns True when a send actually left the building. """ - if gift_lapse_notice_sent(email): + if guest_lapse_notice_sent(email): return False # Greet by name where we can find one: the Cloudron display name, else the # portal slug, else "there" (never the email local part). @@ -2859,7 +2875,7 @@ async def send_gift_lapse_notice(email: str, user_id: str | None, reason: str) - name = next((u.get("displayName") or "" for u in users if u.get("id") == user_id), "") except Exception as e: - logger.warning("Gift lapse notice: name lookup failed for %s: %s", email, e) + logger.warning("Guest lapse notice: name lookup failed for %s: %s", email, e) if not name: conn = get_db() row = conn.execute( @@ -2868,24 +2884,24 @@ async def send_gift_lapse_notice(email: str, user_id: str | None, reason: str) - conn.close() if row and row[0]: name = row[0] - subject, text_body, html_body = gift_limits_email(name or "there", reason) + subject, text_body, html_body = guest_limits_email(name or "there", reason) if send_email(email, subject, text_body, html_body): - mark_gift_lapse_notice_sent(email, reason) + mark_guest_lapse_notice_sent(email, reason) return True return False -async def reconcile_gift_lifecycles() -> dict: - """Lapse gift accounts by their own rules: time box or spent credits. +async def reconcile_guest_lifecycles() -> dict: + """Lapse guest accounts by their own rules: time box or spent credits. Runs inside the nightly sweep. Two deactivation triggers, checked per - ACTIVE gift row: - * gift_expires_at past (the GIFT_DAYS time box) — even with credits left; + ACTIVE guest row: + * guest_expires_at past (the GUEST_DAYS time box) — even with credits left; * credits exhausted — the team's spend has reached the credit balance (LiteLLM's cap already blocks further spend; this retires the row). Deactivation is the same semantics as a member's: guests group → inactive, team budget zeroed, row active=0, newsletter unsubscribed. The account is - KEPT so a returning payer resumes cleanly; the gifts-ledger status records + KEPT so a returning payer resumes cleanly; the guests-ledger status records which rule ended it ('expired' | 'depleted'). Returns {expired, depleted, lapse_notices} counts; never raises past a @@ -2896,8 +2912,8 @@ async def reconcile_gift_lifecycles() -> dict: notified = 0 conn = get_db() rows = conn.execute( - "SELECT email, cloudron_user_id, credit_balance, balance, gift_expires_at " - "FROM members WHERE active = 1 AND account_type = 'gift'" + "SELECT email, cloudron_user_id, credit_balance, balance, guest_expires_at " + "FROM members WHERE active = 1 AND account_type = 'guest'" ).fetchall() conn.close() now = datetime.now(timezone.utc) @@ -2932,7 +2948,7 @@ async def reconcile_gift_lifecycles() -> dict: await listmonk_sync(email, subscribe=False) conn = get_db() conn.execute( - "UPDATE gifts SET status = ? WHERE recipient_email = ? AND status = 'active'", + "UPDATE guests SET status = ? WHERE recipient_email = ? AND status = 'active'", (reason, email), ) conn.commit() @@ -2941,35 +2957,35 @@ async def reconcile_gift_lifecycles() -> dict: expired += 1 else: depleted += 1 - logger.info("Gift lifecycle: %s deactivated (%s)", email, reason) + logger.info("Guest lifecycle: %s deactivated (%s)", email, reason) # Reaching-limits email: once per guest, ever, sent AFTER the # deactivation committed (never tell someone their access ended # while it hasn't). A failed send stays unmarked and is retried # by the catch-up pass below on a later sweep. try: - if await send_gift_lapse_notice(email, user_id, reason): + if await send_guest_lapse_notice(email, user_id, reason): notified += 1 except Exception as e: - logger.warning("Gift lapse notice failed for %s: %s", email, e) + logger.warning("Guest lapse notice failed for %s: %s", email, e) except Exception as e: - logger.warning("Gift lifecycle: failed for %s: %s", email, e) + logger.warning("Guest lifecycle: failed for %s: %s", email, e) # Catch-up: guests already deactivated (lapsed before this email shipped, # or whose send failed) who were never told. Converted guests are excluded # by the WHERE — their account_type is 'member' now, and a member is never - # told their gift ended. + # told their guest ended. conn = get_db() pending = conn.execute( - "SELECT email, cloudron_user_id, gift_expires_at FROM members " - "WHERE active = 0 AND account_type = 'gift'" + "SELECT email, cloudron_user_id, guest_expires_at FROM members " + "WHERE active = 0 AND account_type = 'guest'" ).fetchall() conn.close() for email, user_id, expires_at in pending: - if gift_lapse_notice_sent(email): + if guest_lapse_notice_sent(email): continue try: conn = get_db() grow = conn.execute( - "SELECT status FROM gifts WHERE recipient_email = ? " + "SELECT status FROM guests WHERE recipient_email = ? " "ORDER BY id DESC LIMIT 1", (email,) ).fetchone() conn.close() @@ -2984,19 +3000,19 @@ async def reconcile_gift_lifecycles() -> dict: reason = "expired" if (exp and datetime.now(timezone.utc) >= exp) else "depleted" except ValueError: reason = "depleted" - if await send_gift_lapse_notice(email, user_id, reason): + if await send_guest_lapse_notice(email, user_id, reason): notified += 1 except Exception as e: - logger.warning("Gift lapse catch-up failed for %s: %s", email, e) + logger.warning("Guest lapse catch-up failed for %s: %s", email, e) 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). +async def cancel_guest_account(email: str) -> dict: + """End a guest account at the recipient's own request (self-service cancel). - The guest-side counterpart to reconcile_gift_lifecycles: the recipient + The guest-side counterpart to reconcile_guest_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 + deactivation semantics as a guest 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. @@ -3007,17 +3023,17 @@ async def cancel_gift_account(email: str) -> dict: 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 + its reason naming the cancellation and the original guest 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 → + * the guests 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 + Refuses (403) anything that is not a guest 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. @@ -3032,24 +3048,24 @@ async def cancel_gift_account(email: str) -> dict: 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. + if (account_type or "member") != "guest": + # The hard member guard: this endpoint only ever ends GUEST access. # A membership is ended by ending its Open Collective contribution. - raise HTTPException(403, "Only gift accounts can be cancelled here") + raise HTTPException(403, "Only guest accounts can be cancelled here") - gift_status = _gift_ledger_status(email) + guest_status = _guest_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), + "guest_status": guest_status or "inactive", + "credits_returned": _guest_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). + # already drew (a guest row holds NO allowance — balance is 0 — so the + # credits model's remaining figure IS the unspent guest). allowance = float(balance) if balance is not None else 0.0 credit_total = float(credits or 0.0) spend = None @@ -3060,21 +3076,21 @@ async def cancel_gift_account(email: str) -> dict: spend = team.get("spend") unspent = round(compute_max_budget(allowance, credit_total, spend)["credits_remaining"], 2) - return_ref = f"gift-return:{email}" + return_ref = f"guest-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 + credits_returned = _guest_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})"), + reason=(f"guest cancelled by recipient — unspent credit returned to the " + f"co-op (original guest: guest:{email})"), reference=return_ref, ) credits_returned = unspent - # Deactivation, gift-lapse semantics: row inactive, group out of guests, + # Deactivation, guest-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 @@ -3085,7 +3101,7 @@ async def cancel_gift_account(email: str) -> dict: conn = get_db() conn.execute( - "UPDATE gifts SET status = 'cancelled by recipient' " + "UPDATE guests SET status = 'cancelled by recipient' " "WHERE recipient_email = ? AND status = 'active'", (email,), ) @@ -3095,29 +3111,29 @@ async def cancel_gift_account(email: str) -> dict: # 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") + mark_guest_lapse_notice_sent(email, "cancelled by recipient") - logger.info("Gift cancel: %s cancelled by recipient (returned %.2f)", email, credits_returned) + logger.info("Guest cancel: %s cancelled by recipient (returned %.2f)", email, credits_returned) return { "status": "cancelled", - "gift_status": "cancelled by recipient", + "guest_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.""" +def _guest_ledger_status(email: str) -> str | None: + """The latest guests-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", + "SELECT status FROM guests 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). +def _guest_returned_credits(email: str) -> float: + """Credit returned to the co-op for this guest (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. @@ -3125,7 +3141,7 @@ def _gift_returned_credits(email: str) -> float: conn = get_db() rows = conn.execute( "SELECT delta FROM credit_ledger WHERE reference = ?", - (f"gift-return:{email}",), + (f"guest-return:{email}",), ).fetchall() conn.close() return round(sum(-float(r[0] or 0.0) for r in rows), 2) @@ -3139,9 +3155,9 @@ async def litellm_get_or_create_team(email: str, budget: float, budget. The team holds the chat key + any member-managed API keys, so all spend draws from the one pool. - `budget_duration` is the reset cadence: members renew every 30 days; GIFT + `budget_duration` is the reset cadence: members renew every 30 days; GUEST accounts pass None — a one-time budget that NEVER resets, so the $5 cap is - the gift's whole life (spend it and it is gone). + the guest's whole life (spend it and it is gone). Idempotent: looks up the existing team by alias before creating. Note that /team/new is NOT idempotent (it creates a new team each call), so we must @@ -3676,8 +3692,8 @@ async def opencollective_webhook(request: Request, token: str): member = next((m for m in members if m["slug"] == slug), None) if member: # A contribution may arrive under a DIFFERENT email than the - # portal account (a gifted friend who joined under another OC - # address — linked via /admin/gift-convert): route the payment + # portal account (a invited friend who joined under another OC + # address — linked via /admin/guest-convert): route the payment # to the mapped account instead of minting a duplicate row. oc_email = (member.get("email") or "").strip().lower() if oc_email: @@ -4069,18 +4085,18 @@ async def admin_provision(request: Request): return {"status": "provisioned", "email": email, "user_id": user_id} -@app.post("/admin/provision-gift") +@app.post("/admin/provision-guest") @limiter.limit("20/minute") -async def admin_provision_gift(request: Request): - """Provision a GIFT account (the operator's gifting action). +async def admin_provision_guest(request: Request): + """Provision a GUEST account (the operator's guest access action). Same auth as /admin/provision (X-Admin-Token). Body: {"email": "...", - "name": "...", "inviter": ""}. Runs the gift + "name": "...", "inviter": ""}. Runs the guest pipeline: Cloudron user in the guests group, a $5 LiteLLM team with NO - monthly reset, the portal row marked as a gift with a GIFT_DAYS expiry, - the gift welcome email, the newsletter subscription, and a gifts-ledger - row recording inviter → recipient. Abuse guards: one gift per inviter per - 30 days; one gift per recipient ever; the inviter must be an active + monthly reset, the portal row marked as a guest with a GUEST_DAYS expiry, + the guest welcome email, the newsletter subscription, and a guests-ledger + row recording inviter → recipient. Abuse guards: one guest per inviter per + 30 days; one guest per recipient ever; the inviter must be an active member. No Loomio/Matrix. """ _verify_admin_token(request) @@ -4094,22 +4110,22 @@ async def admin_provision_gift(request: Request): if not inviter or "@" not in inviter: raise HTTPException(400, "The inviting member's email ('inviter') is required") - user_id = await provision_gift_member(email, name, inviter) + user_id = await provision_guest_member(email, name, inviter) return { - "status": "provisioned", "account_type": "gift", "email": email, - "inviter": inviter, "user_id": user_id, "budget": GIFT_BUDGET, - "expires_in_days": int(GIFT_DAYS), + "status": "provisioned", "account_type": "guest", "email": email, + "inviter": inviter, "user_id": user_id, "budget": GUEST_BUDGET, + "expires_in_days": int(GUEST_DAYS), } -@app.post("/admin/gift-convert") +@app.post("/admin/guest-convert") @limiter.limit("20/minute") -async def admin_gift_convert(request: Request): - """Convert a gift account to a member when OC cannot auto-match. +async def admin_guest_convert(request: Request): + """Convert a guest account to a member when OC cannot auto-match. The automatic conversion matches the guest's OWN email against the live OC backer list. When the membership was paid under a DIFFERENT Open - Collective email, the operator links it here: {"email": "", "oc_email": ""}. The OC member record (name, slug) is resolved from oc_email and stored on the row (members.oc_email) so the sweep and the webhook keep matching renewals @@ -4123,11 +4139,11 @@ async def admin_gift_convert(request: Request): email = (body.get("email") or "").strip().lower() oc_email = (body.get("oc_email") or "").strip().lower() if not email or "@" not in email: - raise HTTPException(400, "A valid gift account email is required") + raise HTTPException(400, "A valid guest account email is required") if oc_email and "@" not in oc_email: raise HTTPException(400, "oc_email must be a valid email") - if not is_gift_account(email): - raise HTTPException(409, f"{email} is not a gift account (already converted or a member row)") + if not is_guest_account(email): + raise HTTPException(409, f"{email} is not a guest account (already converted or a member row)") name, slug = "", "" if oc_email: @@ -4142,16 +4158,32 @@ async def admin_gift_convert(request: Request): conn.commit() conn.close() - user_id = await convert_gift_to_member(email, name or email.split("@")[0], slug) + user_id = await convert_guest_to_member(email, name or email.split("@")[0], slug) return { "status": "converted", "email": email, "oc_email": oc_email or None, "user_id": user_id, "note": ("account keeps its own email and login; group moved guests → members; " - "cap lifted to the member allowance with unspent gift credit carried; " + "cap lifted to the member allowance with unspent guest credit carried; " "anchor day (join day) kept"), } +# TRANSITION ALIASES (guest rename, 2026-11-08): the deployed dashboard and +# panel builds predate the guest rename and still call the old paths. These +# answer identically (auth runs inside the real handler) until the renamed +# builds are deployed; REMOVE once no caller remains. +@app.post("/admin/provision-gift") +@limiter.limit("20/minute") +async def admin_provision_gift_alias(request: Request): + return await admin_provision_guest(request) + + +@app.post("/admin/gift-convert") +@limiter.limit("20/minute") +async def admin_gift_convert_alias(request: Request): + return await admin_guest_convert(request) + + @app.post("/admin/org-link") @limiter.limit("20/minute") async def admin_org_link(request: Request): @@ -4489,7 +4521,7 @@ async def admin_overview(request: Request): Authenticated by the X-Admin-Token header. Returns every member (active + inactive) with their balance, spend, remaining, and team reset date, plus - co-op aggregates (total members, total spend). Guest (gift) accounts come + co-op aggregates (total members, total spend). Guest (guest) accounts come back in their own `guests` list — never inside `members` — so no consumer can count them as members by accident; their spend is broken out in the totals rather than folded into the member figures. @@ -4499,19 +4531,19 @@ async def admin_overview(request: Request): conn = get_db() rows = conn.execute( "SELECT email, active, balance, cloudron_user_id, org_slug, matrix_mxid, " - "account_type, oc_email, gift_expires_at FROM members ORDER BY email" + "account_type, oc_email, guest_expires_at FROM members ORDER BY email" ).fetchall() - # Gift inviter/expiry from the gifts ledger (latest row per recipient) — - # the abuse-protection context the panel shows on the gift pill. - gift_info: dict[str, dict] = {} + # Guest inviter/expiry from the guests ledger (latest row per recipient) — + # the abuse-protection context the panel shows on the guest pill. + guest_info: dict[str, dict] = {} try: for r in conn.execute( - "SELECT recipient_email, inviter_email, gift_expires_at, status " - "FROM gifts WHERE id IN (SELECT MAX(id) FROM gifts GROUP BY recipient_email)" + "SELECT recipient_email, inviter_email, guest_expires_at, status " + "FROM guests WHERE id IN (SELECT MAX(id) FROM guests GROUP BY recipient_email)" ).fetchall(): - gift_info[r[0]] = {"inviter": r[1], "expires": r[2], "status": r[3]} + guest_info[r[0]] = {"inviter": r[1], "expires": r[2], "status": r[3]} except Exception as e: - logger.warning("admin overview: gifts ledger read failed: %s", e) + logger.warning("admin overview: guests ledger read failed: %s", e) conn.close() # Fetch Cloudron users once to map user_id → username + inviteAccepted. @@ -4581,7 +4613,7 @@ async def admin_overview(request: Request): operator_all_time = 0.0 guest_spend = 0.0 guest_all_time = 0.0 - for email, active, balance, user_id, org_slug, matrix_mxid, acct_type, oc_email, gift_exp in rows: + for email, active, balance, user_id, org_slug, matrix_mxid, acct_type, oc_email, guest_exp in rows: team = teams.get(f"member:{email}", {}) spend = float(team.get("spend") or 0.0) member_all_time = float(all_time_spend.get(f"member:{email}", 0.0)) @@ -4620,12 +4652,12 @@ async def admin_overview(request: Request): "cloudron_user_id": user_id, "account_type": acct_type or "member", "oc_email": oc_email or None, - "gift_expires_at": gift_exp or None, + "guest_expires_at": guest_exp or None, } - if (acct_type or "member") == "gift": - gi = gift_info.get(email) or {} - entry["gift_inviter"] = gi.get("inviter") - entry["gift_status"] = gi.get("status") + if (acct_type or "member") == "guest": + gi = guest_info.get(email) or {} + entry["guest_inviter"] = gi.get("inviter") + entry["guest_status"] = gi.get("status") if email.lower() in OPERATOR_EMAILS: # Operator accounts: surfaced under a separate "admin" category in # the panel, excluded from member counts and aggregates (their @@ -4636,10 +4668,10 @@ async def admin_overview(request: Request): total_all_time += member_all_time operator_spend += spend operator_all_time += member_all_time - elif (acct_type or "member") == "gift": - # Guest (gift) accounts: their own list, never members. Excluded + elif (acct_type or "member") == "guest": + # Guest (guest) accounts: their own list, never members. Excluded # from the member count AND from the spend totals a reader reads - # as member activity — a gift is not a membership. Their spend is + # as member activity — a guest is not a membership. Their spend is # broken out separately in the totals so it stays visible (the # same reasoning as the agents below). guests.append(entry) @@ -5353,8 +5385,8 @@ def maybe_first_login_service_sync(email: str) -> None: try: if get_loomio_invited_at(email): return # established member — zero further work - if is_gift_account(email): - return # gift accounts receive no Loomio/Matrix invites + if is_guest_account(email): + return # guest accounts receive no Loomio/Matrix invites if _first_login_sync_inflight: return # a sync is already running; it covers every pending member loop = asyncio.get_running_loop() @@ -5429,15 +5461,15 @@ 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. +def _verify_broker_guest_identity(request: Request) -> str: + """Broker auth that also admits ENDED guest 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, + widening scoped to guest 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. + identity can reach — the routes on top enforce the guest-only rule again. """ if not BROKER_SECRET: raise HTTPException(503, "Broker secret not configured") @@ -5460,8 +5492,8 @@ def _verify_broker_gift_identity(request: Request) -> str: 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 account_type == "guest": + return email # any state — the cancel/guest-status route decides if not active or not get_member_key(email): raise HTTPException(403, "No active membership") maybe_first_login_service_sync(email) @@ -5504,7 +5536,7 @@ _MXID_RE = re.compile(r"^@[^\s:]+:[^\s]+\.[^\s]+$") @limiter.limit("30/minute") async def broker_get_matrix_mxid(request: Request): email = _verify_broker_secret(request) - if is_gift_account(email): + if is_guest_account(email): # Guests get no Matrix: their dashboard hides the section and the # sync never invites them — the endpoint refuses too, in depth. raise HTTPException(403, "Matrix chat is available to members") @@ -5526,7 +5558,7 @@ def local_mxid_for_email(email: str) -> str: @limiter.limit("30/minute") async def broker_set_matrix_mxid(request: Request): email = _verify_broker_secret(request) - if is_gift_account(email): + if is_guest_account(email): # Setting an MXID would put a guest's account in the next Matrix sync # invite pass — exactly what the feature excludes. raise HTTPException(403, "Matrix chat is available to members") @@ -5676,7 +5708,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict: key_spend = [] return { "email": email, - "guest": is_gift_account(email), + "guest": is_guest_account(email), "balance": balance, "allowance": allowance, "credits": credits, @@ -5753,7 +5785,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict: return { "email": email, - "guest": is_gift_account(email), + "guest": is_guest_account(email), "balance": balance, "allowance": allowance, "credits": credits, @@ -5778,20 +5810,20 @@ async def broker_usage(request: Request, days: int = 0): return await broker_get_usage(email, days=days) -@app.get("/broker/gift-status") +@app.get("/broker/guest-status") @limiter.limit("30/minute") -async def broker_gift_status(request: Request): - """What became of the caller's gift account (self-service cancel support). +async def broker_guest_status(request: Request): + """What became of the caller's guest 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 + that answers for an ENDED guest too (see _verify_broker_guest_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 + contribution away. For an active guest 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) + email = _verify_broker_guest_identity(request) conn = get_db() row = conn.execute( "SELECT active, balance, credit_balance FROM members WHERE email = ?", @@ -5801,9 +5833,9 @@ async def broker_gift_status(request: Request): if not row: raise HTTPException(403, "No active membership") active, balance, credits = row - if not is_gift_account(email): + if not is_guest_account(email): return {"guest": False, "active": bool(active)} - gift_status = _gift_ledger_status(email) or ("active" if active else "inactive") + guest_status = _guest_ledger_status(email) or ("active" if active else "inactive") if active: # Same remaining-credit figure the usage view shows. spend = None @@ -5824,24 +5856,38 @@ async def broker_gift_status(request: Request): "guest": True, "active": bool(active), "ended": not active, - "gift_status": gift_status, - "cancelled": gift_status == "cancelled by recipient", + "guest_status": guest_status, + "cancelled": guest_status == "cancelled by recipient", "credits_remaining": credits_remaining, - "credits_returned": _gift_returned_credits(email), + "credits_returned": _guest_returned_credits(email), } +@app.post("/broker/cancel-guest") +@limiter.limit("10/minute") +async def broker_cancel_guest(request: Request): + """End the caller's own guest account (self-service cancellation). + + Authenticated with the member-dashboard broker identity, guest accounts + only (see cancel_guest_account for the semantics and the idempotence). + A paying member calling this gets a 403, never a cancellation. + """ + email = _verify_broker_guest_identity(request) + return await cancel_guest_account(email) + + +# TRANSITION ALIASES (guest rename, 2026-11-08): see the note above the admin +# aliases. The deployed dashboard build still calls these two paths. +@app.get("/broker/gift-status") +@limiter.limit("30/minute") +async def broker_gift_status_alias(request: Request): + return await broker_guest_status(request) + + @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) +async def broker_cancel_gift_alias(request: Request): + return await broker_cancel_guest(request) @app.get("/broker/metrics") @@ -5932,7 +5978,7 @@ async def reconcile_memberships() -> dict: logger.warning("Sweep: fetch_members returned empty; skipping reconciliation (fail-safe)") return {"status": "skipped", "reason": "empty_member_list", "provisioned": 0, "deactivated": 0} - # Currently provisioned accounts (from our DB), with their type — the gift + # Currently provisioned accounts (from our DB), with their type — the guest # marker drives both the conversion trigger and the deactivation skip. conn = get_db() rows = conn.execute( @@ -5945,7 +5991,7 @@ async def reconcile_memberships() -> dict: } # Members whose contribution arrives under a DIFFERENT OC email (set by - # POST /admin/gift-convert): their oc_email is an additional presence + # POST /admin/guest-convert): their oc_email is an additional presence # matcher — when it appears in the live OC list the account counts as # active even though their own email does not. conn = get_db() @@ -6000,7 +6046,7 @@ async def reconcile_memberships() -> dict: active_emails.add(org_email) logger.info("Sweep: org-linked member %s active via org %s", org_email, org_slug) - # 1. Provision missing members — and CONVERT gift accounts whose owner has + # 1. Provision missing members — and CONVERT guest accounts whose owner has # joined (their email now appears in the live OC backer list). The # conversion itself lives in provision_member, so the webhook and # /admin/provision trigger the same transition automatically. @@ -6014,29 +6060,29 @@ async def reconcile_memberships() -> dict: logger.info("Sweep: provisioned %s", email) except Exception as e: logger.warning("Sweep: failed to provision %s: %s", email, e) - elif entry["account_type"] == "gift": + elif entry["account_type"] == "guest": try: await provision_member(email, m["name"], m["slug"]) converted_count += 1 - logger.info("Sweep: converted gift account %s to member", email) + logger.info("Sweep: converted guest account %s to member", email) except Exception as e: - logger.warning("Sweep: failed to convert gift %s: %s", email, e) + logger.warning("Sweep: failed to convert guest %s: %s", email, e) - # 1b. Gift lifecycles: time-box expiry + spent-out gifts. A gift is never + # 1b. Guest lifecycles: time-box expiry + spent-out guests. A guest is never # deactivated for LACKING a contribution (next loop excludes them) — # only by its own rules. Runs before the member pass so its results # are independent of OC state. try: - gift_counts = await reconcile_gift_lifecycles() + guest_counts = await reconcile_guest_lifecycles() except Exception as e: - logger.warning("Sweep: gift lifecycle pass failed (non-fatal): %s", e) - gift_counts = {"expired": 0, "depleted": 0} + logger.warning("Sweep: guest lifecycle pass failed (non-fatal): %s", e) + guest_counts = {"expired": 0, "depleted": 0} # 2. Deactivate lapsed members (but never manual/founder members, who have - # no OC membership to lapse, and never GIFT accounts — a gift has no OC + # no OC membership to lapse, and never GUEST accounts — a guest has no OC # membership by design; it lapses only via its own rules, handled above). for email, info in provisioned.items(): - if info["account_type"] == "gift": + if info["account_type"] == "guest": continue user_id = info["user_id"] if email not in active_emails and email not in MANUAL_MEMBERS: @@ -6066,9 +6112,9 @@ async def reconcile_memberships() -> dict: for email, user_id, sent_at, acct_type in reinvite_rows: if not user_id: continue - if (acct_type or "member") == "gift": - # Gift accounts are re-invited by re-running /admin/provision-gift - # (it re-sends the gift email idempotently). The MEMBER pipeline + if (acct_type or "member") == "guest": + # Guest accounts are re-invited by re-running /admin/provision-guest + # (it re-sends the guest email idempotently). The MEMBER pipeline # here would move the user into the members group. continue # Skip if already activated. @@ -6112,9 +6158,9 @@ async def reconcile_memberships() -> dict: "deactivated": deactivated_count, "reinvited": reinvited_count, "converted": converted_count, - "gifts_expired": gift_counts.get("expired", 0), - "gifts_depleted": gift_counts.get("depleted", 0), - "gift_lapse_notices": gift_counts.get("lapse_notices", 0), + "guests_expired": guest_counts.get("expired", 0), + "guests_depleted": guest_counts.get("depleted", 0), + "guest_lapse_notices": guest_counts.get("lapse_notices", 0), "newsletter_removed": newsletter.get("removed", 0), } @@ -6587,9 +6633,9 @@ async def reconcile_allowances(send: bool = False) -> dict: oc_email = (row[5] or "").strip().lower() welcome_sent = row[6] if len(row) > 6 else None - if acct_type == "gift": - # Gift accounts have no OC membership by design — the $5 credit - # balance and the GIFT_DAYS time box govern them instead. No + if acct_type == "guest": + # Guest accounts have no OC membership by design — the $5 credit + # balance and the GUEST_DAYS time box govern them instead. No # renewal decision, no reminder, ever. counts["skipped"] += 1 continue @@ -6601,7 +6647,7 @@ async def reconcile_allowances(send: bool = False) -> dict: continue rec = index.get(email.strip().lower()) if rec is None and oc_email: - # Contribution under a different OC email (gift-convert fallback). + # Contribution under a different OC email (guest-convert fallback). rec = index.get(oc_email) if rec and rec.get("role") == "ADMIN": counts["skipped"] += 1 # the co-op's own account @@ -7471,8 +7517,8 @@ async def budget_notice_sweep(send: bool = False) -> dict: email = row[0] name = ((row[1] or "").strip() if len(row) > 1 else "") or "there" acct_type = (row[2] or "member") if len(row) > 2 else "member" - if acct_type == "gift": - # A gift's exhaustion is handled by the gift lifecycle pass (the + if acct_type == "guest": + # A guest's exhaustion is handled by the guest lifecycle pass (the # sweep deactivates it); member low-balance mail about buying # credit packs is not for guests. skipped += 1 diff --git a/metrics_snapshot.py b/metrics_snapshot.py index 865eb9b..0907284 100644 --- a/metrics_snapshot.py +++ b/metrics_snapshot.py @@ -207,7 +207,7 @@ def from_sqlite() -> dict: """Members, plus the provisioning dates that give the growth curve. Operator/utility accounts are excluded, matching the panel's member count. - GIFT accounts are excluded too: they are $5 guest passes, not members — + GUEST accounts are excluded too: they are $5 guest passes, not members — counting them would move the growth curve the co-op publishes. """ conn = connect() @@ -221,7 +221,7 @@ def from_sqlite() -> dict: conn.close() 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")] + and not (has_acct and len(r) > 3 and (r[3] or "") == "guest")] return { "active": sum(1 for r in real if r[1]), "total": len(real), diff --git a/tests/test_gift_cancel.py b/tests/test_guest_cancel.py similarity index 70% rename from tests/test_gift_cancel.py rename to tests/test_guest_cancel.py index 4a875d1..abb8e15 100644 --- a/tests/test_gift_cancel.py +++ b/tests/test_guest_cancel.py @@ -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") diff --git a/tests/test_gift_lifecycle.py b/tests/test_guest_lifecycle.py similarity index 68% rename from tests/test_gift_lifecycle.py rename to tests/test_guest_lifecycle.py index 26ebbde..eddf37c 100644 --- a/tests/test_gift_lifecycle.py +++ b/tests/test_guest_lifecycle.py @@ -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"]))