caelum0x b851c1c74d
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
ci / node suites (push) Has been cancelled
feat(rithub): RIT-MON Team plan ($49/mo, 5 seats) + migration concierge ($149)
Same checkout/webhook pipeline as the existing Pro flow, two new plans:
- team: pdt_0Nt5QOTvyRsIS2bzPTGMN, $49/mo recurring, 5 seats (no per-seat
  enforcement yet -- same "ship the real promise, not an invented
  paywall" rule as Pro).
- concierge: pdt_0Nt5QOsTUXHh1p3KU6i8A, one-time $149, "we move your
  repos for you" migration service.

Both products created live in Dodo (same business as the existing Pro
products). bin/start.mjs resolves which plan a webhook event is about
from the product id Dodo actually sends (never a client-settable
metadata field for the grant decision), with a safe fallback that
preserves whatever plan was already on record rather than guessing
"pro" on an event with no product info (e.g. a bare cancellation).

rithub_pro.py: pro-users.json (drives the /user/settings Pro/Free
banner) now only ever contains the real recurring "pro" plan -- Team
and concierge entitlements are recorded (visible via /billing/admin)
but never render as a Pro/Free state, and concierge gets a one-time
"we'll start moving your repos" ack mail instead of the subscription
"is on" copy.

Verified live: both checkout URLs 302 to a real Dodo checkout_url
(no card entered, correct name/price rendered); both plans resolve
correctly from a hand-signed Standard Webhooks test payload against
the real product ids (admin view showed plan: "team"/"concierge",
pro_users stayed empty); test entitlement rows cleaned up after.
/pricing updated with Team as a 4th plan card and a concierge callout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:35:13 +03:00

186 lines
7.0 KiB
Python

"""Rithub Pro pass for rithub-lifecycle (RIT-MON, 2026-11-30).
rithub-billing (Dodo checkout + signed webhook) records who paid in
ENTITLEMENTS_FILE but never told anyone and never linked a payment to a
Rithub account. This pass, run every 15 minutes by the lifecycle timer:
- links each entitlement to the Rithub login whose email matches the
payer's email (case-insensitive);
- on a new/changed status, mails the customer once when Pro turns on, and
mails the owner on every change (active / revoked / on_hold);
- writes PRO_USERS_FILE ({login: status}) as the single place later
enforcement (quotas, badges, rate limits) reads from.
Idempotent: what was already announced is kept in pro.json in the state dir,
keyed by the entitlement key, so a status is never mailed twice.
"""
from __future__ import annotations
import json
import logging
import os
from typing import Any, Callable
log = logging.getLogger("rithub-lifecycle")
DEFAULT_ENTITLEMENTS_FILE = "/home/deploy/apps/rithub-billing/data/entitlements.json"
GRANTED = "active"
SendFn = Callable[[str, str, str], bool]
def _load(path: str, default: Any) -> Any:
try:
with open(path) as f:
return json.load(f)
except (FileNotFoundError, ValueError):
return default
def _save(path: str, value: Any) -> None:
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(value, f, indent=2, sort_keys=True)
os.replace(tmp, path)
def _logins_by_email(users: list[dict[str, Any]]) -> dict[str, str]:
out: dict[str, str] = {}
for user in users:
email = (user.get("email") or "").strip().lower()
login = user.get("login") or ""
if email and login:
out[email] = login
return out
PLAN_GRANTED_LINE = {
"pro": "thanks for backing rithub. pro is on for {email}{account}.",
"team": "thanks for backing rithub. your team plan (5 seats) is on for {email}{account}.",
}
PLAN_SUBJECT = {
"pro": "rithub pro is on",
"team": "rithub team is on",
}
def build_customer_mail(
email: str, login: str | None, public_base_url: str, reply_to: str, plan: str = "pro"
) -> tuple[str, str]:
account = f" (account: {login})" if login else ""
# Migration concierge is a one-time paid service, not a subscription --
# the real work (moving the repos) is a human/agent task, not something
# this pass can grant automatically. Send a short ack instead of the
# recurring-plan "is on" copy, and never add it to pro-users.json below.
if plan == "concierge":
lines = [
"hey,",
"",
f"got your migration concierge payment{account}.",
f"we'll start moving your repos and reply from this address ({reply_to}) with next steps, usually within a day.",
"",
"if there's a specific github org/account you want moved, reply here with it now so we don't have to ask.",
]
return "rithub migration concierge: payment received", "\n".join(lines) + "\n"
granted_line = PLAN_GRANTED_LINE.get(plan, PLAN_GRANTED_LINE["pro"]).format(email=email, account=account)
lines = [
"hey,",
"",
granted_line,
"",
f"priority support: reply to this email ({reply_to}) and a person answers it first.",
"new paid features (more storage, team seats) come to your account first as they ship.",
"",
]
if not login:
lines += [
"we could not find a rithub account with this email yet.",
f"sign up with {email} at {public_base_url}/user/sign_up and it links by itself.",
"",
]
lines += ["to cancel or change the plan, use the link in your dodo payments receipt."]
return PLAN_SUBJECT.get(plan, PLAN_SUBJECT["pro"]), "\n".join(lines) + "\n"
def build_owner_mail(key: str, ent: dict[str, Any], login: str | None) -> tuple[str, str]:
status = ent.get("status", "unknown")
plan = ent.get("plan") or "pro"
subject = f"rithub {plan} {status}: {ent.get('email') or key}"
lines = [
f"status: {status}",
f"email: {ent.get('email')}",
f"rithub login: {login or '(no matching account yet)'}",
f"plan: {ent.get('plan')}",
f"subscription: {ent.get('subscriptionId')}",
f"dodo customer: {ent.get('customerId')}",
f"last event: {ent.get('lastEventType')} at {ent.get('updatedAt')}",
]
return subject, "\n".join(lines) + "\n"
def run_pro_pass(
users: list[dict[str, Any]],
entitlements_file: str,
state_dir: str,
send: SendFn,
owner_email: str,
public_base_url: str,
reply_to: str,
now_ts: float,
dry_run: bool,
) -> dict[str, int]:
counts = {"entitlements": 0, "customer_mails": 0, "owner_mails": 0, "linked": 0}
ents = _load(entitlements_file, {}).get("customers", {})
if not isinstance(ents, dict):
log.error("pro: %s has no customers map, skipping", entitlements_file)
return counts
counts["entitlements"] = len(ents)
state_file = os.path.join(state_dir, "pro.json")
state = _load(state_file, {})
by_email = _logins_by_email(users)
pro_users: dict[str, str] = {}
for key, ent in ents.items():
email = (ent.get("email") or "").strip().lower()
status = ent.get("status") or "unknown"
plan = ent.get("plan") or "pro"
login = by_email.get(email) if email else None
if login:
counts["linked"] += 1
# pro-users.json is read by the /user/settings Pro/Free banner
# (RIT-MON) -- only the real recurring Pro plan belongs here.
# Team is a separate plan (no banner wired for it yet, tracked
# honestly via entitlements.json/admin instead) and concierge is
# a one-time service purchase, never a Pro/Free state.
if plan == "pro":
pro_users[login] = status
entry = dict(state.get(key, {}))
if entry.get("announced_status") != status:
if dry_run:
log.info("pro: WOULD announce key=%s status=%s login=%s plan=%s", key, status, login, plan)
else:
subject, body = build_owner_mail(key, ent, login)
if send(owner_email, subject, body):
counts["owner_mails"] += 1
customer_ok = True
if status == GRANTED and not entry.get("customer_mailed_at") and email:
subject, body = build_customer_mail(email, login, public_base_url, reply_to, plan)
customer_ok = send(email, subject, body)
if customer_ok:
entry["customer_mailed_at"] = int(now_ts)
counts["customer_mails"] += 1
if customer_ok:
entry["announced_status"] = status
entry["announced_at"] = int(now_ts)
entry["login"] = login
state[key] = entry
if not dry_run:
_save(state_file, state)
_save(os.path.join(state_dir, "pro-users.json"), pro_users)
return counts