mirror of
https://github.com/bitbaum/heidi.git
synced 2026-12-05 07:19:46 +01:00
* CTAs speak as a command to the learner: «Frag Heidi» Buttons and links that start an action are imperatives addressed to the learner (owner's decision), so the brand phrase, the domain and the buttons say the same thing: «Frag Heidi» (was «Heidi fragen»), «Frag Heidi, warum», «Entdecke die Situationen», «Fang an», «Probier es aus», «Erstell dein Gratis-Konto», and the home, chat, plans, warm-up, practice, play, groups, languages and organisations doors alike. du-form in German (Sie kept on the organisations page, which addresses organisations as Sie), tu in fr/it, ti in rm, ты in ru; English only «Create your free account». Swiss German changes only where the imperative has a source: «Frag d Heidi» (verb «frage» in the gsw-zh pack; imperative «frag» in Wiktionary's Zurich conjugation table), «Lueg … aa» and «Mach …» (the pack's imperative topic). Other gsw labels keep their infinitives. Single-word tab-like labels («Üben», «Starten») and status texts unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * gsw: «Frög d Heidi» (Zurich imperative of fröge) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Heidi Max next to Heidi Plus; owner payment settings and «Stripe einrichten» - paykit 0.7.0. One tier answer (lib/pay/tier.ts: free | plus | max from the entitlement's plan id; the one-time pass counts as plus), read by the caps (capsFor, HEIDI_CAP_MAX_*; Max defaults to 3x Plus), the model route (chainFor: HEIDI_MAX_MODELS first, else exactly the Plus route) and the Rückblick (REVIEW_EVERY_DAYS_BY_TIER: max 7, plus/free 30). - /plans: Free | Plus | Max | own key | Organisations on PlanPicker, Max priced from HEIDI_MAX_* (no price in code); review step per plan; without payment switched on the review says so instead of a pay button; a Stripe TEST key shows «Testmodus». - Back office Geld -> «Zahlungen» (/manage/money/payments): eight prices, sales, Stripe key and webhook secret in pay_settings (migration 0035), secrets sealed and never sent to the page; stored value over env over off. - «Stripe einrichten»: makes or finds Products/Prices, the customer-portal configuration (cancel, card, switch Plus/Max) and the webhook endpoint, storing its signing secret; idempotent, one result per step. - Webhook reads the plan from the subscription's Price, so portal switches move the tier. - Words in all seven dictionaries; changelog 2026-12-03. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r * Paid allowances never below the tier below; Plus and Max cards list them - caps.ts: every paid allowance is at least the tier below (daily with 0 as no count; Plus dictation per 30 days at least free's daily x 30). Plus daily defaults to 3x free (300), Max to 3x Plus (900); voice 1200/3600 s. - plan-cards.ts: one paidBenefits shape for Plus and Max from capsFor: questions a day, Heidi's voice minutes, dictations per 30 days, the Rückblick rhythm, then Max's two «bald» lines, then «Alles aus …». The free card says Heidi's own voice comes with Plus and Max. - All seven dictionaries; changelog lines for the fix. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r --------- Co-authored-by: Claude <noreply@anthropic.com>
474 lines
22 KiB
TypeScript
474 lines
22 KiB
TypeScript
import { and, eq, isNull } from "drizzle-orm";
|
|
import {
|
|
applySubscriptionEvent,
|
|
isActive,
|
|
subscriptionAccessUntil,
|
|
subscriptionStanding,
|
|
type SubscriptionEvent,
|
|
type SubscriptionPlan,
|
|
type SubscriptionRecord,
|
|
type SubscriptionStanding,
|
|
type SubscriptionStatus,
|
|
} from "@bitbaum/paykit/checkout";
|
|
import { subscriptionPricing, type SubscriptionPricing } from "@bitbaum/paykit/plans";
|
|
import { StripeError, stripeBilling, type StripeBilling } from "@bitbaum/paykit/stripe";
|
|
import {
|
|
isSubscriptionPlan,
|
|
stripeKeyMode,
|
|
subscriptionConfig,
|
|
SUBSCRIPTION_TIERS,
|
|
tierPlans,
|
|
type SubscriptionConfig,
|
|
type SubscriptionPlanId,
|
|
type SubscriptionTier,
|
|
} from "../config/payments.ts";
|
|
import { salesEnabled } from "../config/sales.ts";
|
|
import { SITE_URL } from "../config/site.ts";
|
|
import { db, dbConfigured } from "../db/index.ts";
|
|
import { entitlements, payCheckouts, payEvents, paySubscriptions } from "../db/schema.ts";
|
|
import { countPlans } from "./plans-count.ts";
|
|
import { payEnv, STRIPE_PORTAL_SETTING, STRIPE_PRICE_SETTING } from "./settings.ts";
|
|
import { planOfPrice, readPriceSetting, stripeCall } from "./stripe-setup.ts";
|
|
import { entitlementOf, ownCheckout, saveCheckout, type CheckoutRow } from "./store.ts";
|
|
import { tierOfPlan } from "./tier.ts";
|
|
|
|
/**
|
|
* Heidi Plus and Heidi Max: the subscriptions. Everything that talks to
|
|
* Stripe or decides what an event means is `@bitbaum/paykit`; this file joins
|
|
* it to Heidi's configuration (the owner's settings over the environment,
|
|
* `payEnv`) and database.
|
|
*
|
|
* WHAT A SUBSCRIPTION GIVES is its tier, through the same `entitlements` row
|
|
* a one-time pass writes: the row's plan is the subscription's plan
|
|
* (`plus-month`, `max-year`, …), and `lib/pay/tier.ts` reads the tier from
|
|
* it, so every cap, route and cadence knows. The row's end is moved to the
|
|
* end of the paid period each time Stripe says a period was paid, and never
|
|
* moved back: a cancelled or failed subscription keeps what was paid for,
|
|
* and simply is not extended. An upgrade or a downgrade in Stripe's portal
|
|
* arrives as `customer.subscription.updated` with the new Price, whose plan
|
|
* `planOfPrice` reads; the row's plan follows it.
|
|
*
|
|
* WHO A SUBSCRIPTION BELONGS TO is the checkout Heidi stored when it sent the
|
|
* person to Stripe, as for a pass: Stripe is told nothing about the Heidi
|
|
* account (`sendReference: false`). After that, the subscription id stored
|
|
* in `pay_subscriptions` is the link.
|
|
*/
|
|
|
|
export const PLUS_PROVIDER = "stripe";
|
|
|
|
type Env = Record<string, string | undefined>;
|
|
|
|
/** The languages Stripe's pages speak among Heidi's (Checkout and the portal take the same codes). */
|
|
const STRIPE_LOCALES: Record<string, string> = { de: "de", gsw: "de", fr: "fr", it: "it", en: "en", ru: "ru" };
|
|
|
|
type BillingOpts = { locale?: string; productName?: (plan: SubscriptionPlan) => string; introName?: (months: number) => string };
|
|
|
|
export function billingFor(config: SubscriptionConfig, opts: BillingOpts = {}): StripeBilling {
|
|
const prefix = opts.locale ? `/${opts.locale}` : "";
|
|
const stripeLocale = opts.locale ? STRIPE_LOCALES[opts.locale] : undefined;
|
|
return stripeBilling({
|
|
secretKey: config.secretKey,
|
|
webhookSecret: config.webhookSecret,
|
|
baseUrl: config.baseUrl,
|
|
sendReference: false,
|
|
// Back to the same checkout page a pass has: it reads the session and starts the tier.
|
|
successUrl: `${SITE_URL}${prefix}/pass/checkout/{CHECKOUT_SESSION_ID}`,
|
|
cancelUrl: `${SITE_URL}${prefix}/plans`,
|
|
...(stripeLocale ? { locale: stripeLocale } : {}),
|
|
...(opts.productName ? { productName: opts.productName } : {}),
|
|
...(opts.introName ? { introName: (intro) => (opts.introName as (m: number) => string)(intro.months) } : {}),
|
|
});
|
|
}
|
|
|
|
// ── What /plans offers ─────────────────────────────────────────────────────
|
|
|
|
export type TierOffer = { tier: SubscriptionTier; plans: SubscriptionPlan[]; pricing: SubscriptionPricing };
|
|
|
|
/**
|
|
* What /plans shows for Plus and Max. `tiers` holds every tier the owner
|
|
* priced (prices only from the owner's settings or the environment);
|
|
* `payable` says whether a checkout can be opened now, and when it cannot,
|
|
* `why` says what is missing, so the button says so instead of failing.
|
|
* `testMode`: the key is a Stripe TEST key, and the page must say that no
|
|
* money moves.
|
|
*/
|
|
export type SubscriptionOffer = {
|
|
tiers: Partial<Record<SubscriptionTier, TierOffer>>;
|
|
payable: boolean;
|
|
why: "no-database" | "sales-off" | "no-key" | "no-webhook" | null;
|
|
testMode: boolean;
|
|
};
|
|
|
|
export function subscriptionOffer(env: Env = process.env, database: boolean = dbConfigured()): SubscriptionOffer {
|
|
const tiers: SubscriptionOffer["tiers"] = {};
|
|
if (database) {
|
|
for (const tier of SUBSCRIPTION_TIERS) {
|
|
const plans = tierPlans(tier, env);
|
|
if (!plans.length) continue;
|
|
const month = plans.find((p) => p.interval === "month");
|
|
const year = plans.find((p) => p.interval === "year");
|
|
tiers[tier] = { tier, plans, pricing: subscriptionPricing({ month: month?.price, year: year?.price, intro: month?.intro ?? null }) };
|
|
}
|
|
}
|
|
const why: SubscriptionOffer["why"] = !database
|
|
? "no-database"
|
|
: !env.STRIPE_SECRET_KEY?.trim()
|
|
? "no-key"
|
|
: !env.STRIPE_WEBHOOK_SECRET?.trim()
|
|
? "no-webhook"
|
|
: !salesEnabled(env)
|
|
? "sales-off"
|
|
: null;
|
|
return { tiers, payable: why === null && subscriptionConfig(env) !== null, why, testMode: stripeKeyMode(env.STRIPE_SECRET_KEY) === "test" };
|
|
}
|
|
|
|
// ── The record ─────────────────────────────────────────────────────────────
|
|
|
|
type Row = typeof paySubscriptions.$inferSelect;
|
|
|
|
function toRecord(row: Row): SubscriptionRecord {
|
|
return {
|
|
subscriptionId: row.subscriptionId,
|
|
customerId: row.customerId,
|
|
planId: row.planId,
|
|
status: row.status as SubscriptionStatus,
|
|
periodEnd: row.periodEnd ? row.periodEnd.toISOString() : null,
|
|
cancelAtPeriodEnd: row.cancelAtPeriodEnd,
|
|
paymentFailed: row.paymentFailed,
|
|
updatedAt: row.eventAt ? row.eventAt.toISOString() : null,
|
|
};
|
|
}
|
|
|
|
export async function subscriptionOf(actorId: string, database: typeof db = db): Promise<SubscriptionRecord | null> {
|
|
const [row] = await database.select().from(paySubscriptions).where(eq(paySubscriptions.actorId, actorId));
|
|
return row ? toRecord(row) : null;
|
|
}
|
|
|
|
/** What settings shows about this person's subscription: its state, which tier, and whether the portal can open. */
|
|
export async function plusStanding(
|
|
actorId: string,
|
|
now: Date = new Date(),
|
|
): Promise<{ standing: SubscriptionStanding; manageable: boolean; tier: SubscriptionTier | null }> {
|
|
const record = await subscriptionOf(actorId).catch(() => null);
|
|
return {
|
|
standing: subscriptionStanding(record, now),
|
|
manageable: Boolean(record?.customerId),
|
|
tier: record?.planId && isSubscriptionPlan(record.planId) ? tierOfPlan(record.planId) : null,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Does this person already hold something a new subscription would overlap:
|
|
* a subscription that still renews or still gives access (switching between
|
|
* Plus and Max is done in Stripe's portal, on the same subscription), or a
|
|
* pass that has not run out.
|
|
*/
|
|
export type Overlap =
|
|
| { kind: "subscription"; until: string | null; manageable: boolean; tier: SubscriptionTier | null }
|
|
| { kind: "pass"; until: string }
|
|
| null;
|
|
|
|
export async function overlapFor(actorId: string, now: Date = new Date()): Promise<Overlap> {
|
|
const record = await subscriptionOf(actorId);
|
|
const standing = subscriptionStanding(record, now);
|
|
if (standing.state === "renews" || standing.state === "ends" || standing.state === "payment_failed") {
|
|
return {
|
|
kind: "subscription",
|
|
until: standing.date,
|
|
manageable: Boolean(record?.customerId),
|
|
tier: record?.planId && isSubscriptionPlan(record.planId) ? tierOfPlan(record.planId) : null,
|
|
};
|
|
}
|
|
const pass = await entitlementOf(actorId);
|
|
if (pass && isActive(pass, now)) return { kind: "pass", until: pass.expiresAt };
|
|
return null;
|
|
}
|
|
|
|
const RANK = { plus: 1, max: 2 } as const;
|
|
|
|
/**
|
|
* Write a record and move the pass to what it gives, in one transaction.
|
|
*
|
|
* The END only ever moves later: a pass bought in Bitcoin that runs longer
|
|
* than the subscription is not shortened by it. The PLAN follows the
|
|
* subscription (so a downgrade from Max to Plus in the portal is a downgrade
|
|
* here), except over a one-time pass that runs longer and gives as much.
|
|
*/
|
|
async function store(database: typeof db, actorId: string, record: SubscriptionRecord): Promise<void> {
|
|
await database.transaction(async (tx) => {
|
|
const values = {
|
|
provider: PLUS_PROVIDER,
|
|
subscriptionId: record.subscriptionId,
|
|
customerId: record.customerId,
|
|
planId: record.planId,
|
|
status: record.status,
|
|
periodEnd: record.periodEnd ? new Date(record.periodEnd) : null,
|
|
cancelAtPeriodEnd: record.cancelAtPeriodEnd,
|
|
paymentFailed: record.paymentFailed,
|
|
eventAt: record.updatedAt ? new Date(record.updatedAt) : null,
|
|
updatedAt: new Date(),
|
|
};
|
|
await tx.insert(paySubscriptions).values({ actorId, ...values }).onConflictDoUpdate({ target: paySubscriptions.actorId, set: values });
|
|
|
|
const until = subscriptionAccessUntil(record);
|
|
if (!until) return;
|
|
const planId: SubscriptionPlanId = record.planId && isSubscriptionPlan(record.planId) ? record.planId : "plus-month";
|
|
const [current] = await tx.select().from(entitlements).where(eq(entitlements.actorId, actorId)).for("update");
|
|
const later = !current || current.expiresAt.getTime() < new Date(until).getTime();
|
|
const followPlan =
|
|
!current || later || isSubscriptionPlan(current.planId) || RANK[tierOfPlan(planId)] > RANK[tierOfPlan(current.planId)];
|
|
if (!later && (!followPlan || current?.planId === planId)) return;
|
|
const expiresAt = later ? new Date(until) : current!.expiresAt;
|
|
const nextPlan = followPlan ? planId : current!.planId;
|
|
await tx
|
|
.insert(entitlements)
|
|
.values({ actorId, planId: nextPlan, expiresAt })
|
|
.onConflictDoUpdate({ target: entitlements.actorId, set: { planId: nextPlan, expiresAt, updatedAt: new Date() } });
|
|
});
|
|
}
|
|
|
|
/**
|
|
* The checkout came back paid (through the webhook or the return page): read
|
|
* the subscription it made and start the tier. Safe to run twice: the second
|
|
* run finds the same subscription and the same period end.
|
|
*/
|
|
async function startFromCheckout(
|
|
billing: StripeBilling,
|
|
checkout: Pick<CheckoutRow, "id" | "actorId" | "planId">,
|
|
subscriptionId: string,
|
|
customerId: string | null,
|
|
at: string | null,
|
|
database: typeof db,
|
|
): Promise<SubscriptionRecord | null> {
|
|
const snapshot = await billing.readSubscription(subscriptionId);
|
|
const existing = await subscriptionOf(checkout.actorId, database);
|
|
// A person who subscribes again (after an old one ended) replaces the old record.
|
|
const base = existing && existing.subscriptionId === subscriptionId ? existing : null;
|
|
const started = applySubscriptionEvent(base, {
|
|
eventId: null,
|
|
createdAt: at,
|
|
type: "subscription_updated",
|
|
subscription: { ...snapshot, customerId: snapshot.customerId ?? customerId, planId: snapshot.planId ?? checkout.planId },
|
|
});
|
|
if (!started) return null;
|
|
await store(database, checkout.actorId, started);
|
|
const claimed = await database
|
|
.update(payCheckouts)
|
|
.set({ settledAt: new Date() })
|
|
.where(and(eq(payCheckouts.id, checkout.id), isNull(payCheckouts.settledAt)))
|
|
.returning({ id: payCheckouts.id });
|
|
if (claimed.length) await countPlans("paid");
|
|
return started;
|
|
}
|
|
|
|
/**
|
|
* The plan of a subscription event, read from the Price it is on.
|
|
*
|
|
* paykit reads a subscription's plan from its metadata, which is written
|
|
* once, at checkout. Switching from Plus to Max in Stripe's portal changes
|
|
* the subscription's Price and not its metadata, so for a
|
|
* `customer.subscription.*` event the Price (its `metadata.plan_id` or
|
|
* lookup key, both set by «Stripe einrichten») says the plan instead.
|
|
* `rawBody` is the verified delivery.
|
|
*/
|
|
export function withPlanFromPrice(event: SubscriptionEvent, rawBody: string): SubscriptionEvent {
|
|
if (event.type !== "subscription_updated" && event.type !== "subscription_ended") return event;
|
|
let price: unknown = null;
|
|
try {
|
|
const items = (JSON.parse(rawBody) as { data?: { object?: { items?: { data?: { price?: unknown }[] } } } }).data?.object?.items?.data;
|
|
price = Array.isArray(items) ? items[0]?.price : null;
|
|
} catch {
|
|
return event;
|
|
}
|
|
const plan = planOfPrice(price);
|
|
return plan ? { ...event, subscription: { ...event.subscription, planId: plan } } : event;
|
|
}
|
|
|
|
export type EventOutcome = "handled" | "duplicate" | "unknown-subscription" | "unknown-checkout" | "ignored";
|
|
|
|
/**
|
|
* One verified Stripe event about a subscription. Idempotent by the event's
|
|
* id (`pay_events`), and safe without it: every step only moves forward.
|
|
*/
|
|
export async function handleSubscriptionEvent(event: SubscriptionEvent, config: SubscriptionConfig, database: typeof db = db): Promise<EventOutcome> {
|
|
if (event.eventId) {
|
|
const [seen] = await database.select({ id: payEvents.id }).from(payEvents).where(eq(payEvents.id, event.eventId));
|
|
if (seen) return "duplicate";
|
|
}
|
|
const outcome = await apply(event, config, database);
|
|
if (event.eventId) {
|
|
await database.insert(payEvents).values({ id: event.eventId, provider: PLUS_PROVIDER, type: event.type }).onConflictDoNothing();
|
|
}
|
|
return outcome;
|
|
}
|
|
|
|
async function apply(event: SubscriptionEvent, config: SubscriptionConfig, database: typeof db): Promise<EventOutcome> {
|
|
if (event.type === "checkout_completed") {
|
|
const [checkout] = await database.select().from(payCheckouts).where(eq(payCheckouts.id, event.checkoutId));
|
|
if (!checkout || !isSubscriptionPlan(checkout.planId)) return "unknown-checkout";
|
|
if (!event.paid || !event.subscriptionId) return "ignored";
|
|
await startFromCheckout(billingFor(config), checkout, event.subscriptionId, event.customerId, event.createdAt, database);
|
|
return "handled";
|
|
}
|
|
const subscriptionId = event.type === "subscription_updated" || event.type === "subscription_ended" ? event.subscription.id : event.subscriptionId;
|
|
const [row] = await database.select().from(paySubscriptions).where(eq(paySubscriptions.subscriptionId, subscriptionId));
|
|
// Not one of Heidi's yet: an invoice paid before the checkout's own event
|
|
// arrived. Nothing is lost: the checkout's event reads the subscription,
|
|
// period end included.
|
|
if (!row) return "unknown-subscription";
|
|
const next = applySubscriptionEvent(toRecord(row), event);
|
|
if (!next) return "ignored";
|
|
await store(database, row.actorId, next);
|
|
return "handled";
|
|
}
|
|
|
|
/**
|
|
* The return page's question for a subscription checkout: has it been paid,
|
|
* and if so, start the tier now rather than wait for the webhook.
|
|
*/
|
|
export async function plusCheckoutState(row: CheckoutRow, database: typeof db = db): Promise<"pending" | "paid" | "expired" | "failed"> {
|
|
if (row.settledAt) return "paid";
|
|
const config = subscriptionConfig(await payEnv());
|
|
if (!config) return "pending";
|
|
const billing = billingFor(config);
|
|
const state = await billing.readSubscriptionCheckout(row.id);
|
|
if (state.state === "paid" && state.subscriptionId) {
|
|
await startFromCheckout(billing, row, state.subscriptionId, state.customerId, null, database);
|
|
}
|
|
return state.state;
|
|
}
|
|
|
|
// ── Taking one out ─────────────────────────────────────────────────────────
|
|
|
|
export type SubscribeResult =
|
|
| { ok: true; redirect: string }
|
|
| { ok: false; status: 400 | 409 | 502 | 503; error: "off" | "unknown-plan" | "overlap" | "provider" };
|
|
|
|
const STRIPE_CHECKOUT_LOCALES = STRIPE_LOCALES;
|
|
|
|
/**
|
|
* Stripe's page for this plan, ON THE PRICE «Stripe einrichten» made for it
|
|
* (so the portal can later switch it to the other tier), with the intro as
|
|
* paykit's coupon. Where no Price was made, or the owner has changed the
|
|
* amount since, paykit's own checkout states the price on the session: the
|
|
* sale still works, and switching tiers in the portal waits for the next
|
|
* «Stripe einrichten».
|
|
*/
|
|
async function openCheckout(
|
|
config: SubscriptionConfig,
|
|
plan: SubscriptionPlan,
|
|
env: Env,
|
|
input: { reference: string; customerId: string | null; email: string | null },
|
|
opts: BillingOpts,
|
|
) {
|
|
const billing = billingFor(config, opts);
|
|
const priceId = readPriceSetting(env[STRIPE_PRICE_SETTING(plan.id as SubscriptionPlanId)], plan.price.amount);
|
|
if (!priceId) return billing.createSubscriptionCheckout({ plan, reference: input.reference, customerId: input.customerId, email: input.email });
|
|
|
|
const coupon = await billing.ensureIntroCoupon(plan);
|
|
const prefix = opts.locale ? `/${opts.locale}` : "";
|
|
const form = new URLSearchParams({
|
|
mode: "subscription",
|
|
success_url: `${SITE_URL}${prefix}/pass/checkout/{CHECKOUT_SESSION_ID}`,
|
|
cancel_url: `${SITE_URL}${prefix}/plans`,
|
|
"metadata[plan_id]": plan.id,
|
|
"subscription_data[metadata][plan_id]": plan.id,
|
|
"line_items[0][price]": priceId,
|
|
"line_items[0][quantity]": "1",
|
|
});
|
|
if (coupon) form.set("discounts[0][coupon]", coupon);
|
|
if (input.customerId) form.set("customer", input.customerId);
|
|
else if (input.email) form.set("customer_email", input.email);
|
|
const locale = opts.locale ? STRIPE_CHECKOUT_LOCALES[opts.locale] : undefined;
|
|
if (locale) form.set("locale", locale);
|
|
const session = await stripeCall({ secretKey: config.secretKey, baseUrl: config.baseUrl })("/v1/checkout/sessions", { method: "POST", form });
|
|
if (typeof session.id !== "string" || typeof session.url !== "string") throw new StripeError("Stripe returned no payment page.", 502);
|
|
return {
|
|
provider: "stripe",
|
|
id: session.id,
|
|
reference: input.reference,
|
|
planId: plan.id,
|
|
amount: { amount: plan.intro ? plan.intro.amount.amount : plan.price.amount, currency: plan.price.currency.toUpperCase() },
|
|
payUrl: session.url,
|
|
expiresAt: typeof session.expires_at === "number" ? new Date(session.expires_at * 1000).toISOString() : null,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Send this person to Stripe to subscribe to a plan (`plus-month`,
|
|
* `max-year`, …). Refused while they already hold a plan that would
|
|
* overlap: the page offers to manage that one instead, where Plus becomes
|
|
* Max and back.
|
|
*/
|
|
export async function startSubscription(actorId: string, planId: SubscriptionPlanId, opts: BillingOpts & { email?: string | null } = {}): Promise<SubscribeResult> {
|
|
const env = await payEnv();
|
|
const offer = subscriptionOffer(env);
|
|
const config = subscriptionConfig(env);
|
|
if (!offer.payable || !config) return { ok: false, status: 503, error: "off" };
|
|
const plan = config.plans.find((p) => p.id === planId);
|
|
if (!plan) return { ok: false, status: 400, error: "unknown-plan" };
|
|
if (await overlapFor(actorId)) return { ok: false, status: 409, error: "overlap" };
|
|
|
|
try {
|
|
const existing = await subscriptionOf(actorId);
|
|
const checkout = await openCheckout(
|
|
config,
|
|
plan,
|
|
env,
|
|
// A returning subscriber keeps their Stripe customer (and its saved card).
|
|
{ reference: actorId, customerId: existing?.customerId ?? null, email: opts.email ?? null },
|
|
opts,
|
|
);
|
|
await saveCheckout(checkout);
|
|
const row = await ownCheckout(checkout.id, actorId);
|
|
if (!row) return { ok: false, status: 502, error: "provider" };
|
|
return { ok: true, redirect: checkout.payUrl };
|
|
} catch (error) {
|
|
// Stripe's sentences are for whoever holds the key: logged, not shown.
|
|
console.error(`[pay] no subscription checkout: ${error instanceof Error ? error.name : "unknown"}${error instanceof StripeError ? ` ${error.status}` : ""}`);
|
|
return { ok: false, status: 502, error: "provider" };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Stripe's page to manage, switch between Plus and Max, or cancel, for this
|
|
* person. With the portal configuration «Stripe einrichten» made, so it works
|
|
* without the Dashboard's portal settings. Null when they have no Stripe customer.
|
|
*/
|
|
export async function portalUrl(actorId: string, locale: string, returnPath: string): Promise<string | null> {
|
|
const env = await payEnv();
|
|
const config = subscriptionConfig(env);
|
|
const record = await subscriptionOf(actorId);
|
|
if (!config || !record?.customerId) return null;
|
|
const configuration = env[STRIPE_PORTAL_SETTING]?.trim();
|
|
if (!configuration) {
|
|
const { url } = await billingFor(config, { locale }).createPortalSession({ customerId: record.customerId, returnUrl: `${SITE_URL}${returnPath}` });
|
|
return url;
|
|
}
|
|
// paykit's `createPortalSession` takes no configuration (a paykit candidate): the same call, with it.
|
|
const form = new URLSearchParams({ customer: record.customerId, return_url: `${SITE_URL}${returnPath}`, configuration });
|
|
const stripeLocale = STRIPE_LOCALES[locale];
|
|
if (stripeLocale) form.set("locale", stripeLocale);
|
|
const session = await stripeCall({ secretKey: config.secretKey, baseUrl: config.baseUrl })("/v1/billing_portal/sessions", { method: "POST", form });
|
|
if (typeof session.url !== "string") throw new StripeError("Stripe returned no portal page.", 502);
|
|
return session.url;
|
|
}
|
|
|
|
/**
|
|
* Stop a person's subscription at Stripe now, because their account is being
|
|
* deleted: nobody should go on paying for an account that no longer exists.
|
|
* Best effort, and it says whether it could.
|
|
*/
|
|
export async function cancelForErasure(actorId: string, database: typeof db = db): Promise<"none" | "cancelled" | "failed"> {
|
|
const record = await subscriptionOf(actorId, database).catch(() => null);
|
|
if (!record || record.status === "canceled" || record.status === "incomplete_expired") return "none";
|
|
const config = subscriptionConfig(await payEnv());
|
|
if (!config) return "failed";
|
|
try {
|
|
await billingFor(config).cancelSubscription(record.subscriptionId);
|
|
return "cancelled";
|
|
} catch {
|
|
return "failed";
|
|
}
|
|
}
|