gift emails: invitation at gift time + once-only reaching-limits notice

- gift_welcome_email becomes gift_invitation_email: the ONE email a gift
  sends (the invitation and the guest welcome merged, not two mails at
  once). Subject 'You've been invited to the Inference Cooperative'; names
  the inviter (member slug), the $5 credits, the setup link, the
  Become-a-member button on BECOME_MEMBER_URL. Uses the shared
  PINE_LOGO_SVG instead of an inline copy.
- reaching-limits email (gift_limits_email, 'Your guest access has ended —
  become a member to continue') wired into the sweep's gift deactivation:
  sent once per guest, gated by a gift_lapse_notices sent-state row (same
  pattern as mark_shortfall_notice_sent). Says the access ended, the
  account and data are kept, and membership ($15/mo via Open Collective)
  restores a full monthly allowance + community spaces.
- catch-up pass in reconcile_gift_lifecycles: guests deactivated before the
  email shipped (or a failed send) get exactly one notice on a later sweep;
  converted guests are excluded by account_type.
- sweep summary now reports gift_lapse_notices.
- test_gift_lifecycle: invitation-subject assertion; send_email stub
  returns True (the bool is the gate's contract); new once-only + catch-up
  + healthy-untouched checks. 43/43.
This commit is contained in:
inference-bot committed 2026-11-08 02:22:59 +00:00
1 parent 0bc3cd65e7
commit 0b0bdaab6f
2 files changed
+263 -39

No files matched your search

+232 -35
View File
@@ -2410,28 +2410,39 @@ async def provision_member(email: str, name: str, slug: str = "") -> str:
# 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.
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.
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.
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,
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
background, white card, forest-green button, pine mark, no external
assets. No Loomio/Matrix — guests receive no member invitations.
"""
subject = "You've been gifted access to the Inference Cooperative"
subject = "You've been invited to the Inference Cooperative"
if inviter_name:
invited_line = f"{inviter_name} has invited you to the Inference Cooperative"
html_invited = f"<strong style=\"color:#2d3327;\">{inviter_name}</strong> has invited you to the <strong style=\"color:#2d3327;\">Inference Cooperative</strong>"
else:
invited_line = "A member has invited you to the Inference Cooperative"
html_invited = "A member has invited you to the <strong style=\"color:#2d3327;\">Inference Cooperative</strong>"
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"{invited_line}.\n\n"
"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"
"themselves don't expire early.\n\n"
"To accept, create your account — it takes about a minute:\n\n"
f"{setup_url}\n\n"
"If you like it, membership is $15/month: a full monthly allowance,\n"
"the co-op's forum and chat community, and a say in how it's run.\n\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"
"You're also on our low-volume newsletter — unsubscribe anytime\n"
"from any issue.\n\n"
"Questions? Just reply to this email — it reaches the co-op directly.\n\n"
"— The Inference Cooperative\n"
)
@@ -2445,27 +2456,20 @@ def gift_welcome_email(name: str, setup_url: str) -> tuple[str, str, str]:
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;">
<tr>
<td align="center" style="padding-bottom:24px;">
<svg width="56" height="56" viewBox="0 0 130 130" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<circle cx="65" cy="14" r="5" fill="#5b8c5a"/><circle cx="58" cy="30" r="6" fill="#7ab87a"/><circle cx="74" cy="30" r="4" fill="#6ba86b"/>
<circle cx="51.5" cy="46" r="6.5" fill="#5b8c5a"/><circle cx="65" cy="46" r="5" fill="#7ab87a"/><circle cx="81" cy="46" r="4" fill="#6ba86b"/>
<circle cx="44" cy="62" r="7" fill="#6ba86b"/><circle cx="61" cy="62" r="5.5" fill="#5b8c5a"/><circle cx="76" cy="62" r="4.5" fill="#7ab87a"/><circle cx="89.5" cy="62" r="3.5" fill="#6ba86b"/>
<circle cx="36.5" cy="78" r="7.5" fill="#5b8c5a"/><circle cx="54" cy="78" r="6" fill="#7ab87a"/><circle cx="70" cy="78" r="5" fill="#6ba86b"/><circle cx="84" cy="78" r="4" fill="#5b8c5a"/><circle cx="97.5" cy="78" r="3.5" fill="#7ab87a"/>
<circle cx="44" cy="94" r="6.5" fill="#6ba86b"/><circle cx="61" cy="94" r="5.5" fill="#5b8c5a"/><circle cx="76" cy="94" r="4.5" fill="#7ab87a"/><circle cx="89.5" cy="94" r="3.5" fill="#6ba86b"/>
<circle cx="51.5" cy="110" r="5.5" fill="#5b8c5a"/><circle cx="65" cy="110" r="4.5" fill="#7ab87a"/><circle cx="81" cy="110" r="3.5" fill="#6ba86b"/>
</svg>
{PINE_LOGO_SVG}
</td>
</tr>
<tr>
<td align="center" style="background:#ffffff;border:1px solid #e8e2d8;border-radius:16px;padding:40px 32px;">
<h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">You've been gifted access, {name}</h1>
<p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">A member of the <strong style="color:#2d3327;">Inference Cooperative</strong> has given you <strong style="color:#2d3327;">$5 of AI usage</strong> — the co-op's private, renewable-energy models across chat and the API.</p>
<p style="margin:0 0 24px;font-size:15px;color:#6b7a62;line-height:1.5;">Your gift lasts until the $5 of credits are used up (they don't expire early — access runs 60 days from today).</p>
<h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">You're invited, {name}</h1>
<p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">{html_invited} — a member-governed AI cooperative running open models on renewable energy.</p>
<p style="margin:0 0 24px;font-size:15px;color:#6b7a62;line-height:1.5;">Your invitation comes with <strong style="color:#2d3327;">$5 of credits</strong> for the co-op's chat and API. Access runs for {int(GIFT_DAYS)} days from today; the credits themselves don't expire early.</p>
<a href="{setup_url}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Create your account</a>
<p style="margin:14px 0 28px;font-size:13px;color:#94a08c;line-height:1.5;">This takes about a minute.</p>
<p style="margin:0 0 10px;font-size:15px;color:#2d3327;line-height:1.5;"><strong>Like it? Become a member.</strong></p>
<p style="margin:0 0 16px;font-size:14px;color:#6b7a62;line-height:1.5;">$10–20/month, sliding scale — same login, plus a monthly allowance and a say in how the co-op is run.</p>
<p style="margin:0 0 10px;font-size:15px;color:#2d3327;line-height:1.5;"><strong>If you like it, become a member.</strong></p>
<p style="margin:0 0 16px;font-size:14px;color:#6b7a62;line-height:1.5;">$15/month — a full monthly allowance, the co-op's forum and chat community, and a say in how it's run.</p>
<a href="{BECOME_MEMBER_URL}" style="display:inline-block;background:#eaf3ea;color:#2f5c30;text-decoration:none;padding:12px 30px;border-radius:10px;font-size:15px;font-weight:600;border:1px solid #cfe0cf;">Become a member</a>
<p style="margin:24px 0 0;font-size:13px;color:#94a08c;line-height:1.5;">You're also on our (low-volume) newsletter — hear what the co-op is building; unsubscribe anytime.</p>
<p style="margin:24px 0 0;font-size:13px;color:#94a08c;line-height:1.5;">You're also on our low-volume newsletter — unsubscribe anytime from any issue.</p>
</td>
</tr>
<tr>
@@ -2535,6 +2539,59 @@ 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.
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
member ($15/month via Open Collective) restores access with a full
monthly allowance and the community spaces. Same shell as the other gift
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."
else:
ended = f"The gift's {int(GIFT_DAYS)} days are up."
text = (
f"Hi {name},\n\n"
f"{ended} Your gift 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"
f"{BECOME_MEMBER_URL}\n\n"
"Questions? Just reply to this email — it reaches the co-op directly.\n\n"
"— The Inference Cooperative\n"
)
html = f"""<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin:0;padding:0;background:#faf8f5;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#faf8f5;padding:40px 16px;">
<tr><td align="center">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;">
<tr><td align="center" style="padding-bottom:24px;">
{PINE_LOGO_SVG}
</td></tr>
<tr><td align="center" style="background:#ffffff;border:1px solid #e8e2d8;border-radius:16px;padding:40px 32px;">
<h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">Your gift access has ended</h1>
<p style="margin:0 0 16px;font-size:16px;color:#6b7a62;line-height:1.5;">{ended} Your gift access to the <strong style="color:#2d3327;">Inference Cooperative</strong> has ended.</p>
<p style="margin:0 0 24px;font-size:15px;color:#6b7a62;line-height:1.5;"><strong style="color:#2d3327;">Your account and data are kept.</strong> 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.</p>
<a href="{BECOME_MEMBER_URL}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Become a member</a>
<p style="margin:24px 0 0;font-size:13px;color:#94a08c;line-height:1.5;">Questions? Reply to this email — it reaches the co-op directly.</p>
</td></tr>
<tr><td align="center" style="padding-top:24px;font-size:13px;color:#94a08c;line-height:1.6;">
<span style="color:#2d3327;">The Inference Cooperative</span> &middot; inference.coop
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>"""
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).
@@ -2545,7 +2602,8 @@ async def provision_gift_member(email: str, name: str, inviter_email: str) -> st
(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
* the gift 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;
* NO Loomio/Matrix invites, no docs-RAG members group.
@@ -2596,7 +2654,19 @@ async def provision_gift_member(email: str, name: str, inviter_email: str) -> st
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)
# Name the inviter in the invitation: their member slug (the username the
# co-op knows them by — the members table has no display-name column).
inviter_name = ""
conn = get_db()
row = conn.execute(
"SELECT slug FROM members WHERE email = ?", (inviter_email.strip().lower(),)
).fetchone()
conn.close()
if row and row[0]:
inviter_name = row[0]
# ONE email at gift 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)
send_email(email, subject, text, html)
touch_welcome_sent(email)
@@ -2715,6 +2785,86 @@ async def convert_gift_to_member(email: str, name: str, slug: str = "") -> str:
return user_id
def gift_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
records what actually left the building.
"""
conn = get_db()
_ensure_gift_notice_table(conn)
row = conn.execute(
"SELECT 1 FROM gift_lapse_notices WHERE email = ? LIMIT 1", (email,)
).fetchone()
conn.close()
return bool(row)
def mark_gift_lapse_notice_sent(email: str, reason: str) -> None:
conn = get_db()
_ensure_gift_notice_table(conn)
conn.execute(
"INSERT OR REPLACE INTO gift_lapse_notices (email, reason, sent_at)"
" VALUES (?, ?, datetime('now'))",
(email, reason),
)
conn.commit()
conn.close()
def _ensure_gift_notice_table(conn) -> None:
"""Records which guests have been told their gift 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
guest is notified at most once, ever.
"""
conn.execute(
"CREATE TABLE IF NOT EXISTS gift_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:
"""Send the reaching-limits email ONCE per guest.
Checks the sent-state row before sending and marks it only after the send
succeeded — an unmarked guest (send failed, or lapsed before this email
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):
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).
name = ""
if user_id:
try:
async with httpx.AsyncClient() as client:
users = await cloudron_fetch_all_users(client)
if users:
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)
if not name:
conn = get_db()
row = conn.execute(
"SELECT slug FROM members WHERE email = ?", (email,)
).fetchone()
conn.close()
if row and row[0]:
name = row[0]
subject, text_body, html_body = gift_limits_email(name or "there", reason)
if send_email(email, subject, text_body, html_body):
mark_gift_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.
@@ -2728,10 +2878,12 @@ async def reconcile_gift_lifecycles() -> dict:
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.
Returns {expired, depleted, lapse_notices} counts; never raises past a
logged warning.
"""
expired = 0
depleted = 0
notified = 0
conn = get_db()
rows = conn.execute(
"SELECT email, cloudron_user_id, credit_balance, balance, gift_expires_at "
@@ -2780,9 +2932,53 @@ async def reconcile_gift_lifecycles() -> dict:
else:
depleted += 1
logger.info("Gift 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):
notified += 1
except Exception as e:
logger.warning("Gift lapse notice failed for %s: %s", email, e)
except Exception as e:
logger.warning("Gift lifecycle: failed for %s: %s", email, e)
return {"expired": expired, "depleted": depleted}
# 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.
conn = get_db()
pending = conn.execute(
"SELECT email, cloudron_user_id, gift_expires_at FROM members "
"WHERE active = 0 AND account_type = 'gift'"
).fetchall()
conn.close()
for email, user_id, expires_at in pending:
if gift_lapse_notice_sent(email):
continue
try:
conn = get_db()
grow = conn.execute(
"SELECT status FROM gifts WHERE recipient_email = ? "
"ORDER BY id DESC LIMIT 1", (email,)
).fetchone()
conn.close()
reason = grow[0] if grow and grow[0] in ("expired", "depleted") else None
if reason is None:
# No ledger verdict: read the time box off the row; a row with
# no expiry was ended by its credits.
try:
exp = datetime.fromisoformat(str(expires_at)) if expires_at else None
if exp and exp.tzinfo is None:
exp = exp.replace(tzinfo=timezone.utc)
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):
notified += 1
except Exception as e:
logger.warning("Gift lapse catch-up failed for %s: %s", email, e)
return {"expired": expired, "depleted": depleted, "lapse_notices": notified}
async def litellm_get_or_create_team(email: str, budget: float,
@@ -5663,6 +5859,7 @@ async def reconcile_memberships() -> dict:
"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),
"newsletter_removed": newsletter.get("removed", 0),
}
+31 -4
View File
@@ -87,8 +87,9 @@ 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):
def rec_email(to, subject, text_body=None, html_body=None):
calls["email"].append((to, subject))
return True # send_email's contract: truthy = the send left the building
async def rec_listmonk(email, subscribe):
@@ -242,8 +243,8 @@ def main():
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: 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"]))
check("provision: NO loomio/matrix calls", calls["loomio"] == 0 and calls["matrix"] == 0)
@@ -288,9 +289,14 @@ def main():
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"):
# A guest whose gift 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,
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) "
"VALUES (?, ?, ?, 'active')", (inviter, e, future))
conn.execute("UPDATE gifts SET status = 'expired' WHERE recipient_email = 'already-gone@x.org'")
conn.commit()
conn.close()
@@ -315,6 +321,16 @@ def main():
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))
check("lifecycle: reaching-limits email sent once to the expired guest",
sum(1 for to, s in calls["email"]
if to == "expired@x.org" and "guest access has ended" in s) == 1,
str(calls["email"]))
check("lifecycle: catch-up told the pre-shutdown guest exactly once",
sum(1 for to, s in calls["email"]
if to == "already-gone@x.org" and "guest access has ended" in s) == 1,
str(calls["email"]))
check("lifecycle: notice counts in the sweep result",
out.get("lapse_notices") == 2, str(out))
conn.close()
TEAM_SPEND["team-depleted@x.org"] = 5.5 # depleted: spend reached the credits
@@ -329,6 +345,17 @@ def main():
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))
check("lifecycle: depleted guest also told once",
sum(1 for to, s in calls["email"]
if to == "depleted@x.org" and "guest access has ended" in s) == 1,
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"),
str(calls["email"]))
check("lifecycle: healthy guest never emailed",
not any(to == "healthy@x.org" for to, _ in calls["email"]), str(calls["email"]))
conn.close()
failed = [r for r in results if not r[1]]