diff --git a/README.md b/README.md index 686ef4b..bb3f354 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,50 @@ LibreChat ──→ Member Portal ──→ LiteLLM ──→ backend | `ALLOWANCE_POLICY` | `report` (default) \| `on`. `report` computes every allowance decision and changes nothing; `on` performs renewals and sends the one reminder. Deactivation is gated separately by `ALLOWANCE_DEACTIVATE`. | | `ALLOWANCE_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. | + +## Gift accounts + +A member can give a friend access to the co-op with $5 of credits — no Open +Collective membership required. `POST /admin/provision-gift` (X-Admin-Token) +with `{"email", "name", "inviter": ""}` runs the +gift pipeline: Cloudron user in the **guests** group, a LiteLLM team capped at +`GIFT_BUDGET` with **no monthly reset** (the cap is the gift's whole life), the +portal row marked `account_type='gift'` with the $5 held as non-expiring +credit, `gift_expires_at` set to now + `GIFT_DAYS`, the gift welcome email +(setup link, what they can use, Become-a-member, newsletter note), and a +**gifts ledger** row (`gifts` table: inviter → recipient, expiry, status) for +the abuse audit. Guards: one gift per inviter per `GIFT_PER_INVITER_DAYS`; one +gift per recipient ever; the inviter must be an active member; an existing +portal row under the recipient address is refused. Guests are subscribed to +the newsletter and invited to NOTHING else (no Loomio, no Matrix). + +**Sweep safety.** `reconcile_memberships()` never deactivates a gift for +lacking an OC contribution. A gift lapses only by its own rules, handled by +`reconcile_gift_lifecycles()` inside the sweep: credits spent out (LiteLLM's +cap enforces the limit; the sweep retires the row) or the `GIFT_DAYS` time box. +Deactivation is the same semantics as a member's — guests group → inactive, +budget zeroed, row `active=0`, newsletter unsubscribed — and the account is +KEPT so a returning payer resumes cleanly. + +**Guest → member conversion (automatic).** When a gift's OC identity appears as +a live BACKER/ADMIN with the account's own email — via the webhook or the +nightly sweep — `provision_member()` routes the call to +`convert_gift_to_member()`: the Cloudron user moves guests → members, the +LiteLLM cap lifts to the member allowance + credits (unspent gift credit is +carried — it already lives in `credit_balance`), the row becomes a normal +member with the standard `MEMBER_BUDGET`, the anchor day (the gift's start +date) is kept and the reset pinned to it, the congratulations email goes out, +and the normal member onboarding runs (newsletter, Loomio + Matrix syncs, +docs-RAG group, held-credit grants). When the contribution arrives under a +DIFFERENT OC email it cannot auto-match: the operator links it with +`POST /admin/gift-convert` `{"email": "", "oc_email": ""}` — the row records `members.oc_email`, and +the sweep and webhook treat that address as an additional matcher from then on. + ## Budget model diff --git a/app/main.py b/app/main.py index e3274ea..a613a10 100644 --- a/app/main.py +++ b/app/main.py @@ -335,6 +335,33 @@ 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) -------------------------- # +# 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 +# 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. +# 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")) + +# The Cloudron "guests" group: gift 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", "") + +# Where a guest's "Become a member" button and email point (the contribution +# page — what actually starts a membership). Deliberately NOT the portal's +# credit-pack URL: a guest needs a membership, not a credit pack. +BECOME_MEMBER_URL = "https://opencollective.com/inference-cooperative/contribute" + # Days to wait before re-sending the welcome/invite email to a member who was # provisioned but never completed account setup (inviteAccepted=False). The # nightly sweep re-invites such members, throttled by this interval so they @@ -874,6 +901,38 @@ 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 + # 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). + 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 + # 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 + # 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. + conn.execute( + "CREATE TABLE IF NOT EXISTS gifts (" + "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, " + "status TEXT DEFAULT 'active')" + ) # Credit ledger: audit trail for every credit movement (purchases via the # OC webhook, admin adjustments, spends drawn against credits). Money needs # an audit trail. @@ -988,6 +1047,69 @@ def get_credit_balance(email: str) -> float: return 0.0 +def get_member_account_type(email: str) -> str: + """Return the row's account type: 'member' (default) or 'gift'.""" + conn = get_db() + row = conn.execute( + "SELECT account_type FROM members WHERE email = ?", (email,) + ).fetchone() + conn.close() + 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 gift_provision_guard(conn, inviter_email: str, recipient_email: str) -> str | None: + """Decide whether a gift 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 + recipient refuses, as does an existing portal row under that email + (they already have/had a gift account or are a member). + + Returns None when the gift may proceed, else a human-readable refusal. + """ + inviter = (inviter_email or "").strip().lower() + recipient = (recipient_email or "").strip().lower() + if not inviter or "@" not in inviter: + return "The inviting member's email is required" + 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" + 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": + return f"Inviter {inviter} is not an active member account" + recent = conn.execute( + "SELECT COUNT(*) FROM gifts WHERE inviter_email = ? AND " + "created_at >= datetime('now', ?)", + (inviter, f"-{int(GIFT_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") + ever = conn.execute( + "SELECT COUNT(*) FROM gifts WHERE recipient_email = ?", (recipient,) + ).fetchone()[0] + if ever: + return f"{recipient} has already received a gift 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 None + + def add_credits(email: str, delta: float, reason: str, reference: str | None = None) -> float: """Adjust a member's credit balance and record the movement in the ledger. @@ -1327,17 +1449,20 @@ def welcome_email(name: str, setup_url: str) -> tuple[str, str, str]: async def get_active_member_emails() -> list[str]: - """Return the list of active member emails from the portal's own database. + """Return the list of active MEMBER emails from the portal's own database. The local `members` table is the authoritative source of member emails - (populated during provisioning). Used for the Loomio sync. + (populated during provisioning). Used for the Loomio sync and the Matrix + invite pass. GIFT 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. """ conn = get_db() rows = conn.execute( - "SELECT email FROM members WHERE active = 1" + "SELECT email, account_type FROM members WHERE active = 1" ).fetchall() conn.close() - return [r[0] for r in rows] + return [r[0] for r in rows if (r[1] or "member") != "gift"] def get_loomio_invited_at(email: str) -> str | None: @@ -1874,7 +1999,8 @@ async def filter_loomio_activated(emails: list[str]) -> list[str]: return [e for e in emails if e in keep or e in activated] -def store_member(email: str, key_token: str, cloudron_user_id: str, slug: str = "") -> None: +def store_member(email: str, key_token: str, cloudron_user_id: str, slug: str = "", + account_type: str | None = None) -> None: conn = get_db() # Preserve an existing slug if the caller passed none — re-provisioning an # already-provisioned member must not wipe their OC slug (the deactivation @@ -1883,12 +2009,17 @@ def store_member(email: str, key_token: str, cloudron_user_id: str, slug: str = row = conn.execute("SELECT slug FROM members WHERE email = ?", (email,)).fetchone() 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. conn.execute( - "INSERT INTO members (email, key_token, cloudron_user_id, slug, active) " - "VALUES (?, ?, ?, ?, 1) " + "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", - (email, encrypt_key(key_token), cloudron_user_id, slug), + "cloudron_user_id=excluded.cloudron_user_id, slug=excluded.slug, active=1, " + "account_type=CASE WHEN excluded.account_type='gift' THEN 'gift' " + "ELSE COALESCE(members.account_type, 'member') END", + (email, encrypt_key(key_token), cloudron_user_id, slug, account_type), ) conn.commit() conn.close() @@ -2212,7 +2343,14 @@ async def provision_member(email: str, name: str, slug: str = "") -> str: with 400 — the bug that previously made re-provisioning of existing members 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 + 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) user_id = await cloudron_create_user(email, name) await cloudron_set_group(user_id) await cloudron_set_active(user_id, True) @@ -2265,13 +2403,400 @@ async def provision_member(email: str, name: str, slug: str = "") -> str: return user_id -async def litellm_get_or_create_team(email: str, budget: float) -> str: +# --- Gift 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 +# email, and the newsletter subscription. NO Loomio/Matrix invites. See the +# constants block for the lapse rules (credit exhaustion + GIFT_DAYS time box). + +def gift_welcome_email(name: str, setup_url: str) -> tuple[str, str, str]: + """Build the GIFT welcome email — same branded shell as the member welcome. + + Says what the recipient can use, that it lasts until the $5 of credits are + spent (or 60 days pass), carries the Become-a-member button, notes the + newsletter subscription, and points replies at the co-op inbox. No + Loomio/Matrix — guests receive no member invitations. + """ + subject = "You've been gifted access to the Inference Cooperative" + text = ( + f"Hi {name},\n\n" + "A member of the Inference Cooperative has gifted you access!\n\n" + "Your gift gives you $5 of AI usage across the co-op's chat and API —\n" + "the same private, renewable-energy models members use. It lasts until\n" + "the $5 of credits are used up (they don't expire early; your access\n" + "runs for 60 days from today).\n\n" + f"To start, create your account — it takes about a minute:\n\n{setup_url}\n\n" + "When the credits run out (or anytime), you can become a member for\n" + "$10-20/month, sliding scale — same login, plus a monthly allowance:\n" + f"{BECOME_MEMBER_URL}\n\n" + "You're also on our (low-volume, member) newsletter — a way to hear\n" + "what the co-op is building. Unsubscribe anytime from any issue.\n\n" + "Questions? Just reply to this email — it reaches the co-op directly.\n\n" + "— The Inference Cooperative\n" + ) + html = f""" + + + + + + + +
+ + + + + + + + + + +
+ +
+

You've been gifted access, {name}

+

A member of the Inference Cooperative has given you $5 of AI usage — the co-op's private, renewable-energy models across chat and the API.

+

Your gift lasts until the $5 of credits are used up (they don't expire early — access runs 60 days from today).

+ Create your account +

This takes about a minute.

+

Like it? Become a member.

+

$10–20/month, sliding scale — same login, plus a monthly allowance and a say in how the co-op is run.

+ Become a member +

You're also on our (low-volume) newsletter — hear what the co-op is building; unsubscribe anytime.

+
+ Questions? Just reply to this email — it reaches the co-op directly, or write to info@inference.coop.
+ The Inference Cooperative · inference.coop
+ By creating your account, you agree to our Terms of Service and Privacy Policy. +
+
+ +""" + 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. + + Their account, login and any unspent gift credit carry over unchanged; + they gain the monthly allowance and the member services (Loomio, Matrix + invites follow from the normal syncs). + """ + subject = "Welcome to the Inference Cooperative — you're a member now!" + setup_line = "" + if setup_url: + setup_line = (f"Your account isn't set up yet — one minute and you're in:\n\n" + 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" + "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" + " • our co-op forum (Loomio) and chat space (Matrix) — invites on the way\n" + " • a say in how the co-op is run\n\n" + f"{setup_line}" + f"Your dashboard: https://dashboard.inference.coop\n\n" + "Questions? Reply to this email — it reaches the co-op directly.\n\n" + "— The Inference Cooperative\n" + ) + html = f""" + + + + + +
+ + + +
+

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.

+

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.

+
+ The Inference Cooperative · inference.coop +
+
+ +""" + 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). + + A gift 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 welcome email (setup link, expiry, Become-a-member) and the + newsletter subscription; + * a gifts-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. + """ + conn = get_db() + refusal = gift_provision_guard(conn, inviter_email, email) + conn.close() + if refusal: + raise HTTPException(429, refusal) + if not GUESTS_GROUP_ID: + raise HTTPException(503, "GUESTS_GROUP_ID is not configured on the portal app") + + user_id = await cloudron_create_user(email, name) + await cloudron_set_group(user_id, GUESTS_GROUP_ID) + 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) + key_token = get_stored_key(email) + if not key_token: + key_token = await litellm_create_key(email, GIFT_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 + # 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). + conn = get_db() + conn.execute( + "UPDATE members SET balance = 0.0, " + "gift_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), + ) + conn.commit() + conn.close() + await sync_team_budget_from_balance(email) # cap = allowance(0) + credits(5) + + setup_url = await cloudron_get_invite_link(user_id) + subject, text, html = gift_welcome_email(name, setup_url) + send_email(email, subject, text, html) + touch_welcome_sent(email) + + # Guests receive the newsletter (same pattern as members) — and nothing + # else: no Loomio/Matrix sync, no docs-RAG group. + await listmonk_sync(email, subscribe=True) + + 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')", + (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) + 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). + + 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 + 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 + 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 + 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, + held-credit grants). + """ + conn = get_db() + row = conn.execute( + "SELECT cloudron_user_id, anchor_day FROM members WHERE email = ?", (email,) + ).fetchone() + conn.close() + if not row: + raise HTTPException(404, f"No portal row for {email}") + user_id = row[0] + + # 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 + # simply stay in credit_balance. anchor_day is untouched: their join + # day is the day the gift 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 = ?", + (MEMBER_BUDGET, slug, slug, email), + ) + conn.commit() + conn.close() + + # 3. Lift the LiteLLM cap to allowance + credits and pin the reset to + # their anchor day, exactly as the webhook does for any member. + await sync_team_budget_from_balance(email) + try: + team_id = await litellm_team_id_for_email(email) + if team_id: + 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) + + # 4. Full member onboarding — the pieces the gift 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) + await listmonk_sync(email, subscribe=True) + try: + conn = get_db() + granted = grant_held_credits(conn, email, slug) + conn.close() + if granted > 0: + await sync_team_budget_from_balance(email) + logger.info("Gift 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) + await sync_loomio_memberships() + await sync_matrix_space() + + # 5. Congratulations email (include the setup link only if they never + # activated — a 409 from invite_link means they did). + setup_url = None + try: + if not await cloudron_is_activated(user_id): + 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) + 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'", + (email,)) + conn.commit() + conn.close() + logger.info("Converted GIFT account %s to member (slug=%s)", email, slug) + return user_id + + +async def reconcile_gift_lifecycles() -> dict: + """Lapse gift 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; + * 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 + which rule ended it ('expired' | 'depleted'). + + Returns {expired, depleted} counts; never raises past a logged warning. + """ + expired = 0 + depleted = 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'" + ).fetchall() + conn.close() + now = datetime.now(timezone.utc) + for email, user_id, credits, balance, expires_at in rows: + try: + allowance = float(balance) if balance is not None else 0.0 + credits = float(credits or 0.0) + reason = None + if expires_at: + exp = datetime.fromisoformat(str(expires_at)) + if exp.tzinfo is None: + exp = exp.replace(tzinfo=timezone.utc) + if now >= exp: + reason = "expired" + if reason is None: + team_id = await litellm_team_id_for_email(email) + spend = None + if team_id: + team = get_team_budget_from_db(team_id) + if team: + spend = team.get("spend") + if spend is not None: + eff = compute_max_budget(allowance, credits, float(spend)) + if eff["credits_remaining"] <= 0.0: + reason = "depleted" + if reason is None: + continue + if INACTIVE_GROUP_ID and user_id: + await cloudron_set_group(user_id, INACTIVE_GROUP_ID) + deactivate_member(email) + await revoke_member_litellm_access(email) + await listmonk_sync(email, subscribe=False) + conn = get_db() + conn.execute( + "UPDATE gifts SET status = ? WHERE recipient_email = ? AND status = 'active'", + (reason, email), + ) + conn.commit() + conn.close() + if reason == "expired": + expired += 1 + else: + depleted += 1 + logger.info("Gift lifecycle: %s deactivated (%s)", email, reason) + except Exception as e: + logger.warning("Gift lifecycle: failed for %s: %s", email, e) + return {"expired": expired, "depleted": depleted} + + +async def litellm_get_or_create_team(email: str, budget: float, + budget_duration: str | None = "30d") -> str: """Return the team_id for a member's budget team, creating it if needed. Each member gets a LiteLLM "team" (a budget container) with a $15/30d 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 + 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). + 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 check /team/list first. @@ -2289,15 +2814,17 @@ async def litellm_get_or_create_team(email: str, budget: float) -> str: if t.get("team_alias") == alias: return t["team_id"] + payload = { + "team_alias": alias, + "max_budget": budget, + "models": MEMBER_MODELS, + } + if budget_duration: + payload["budget_duration"] = budget_duration r = await client.post( f"{LITELLM_BASE}/team/new", headers={"Authorization": f"Bearer {LITELLM_MASTER_KEY}"}, - json={ - "team_alias": alias, - "max_budget": budget, - "budget_duration": "30d", - "models": MEMBER_MODELS, - }, + json=payload, ) r.raise_for_status() return r.json()["team_id"] @@ -2802,6 +3329,21 @@ async def opencollective_webhook(request: Request, token: str): members = await fetch_members() 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 + # to the mapped account instead of minting a duplicate row. + oc_email = (member.get("email") or "").strip().lower() + if oc_email: + conn = get_db() + mapped = conn.execute( + "SELECT email FROM members WHERE oc_email = ?", (oc_email,) + ).fetchone() + conn.close() + if mapped and mapped[0] != member["email"]: + member = {**member, "email": mapped[0]} + logger.info("Webhook: payment under %s mapped to portal account %s", + oc_email, mapped[0]) if first_payment: try: await provision_member(member["email"], member["name"], member["slug"]) @@ -3181,6 +3723,89 @@ async def admin_provision(request: Request): return {"status": "provisioned", "email": email, "user_id": user_id} +@app.post("/admin/provision-gift") +@limiter.limit("20/minute") +async def admin_provision_gift(request: Request): + """Provision a GIFT account (the operator's gifting action). + + Same auth as /admin/provision (X-Admin-Token). Body: {"email": "...", + "name": "...", "inviter": ""}. Runs the gift + 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 + member. No Loomio/Matrix. + """ + _verify_admin_token(request) + + body = await request.json() + email = (body.get("email") or "").strip().lower() + name = (body.get("name") or "").strip() or email.split("@")[0] + inviter = (body.get("inviter") or body.get("inviter_email") or "").strip().lower() + if not email or "@" not in email: + raise HTTPException(400, "A valid recipient email is required") + 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) + return { + "status": "provisioned", "account_type": "gift", "email": email, + "inviter": inviter, "user_id": user_id, "budget": GIFT_BUDGET, + "expires_in_days": int(GIFT_DAYS), + } + + +@app.post("/admin/gift-convert") +@limiter.limit("20/minute") +async def admin_gift_convert(request: Request): + """Convert a gift 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 + under that address. Omitting oc_email converts on the account's own email + without an OC lookup (the operator asserts the membership exists; the row + is then matched by its own email as usual). + """ + _verify_admin_token(request) + + body = await request.json() + 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") + 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)") + + name, slug = "", "" + if oc_email: + rec = next((m for m in await fetch_members() + if (m.get("email") or "").strip().lower() == oc_email), None) + if not rec: + raise HTTPException(404, f"No Open Collective member found under {oc_email}") + name = rec.get("name") or "" + slug = rec.get("slug") or "" + conn = get_db() + conn.execute("UPDATE members SET oc_email = ? WHERE email = ?", (oc_email, email)) + conn.commit() + conn.close() + + user_id = await convert_gift_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; " + "anchor day (join day) kept"), + } + + @app.post("/admin/org-link") @limiter.limit("20/minute") async def admin_org_link(request: Request): @@ -3524,8 +4149,20 @@ async def admin_overview(request: Request): conn = get_db() rows = conn.execute( - "SELECT email, active, balance, cloudron_user_id, org_slug, matrix_mxid FROM members ORDER BY email" + "SELECT email, active, balance, cloudron_user_id, org_slug, matrix_mxid, " + "account_type, oc_email, gift_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] = {} + 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)" + ).fetchall(): + gift_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) conn.close() # Fetch Cloudron users once to map user_id → username + inviteAccepted. @@ -3592,7 +4229,7 @@ async def admin_overview(request: Request): total_all_time = 0.0 operator_spend = 0.0 operator_all_time = 0.0 - for email, active, balance, user_id, org_slug, matrix_mxid in rows: + for email, active, balance, user_id, org_slug, matrix_mxid, acct_type, oc_email, gift_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)) @@ -3629,7 +4266,14 @@ async def admin_overview(request: Request): "remaining": max(eff["max_budget"] - spend, 0.0), "reset_at": team.get("budget_reset_at"), "cloudron_user_id": user_id, + "account_type": acct_type or "member", + "oc_email": oc_email or None, + "gift_expires_at": gift_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 email.lower() in OPERATOR_EMAILS: # Operator accounts: surfaced under a separate "admin" category in # the panel, excluded from member counts and aggregates (their @@ -4341,6 +4985,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 _first_login_sync_inflight: return # a sync is already running; it covers every pending member loop = asyncio.get_running_loop() @@ -4451,6 +5097,10 @@ _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): + # 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") return {"matrix_mxid": get_member_matrix_mxid(email), "local_mxid": local_mxid_for_email(email)} @@ -4469,6 +5119,10 @@ 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): + # 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") body = await request.json() mxid = (body.get("matrix_mxid") or "").strip() if mxid and not _MXID_RE.match(mxid): @@ -4615,6 +5269,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict: key_spend = [] return { "email": email, + "guest": is_gift_account(email), "balance": balance, "allowance": allowance, "credits": credits, @@ -4691,6 +5346,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict: return { "email": email, + "guest": is_gift_account(email), "balance": balance, "allowance": allowance, "credits": credits, @@ -4803,14 +5459,40 @@ 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 members (from our DB). + # Currently provisioned accounts (from our DB), with their type — the gift + # marker drives both the conversion trigger and the deactivation skip. conn = get_db() - rows = conn.execute("SELECT email, cloudron_user_id FROM members WHERE active = 1").fetchall() + rows = conn.execute( + "SELECT email, cloudron_user_id, account_type FROM members WHERE active = 1" + ).fetchall() conn.close() - provisioned = {r[0]: r[1] for r in rows} + provisioned = { + r[0]: {"user_id": r[1], "account_type": (r[2] or "member")} + for r in rows + } + + # Members whose contribution arrives under a DIFFERENT OC email (set by + # POST /admin/gift-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() + oc_rows = conn.execute( + "SELECT email, oc_email FROM members WHERE oc_email IS NOT NULL AND oc_email != ''" + ).fetchall() + conn.close() + for row_email, oc in oc_rows: + if (oc or "").strip().lower() in active_emails: + active_emails.add(row_email) + if row_email not in active_by_email: + active_by_email[row_email] = { + "email": row_email, "name": row_email.split("@")[0], + "slug": "", "role": "BACKER", + } + logger.info("Sweep: %s active via OC email %s", row_email, oc) provisioned_count = 0 deactivated_count = 0 + converted_count = 0 # 0. Organization-backed memberships: dues paid by an OC Organization. # Linked accounts (members.org_slug) stay active while their org holds a @@ -4845,20 +5527,45 @@ 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. + # 1. Provision missing members — and CONVERT gift 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. for m in active: email = m["email"] - if email not in provisioned: + entry = provisioned.get(email) + if entry is None: try: await provision_member(email, m["name"], m["slug"]) provisioned_count += 1 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": + try: + await provision_member(email, m["name"], m["slug"]) + converted_count += 1 + logger.info("Sweep: converted gift account %s to member", email) + except Exception as e: + logger.warning("Sweep: failed to convert gift %s: %s", email, e) + + # 1b. Gift lifecycles: time-box expiry + spent-out gifts. A gift 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() + except Exception as e: + logger.warning("Sweep: gift lifecycle pass failed (non-fatal): %s", e) + gift_counts = {"expired": 0, "depleted": 0} # 2. Deactivate lapsed members (but never manual/founder members, who have - # no OC membership to lapse). - for email, user_id in provisioned.items(): + # no OC membership to lapse, and never GIFT accounts — a gift 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": + continue + user_id = info["user_id"] if email not in active_emails and email not in MANUAL_MEMBERS: try: if INACTIVE_GROUP_ID and user_id: @@ -4879,13 +5586,18 @@ async def reconcile_memberships() -> dict: reinvited_count = 0 conn = get_db() reinvite_rows = conn.execute( - "SELECT email, cloudron_user_id, welcome_sent_at FROM members WHERE active = 1" + "SELECT email, cloudron_user_id, welcome_sent_at, account_type FROM members WHERE active = 1" ).fetchall() conn.close() now = datetime.now(timezone.utc) - for email, user_id, sent_at in reinvite_rows: + 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 + # here would move the user into the members group. + continue # Skip if already activated. try: if await cloudron_is_activated(user_id): @@ -4926,6 +5638,9 @@ async def reconcile_memberships() -> dict: "provisioned": provisioned_count, "deactivated": deactivated_count, "reinvited": reinvited_count, + "converted": converted_count, + "gifts_expired": gift_counts.get("expired", 0), + "gifts_depleted": gift_counts.get("depleted", 0), "newsletter_removed": newsletter.get("removed", 0), } @@ -5374,7 +6089,8 @@ async def reconcile_allowances(send: bool = False) -> dict: cols = {r[1] for r in conn.execute("PRAGMA table_info(members)")} extra = ", welcome_sent_at" if "welcome_sent_at" in cols else "" rows = conn.execute( - f"SELECT email, slug, anchor_day, org_slug{extra} FROM members WHERE active = 1" + f"SELECT email, slug, anchor_day, org_slug, account_type, oc_email{extra} " + "FROM members WHERE active = 1" ).fetchall() now = datetime.now(timezone.utc) @@ -5393,8 +6109,16 @@ async def reconcile_allowances(send: bool = False) -> dict: slug = row[1] or "" anchor_day = row[2] org_slug = row[3] - welcome_sent = row[4] if len(row) > 4 else None + acct_type = row[4] or "member" + 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 + # renewal decision, no reminder, ever. + counts["skipped"] += 1 + continue if email.lower() in MANUAL_MEMBERS: counts["skipped"] += 1 continue @@ -5402,6 +6126,9 @@ async def reconcile_allowances(send: bool = False) -> dict: counts["skipped"] += 1 # dues paid by an OC Organization continue rec = index.get(email.strip().lower()) + if rec is None and oc_email: + # Contribution under a different OC email (gift-convert fallback). + rec = index.get(oc_email) if rec and rec.get("role") == "ADMIN": counts["skipped"] += 1 # the co-op's own account continue @@ -6260,7 +6987,8 @@ async def budget_notice_sweep(send: bool = False) -> dict: # back to the email local part produced "Hi n," for the operator, which is how this was # caught. Prefer the username; say "there" rather than inventing a name. ident = "slug" if "slug" in cols else None - sel = "SELECT email" + (f", {ident}" if ident else "") + " FROM members WHERE active = 1" + sel = ("SELECT email" + (f", {ident}" if ident else "") + ", account_type" + " FROM members WHERE active = 1") rows = conn.execute(sel).fetchall() pack = credit_pack_url() @@ -6268,6 +6996,13 @@ async def budget_notice_sweep(send: bool = False) -> dict: for row in rows: 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 + # sweep deactivates it); member low-balance mail about buying + # credit packs is not for guests. + skipped += 1 + continue team_id = await litellm_team_id_for_email(email) if not team_id: skipped += 1 diff --git a/metrics_snapshot.py b/metrics_snapshot.py index f0030be..865eb9b 100644 --- a/metrics_snapshot.py +++ b/metrics_snapshot.py @@ -207,13 +207,21 @@ 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 — + counting them would move the growth curve the co-op publishes. """ conn = connect() try: - rows = conn.execute("SELECT email, active, welcome_sent_at FROM members").fetchall() + cols = {r[1] for r in conn.execute("PRAGMA table_info(members)").fetchall()} + sel = "SELECT email, active, welcome_sent_at" + ( + ", account_type" if "account_type" in cols else "") + " FROM members" + has_acct = "account_type" in cols + rows = conn.execute(sel).fetchall() finally: conn.close() - real = [r for r in rows if (r[0] or "").strip().lower() not in OPERATOR_EMAILS] + real = [r for r in rows + if (r[0] or "").strip().lower() not in OPERATOR_EMAILS + and not (has_acct and len(r) > 3 and (r[3] or "") == "gift")] return { "active": sum(1 for r in real if r[1]), "total": len(real), diff --git a/tests/test_gift_lifecycle.py b/tests/test_gift_lifecycle.py new file mode 100644 index 0000000..881fd3b --- /dev/null +++ b/tests/test_gift_lifecycle.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +"""Gift-account lifecycle tests — structurally isolated from live services. + +WHY THIS EXISTS + Gift accounts (operator feature, 2026-11-08) touch money ($5 of credits), + Cloudron groups and email. Every path proven here runs against a FIXTURE + database with the network layer REPLACED BY A RAISING GUARD: any code path + that tries to reach Cloudron, LiteLLM, OC, Listmonk, Loomio, Matrix or SMTP + outside the stubs fails the test loudly instead of acting on live systems. + + GUARDS (abuse protection — one gift per inviter per 30d, one per recipient) + 1. An inviter who is not an active member is refused. + 2. A SECOND gift by the same inviter within the window is refused. + 3. A recipient who already received a gift (ledger) or already has a + portal row is refused. + PROVISION + 4. The full gift pipeline marks the row (account_type='gift', balance 0, + credit_balance 5, gift_expires_at set, anchor day kept), records + inviter → recipient in the gifts ledger, subscribes the newsletter, + and sends the gift welcome email — no Loomio/Matrix calls. + CONVERT (guest → member) + 5. Group moves guests → members; allowance set to MEMBER_BUDGET; the + unspent gift credit carries; the cap lifts to allowance + credits + (15 + 5); the anchor day is KEPT; the congrats email goes out; the + gifts-ledger row becomes 'converted'; Loomio + Matrix syncs fire. + LIFECYCLE (sweep pass) + 6. An EXPIRED gift (past gift_expires_at, credits remaining) is + deactivated by the sweep: row active=0, group → inactive, budget + zeroed, newsletter unsubscribed, ledger status 'expired'. + 7. A DEPLETED gift (spend reached the credits) is deactivated likewise, + status 'depleted'. + 8. A healthy gift (not expired, credits left) is left untouched. + +Runnable: python3 tests/test_gift_lifecycle.py (from the repo root) +""" +import asyncio +import base64 +import os +import sys +import tempfile +from datetime import datetime, timedelta, timezone + +os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db") +os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode() +os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests") +os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members") +os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive") +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import app.main as m # noqa: E402 + +m.DB_PATH = os.environ["DB_PATH"] + +results = [] + + +def check(name, ok, detail=""): + results.append((name, bool(ok), detail)) + print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else "")) + + +class _NoNetwork: + """Guard: ANY httpx client construction inside the test is a failure.""" + + def __init__(self, *a, **k): + raise AssertionError("live network attempted during fixture test") + + def __call__(self, *a, **k): # pragma: no cover + raise AssertionError("live network attempted during fixture test") + + +m.httpx.AsyncClient = _NoNetwork + +# --- recorders -------------------------------------------------------------- # +calls = {"group": [], "budget": [], "pin": [], "email": [], "listmonk": [], + "loomio": 0, "matrix": 0, "revoke": [], "owui": [], "subscribe": []} + + +async def rec_group(user_id, group_id=None): + calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID)) + + +async def rec_budget(team_id, budget): + calls["budget"].append((team_id, round(float(budget), 2))) + + +async def rec_pin(team_id, reset_at): + calls["pin"].append((team_id, str(reset_at))) + + +def rec_email(to, subject, text_body, html_body=None): + calls["email"].append((to, subject)) + + +async def rec_listmonk(email, subscribe): + calls["listmonk"].append((email, bool(subscribe))) + + +async def rec_loomio(): + calls["loomio"] += 1 + + +async def rec_matrix(): + calls["matrix"] += 1 + + +async def rec_revoke(email): + calls["revoke"].append(email) + return True + + +async def rec_owui(uid): + calls["owui"].append(uid) + return True + + +CALL_KEYS = ("group", "budget", "pin", "email", "listmonk", "loomio", "matrix", + "revoke", "owui", "subscribe") + + +def reset_calls(): + for k in CALL_KEYS: + calls[k] = 0 if k in ("loomio", "matrix") else [] + + +TEAM_SPEND = {} # team_id -> cycle spend (default 0.0) + + +def fake_team_db(team_id): + return {"max_budget": None, "spend": TEAM_SPEND.get(team_id, 0.0), + "budget_reset_at": None} + + +async def fake_team_id(email): + return "team-" + email + + +async def fake_get_or_create_team(email, budget, budget_duration="30d"): + return "team-fixture" + + +async def fake_create_key(email, budget, team_id): + return "sk-fixture-key" + + +async def fake_user_create(email, name): + return "uid-fixture" + + +async def fake_invite_link(user_id): + return "https://my.example/setupaccount.html?inviteToken=x" + + +async def fake_activated(user_id): + return False + + +m.cloudron_set_group = rec_group +m.cloudron_set_active = rec_group # same signature (uid, bool); recorded nowhere critical +m.cloudron_create_user = fake_user_create +m.cloudron_get_invite_link = fake_invite_link +m.cloudron_is_activated = fake_activated +m.litellm_get_or_create_team = fake_get_or_create_team +m.litellm_create_key = fake_create_key +m.litellm_team_id_for_email = fake_team_id +m.litellm_update_team_budget = rec_budget +m.litellm_pin_reset_date = rec_pin +m.get_team_budget_from_db = fake_team_db +m.send_email = rec_email +m.listmonk_sync = rec_listmonk +m.sync_loomio_memberships = rec_loomio +m.sync_matrix_space = rec_matrix +m.revoke_member_litellm_access = rec_revoke +m.owui_add_to_members_group = rec_owui + + +def seed_member(conn, email, account_type="member", active=1, balance=None, + credits=None, anchor=None, expires=None, slug=""): + conn.execute( + "INSERT INTO members (email, key_token, cloudron_user_id, slug, active, " + "balance, credit_balance, account_type, anchor_day, gift_expires_at) " + "VALUES (?, 'enc', 'uid-' || ?, ?, ?, ?, ?, ?, ?, ?)", + (email, email, slug, active, + balance if balance is not None else m.MEMBER_BUDGET, + credits if credits is not None else 0.0, + account_type, anchor, expires), + ) + + +def row_of(conn, email, col): + return conn.execute(f"SELECT {col} FROM members WHERE email = ?", (email,)).fetchone()[0] + + +def main(): + m.get_db().close() # create + migrate the fixture schema + conn = m.get_db() + m._ensure_allowance_tables(conn) # anchor_day column (as production does) + conn.close() + inviter = "member-one@x.org" + + # --- 1. inviter must be an active member ------------------------------- + conn = m.get_db() + seed_member(conn, inviter, active=1) + conn.commit() + conn.close() + conn = m.get_db() + check("guard: non-member inviter refused", + m.gift_provision_guard(conn, "stranger@x.org", "friend@x.org") is not None) + check("guard: active member inviter allowed", + m.gift_provision_guard(conn, inviter, "friend@x.org") is None) + # --- 2. one gift per inviter per 30 days ------------------------------- + conn.execute( + "INSERT INTO gifts (inviter_email, recipient_email, created_at, status) " + "VALUES (?, 'friend@x.org', datetime('now'), 'active')", (inviter,)) + conn.commit() + refusal = m.gift_provision_guard(conn, inviter, "friend2@x.org") + check("guard: second gift within 30 days refused", refusal is not None and "30 days" in refusal, + str(refusal)) + # backdate the ledger row: outside the window the inviter may gift again + conn.execute("UPDATE gifts SET created_at = datetime('now', '-31 days')") + check("guard: gift allowed again after the window", + m.gift_provision_guard(conn, inviter, "friend2@x.org") is None) + # --- 3. one gift per recipient ever ------------------------------------ + conn.execute("UPDATE gifts SET recipient_email = 'friend2@x.org'") + conn.commit() + refusal = m.gift_provision_guard(conn, inviter, "friend2@x.org") + check("guard: recipient already in ledger refused", refusal is not None, str(refusal)) + seed_member(conn, "existing@x.org", account_type="member", active=1) + conn.commit() + check("guard: existing member as recipient refused", + m.gift_provision_guard(conn, inviter, "existing@x.org") is not None) + conn.close() + + # --- 4. the full gift pipeline (provision_gift_member) ------------------ + reset_calls() + asyncio.run(m.provision_gift_member("gifted@x.org", "Gifted Friend", inviter)) + conn = m.get_db() + check("provision: row marked gift", row_of(conn, "gifted@x.org", "account_type") == "gift") + check("provision: allowance balance 0", row_of(conn, "gifted@x.org", "balance") == 0.0) + check("provision: $5 credit", row_of(conn, "gifted@x.org", "credit_balance") == 5.0) + check("provision: gift_expires_at set", bool(row_of(conn, "gifted@x.org", "gift_expires_at"))) + check("provision: group = guests group", + calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"])) + check("provision: cap set to 5.00 (one-time)", + (calls["budget"] and calls["budget"][0][1] == 5.0), str(calls["budget"])) + check("provision: welcome email sent", + any("gifted access" in s for _, s in calls["email"]), str(calls["email"])) + check("provision: newsletter subscribed", + ("gifted@x.org", True) in calls["listmonk"], str(calls["listmonk"])) + check("provision: NO loomio/matrix calls", calls["loomio"] == 0 and calls["matrix"] == 0) + g = conn.execute("SELECT inviter_email, recipient_email, status FROM gifts " + "WHERE recipient_email = 'gifted@x.org'").fetchone() + check("provision: gifts ledger records inviter→recipient", + bool(g) and g[0] == inviter and g[1] == "gifted@x.org" and g[2] == "active", str(g)) + conn.close() + + # --- 5. conversion (guest → member) ------------------------------------- + reset_calls() + anchor_before = row_of(m.get_db(), "gifted@x.org", "anchor_day") + asyncio.run(m.convert_gift_to_member("gifted@x.org", "Gifted Friend", "giftedfriend")) + conn = m.get_db() + check("convert: account_type back to member", + row_of(conn, "gifted@x.org", "account_type") == "member") + check("convert: allowance lifted to MEMBER_BUDGET", + row_of(conn, "gifted@x.org", "balance") == m.MEMBER_BUDGET) + check("convert: unspent gift credit carried", + row_of(conn, "gifted@x.org", "credit_balance") == 5.0) + check("convert: group moved to members", + calls["group"] and calls["group"][0][1] == m.MEMBERS_GROUP_ID, str(calls["group"])) + check("convert: cap lifted to 20.00 (15 + 5 credits)", + (calls["budget"] and calls["budget"][0][1] == m.MEMBER_BUDGET + 5.0), str(calls["budget"])) + check("convert: anchor day kept", row_of(conn, "gifted@x.org", "anchor_day") == anchor_before) + check("convert: congrats email sent", + any("member now" in s for _, s in calls["email"]), str(calls["email"])) + check("convert: Loomio + Matrix syncs fired", calls["loomio"] == 1 and calls["matrix"] == 1) + check("convert: gifts ledger status converted", + conn.execute("SELECT status FROM gifts WHERE recipient_email='gifted@x.org'" + ).fetchone()[0] == "converted") + check("convert: expiry cleared", row_of(conn, "gifted@x.org", "gift_expires_at") is None) + conn.close() + + # --- 6/7/8. lifecycle sweep: expired / depleted / healthy --------------- + past = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat() + future = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat() + conn = m.get_db() + seed_member(conn, "expired@x.org", account_type="gift", active=1, balance=0.0, + credits=5.0, anchor=8, expires=past) + seed_member(conn, "healthy@x.org", account_type="gift", active=1, balance=0.0, + credits=5.0, anchor=8, expires=future) + seed_member(conn, "depleted@x.org", account_type="gift", active=1, balance=0.0, + credits=5.0, anchor=8, expires=future) + for e in ("expired@x.org", "healthy@x.org", "depleted@x.org"): + conn.execute("INSERT INTO gifts (inviter_email, recipient_email, gift_expires_at, status) " + "VALUES (?, ?, ?, 'active')", (inviter, e, future)) + conn.commit() + conn.close() + + TEAM_SPEND.clear() # healthy + expired have unspent credits + reset_calls() + out = asyncio.run(m.reconcile_gift_lifecycles()) + conn = m.get_db() + check("lifecycle: expired gift deactivated by the sweep", + row_of(conn, "expired@x.org", "active") == 0) + check("lifecycle: expired gift group → inactive", + any(e == "uid-expired@x.org" and g == m.INACTIVE_GROUP_ID + for e, g in calls["group"]), str(calls["group"])) + check("lifecycle: expired gift budget zeroed (revoke path called)", + "expired@x.org" in calls["revoke"], str(calls["revoke"])) + check("lifecycle: expired gift unsubscribed", + ("expired@x.org", False) in calls["listmonk"], str(calls["listmonk"])) + check("lifecycle: ledger status 'expired'", + conn.execute("SELECT status FROM gifts WHERE recipient_email='expired@x.org'" + ).fetchone()[0] == "expired") + check("lifecycle: healthy gift untouched", + row_of(conn, "healthy@x.org", "active") == 1 and + not any(e == "uid-healthy@x.org" for e, _ in calls["group"])) + check("lifecycle: counts report expired=1 depleted=0", + out.get("expired") == 1 and out.get("depleted") == 0, str(out)) + conn.close() + + TEAM_SPEND["team-depleted@x.org"] = 5.5 # depleted: spend reached the credits + reset_calls() + out = asyncio.run(m.reconcile_gift_lifecycles()) + conn = m.get_db() + check("lifecycle: depleted gift deactivated", + row_of(conn, "depleted@x.org", "active") == 0) + check("lifecycle: depleted ledger status", + conn.execute("SELECT status FROM gifts WHERE recipient_email='depleted@x.org'" + ).fetchone()[0] == "depleted") + check("lifecycle: healthy gift STILL untouched on second pass", + row_of(conn, "healthy@x.org", "active") == 1) + check("lifecycle: counts report depleted=1", out.get("depleted") == 1, str(out)) + conn.close() + + failed = [r for r in results if not r[1]] + print(f"\n{len(results) - len(failed)}/{len(results)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main())