mirror of
https://github.com/bitbaum/heidi.git
synced 2026-12-05 12:28:30 +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>
333 lines
16 KiB
TypeScript
333 lines
16 KiB
TypeScript
import { test, before, after, mock } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { readdirSync, readFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { PGlite } from "@electric-sql/pglite";
|
|
import { drizzle } from "drizzle-orm/pglite";
|
|
import * as schema from "../db/schema.ts";
|
|
import { subscriptionConfig, plusPlans, tierPlans } from "../config/payments.ts";
|
|
import { capsFor } from "../config/caps.ts";
|
|
import { reviewEveryDays } from "../domain/coach/review.ts";
|
|
import { readiness } from "./readiness.ts";
|
|
|
|
/**
|
|
* Heidi Plus, the subscription: what /plans shows from the owner's prices,
|
|
* what each Stripe event does to the pass, that the owner's page lists what
|
|
* is missing without showing a value, and that no price is written in code.
|
|
*
|
|
* Every price below is a TEST value, set the way the owner sets them: in the
|
|
* environment.
|
|
*/
|
|
|
|
const PRICES = { HEIDI_PLUS_MONTH_CHF: "10", HEIDI_PLUS_YEAR_CHF: "84", HEIDI_PLUS_INTRO_CHF: "5", HEIDI_PLUS_INTRO_MONTHS: "2" };
|
|
const KEYS = { STRIPE_SECRET_KEY: "sk_test_plus_value_that_must_not_show", STRIPE_WEBHOOK_SECRET: "whsec_plus_value_that_must_not_show" };
|
|
const ENV = { HEIDI_SALES_ENABLED: "1", ...KEYS, ...PRICES };
|
|
|
|
let pg: PGlite;
|
|
let plus: typeof import("./plus.ts");
|
|
const realFetch = globalThis.fetch;
|
|
/** What Stripe answers for GET /v1/subscriptions/{id}. */
|
|
const stripe: { subscription: Record<string, unknown>; calls: string[] } = { subscription: {}, calls: [] };
|
|
|
|
before(async () => {
|
|
pg = new PGlite();
|
|
const dir = join(process.cwd(), "drizzle");
|
|
for (const file of readdirSync(dir).filter((f) => f.endsWith(".sql")).sort()) {
|
|
for (const statement of readFileSync(join(dir, file), "utf8").split("--> statement-breakpoint")) {
|
|
if (statement.trim()) await pg.exec(statement);
|
|
}
|
|
}
|
|
const db = drizzle(pg, { schema });
|
|
mock.module(new URL("../db/index.ts", import.meta.url).href, {
|
|
namedExports: { db, getDb: () => db, dbConfigured: () => true, schema },
|
|
});
|
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = new URL(String(input));
|
|
stripe.calls.push(`${init?.method ?? "GET"} ${url.pathname}`);
|
|
if (url.pathname.startsWith("/v1/subscriptions/")) return Response.json(stripe.subscription);
|
|
return Response.json({ error: { message: "not in this test" } }, { status: 404 });
|
|
}) as typeof fetch;
|
|
plus = await import("./plus.ts");
|
|
});
|
|
|
|
after(async () => {
|
|
globalThis.fetch = realFetch;
|
|
await pg.close();
|
|
});
|
|
|
|
const day = 86_400_000;
|
|
const unix = (ms: number) => Math.floor(ms / 1000);
|
|
const iso = (ms: number) => new Date(unix(ms) * 1000).toISOString();
|
|
|
|
async function passUntil(actorId: string): Promise<string | null> {
|
|
const rows = await pg.query<{ expires_at: Date }>("select expires_at from entitlements where actor_id = $1", [actorId]);
|
|
return rows.rows[0] ? new Date(rows.rows[0].expires_at).toISOString() : null;
|
|
}
|
|
|
|
test("the page's prices come from the environment: the yearly saving and the intro are computed", () => {
|
|
const offer = plus.subscriptionOffer(ENV, true).tiers.plus;
|
|
assert.ok(offer);
|
|
assert.equal(offer.pricing.month?.amount, 1000);
|
|
assert.equal(offer.pricing.year?.amount, 8400);
|
|
// 84 a year is 7 a month; 120 at the monthly price: 30 % less.
|
|
assert.equal(offer.pricing.yearPerMonth?.amount, 700);
|
|
assert.equal(offer.pricing.savePercent, 30);
|
|
assert.deepEqual(offer.pricing.intro, { amount: { amount: 500, currency: "CHF" }, months: 2 });
|
|
|
|
// An intro that is not cheaper is not an intro; a yearly price that saves nothing shows no saving.
|
|
const flat = plus.subscriptionOffer({ ...ENV, HEIDI_PLUS_INTRO_CHF: "10", HEIDI_PLUS_YEAR_CHF: "120" }, true).tiers.plus;
|
|
assert.ok(flat);
|
|
assert.equal(flat.pricing.intro, null);
|
|
assert.equal(flat.pricing.savePercent, null);
|
|
});
|
|
|
|
test("without prices, or with sales off, or without the webhook secret, Plus is not sold", () => {
|
|
assert.equal(plus.subscriptionOffer({ HEIDI_SALES_ENABLED: "1", ...KEYS }, true).payable, false);
|
|
assert.equal(plus.subscriptionOffer({ ...ENV, HEIDI_SALES_ENABLED: "" }, true).payable, false);
|
|
assert.equal(plus.subscriptionOffer({ ...ENV, STRIPE_WEBHOOK_SECRET: "" }, true).payable, false);
|
|
assert.equal(plus.subscriptionOffer(ENV, false).payable, false, "no database, no subscription record");
|
|
});
|
|
|
|
test("no price is written in code: an empty environment prices nothing, and no copy names a franc amount", () => {
|
|
assert.deepEqual(plusPlans({}), []);
|
|
assert.equal(subscriptionConfig({ ...KEYS }), null);
|
|
const files = [
|
|
"../../app/[locale]/plans/page.tsx",
|
|
"../../app/[locale]/plans/plans-view.tsx",
|
|
"../../app/[locale]/plans/plus-review.tsx",
|
|
"../../app/[locale]/settings/subscription-section.tsx",
|
|
"../../app/api/pay/subscribe/route.ts",
|
|
"./plus.ts",
|
|
"./settings.ts",
|
|
"./stripe-setup.ts",
|
|
"./tier.ts",
|
|
"./plan-cards.ts",
|
|
"../../app/[locale]/manage/money/payments/page.tsx",
|
|
"../../app/[locale]/manage/money/payments/payments-form.tsx",
|
|
"../../app/api/owner/pay-settings/route.ts",
|
|
"../../app/api/owner/stripe-setup/route.ts",
|
|
"../i18n/dictionaries/operator.ts",
|
|
...["de", "en", "fr", "it", "rm", "ru", "gsw"].map((l) => `../i18n/dictionaries/${l}.ts`),
|
|
];
|
|
for (const file of files) {
|
|
const code = readFileSync(new URL(file, import.meta.url), "utf8");
|
|
const found = code.match(/\b(?:CHF|Fr\.)\s?\d|\d+(?:[.,]\d{2})?\s?(?:CHF|Franken|francs|franchi)\b/);
|
|
assert.equal(found, null, `${file} names a price: ${found?.[0]}`);
|
|
}
|
|
});
|
|
|
|
test("a paid checkout starts Plus; each paid invoice moves the pass to its period end", async () => {
|
|
const config = subscriptionConfig(ENV);
|
|
assert.ok(config);
|
|
const start = Date.now();
|
|
await pg.query(
|
|
"insert into pay_checkouts (id, actor_id, provider, plan_id, amount, currency) values ('cs_test_1', 'actor-plus', 'stripe', 'plus-month', 500, 'CHF')",
|
|
);
|
|
stripe.subscription = {
|
|
id: "sub_1",
|
|
customer: "cus_1",
|
|
status: "active",
|
|
cancel_at_period_end: false,
|
|
metadata: { plan_id: "plus-month" },
|
|
items: { data: [{ current_period_end: unix(start + 30 * day) }] },
|
|
};
|
|
|
|
const started = await plus.handleSubscriptionEvent(
|
|
{ type: "checkout_completed", eventId: "evt_1", createdAt: iso(start), checkoutId: "cs_test_1", subscriptionId: "sub_1", customerId: "cus_1", paid: true, planId: "plus-month" },
|
|
config,
|
|
);
|
|
assert.equal(started, "handled");
|
|
assert.equal(await passUntil("actor-plus"), iso(start + 30 * day));
|
|
const row = await plus.subscriptionOf("actor-plus");
|
|
assert.equal(row?.subscriptionId, "sub_1");
|
|
assert.equal(row?.customerId, "cus_1");
|
|
|
|
// The same event again: Stripe retries; nothing happens twice.
|
|
const again = await plus.handleSubscriptionEvent(
|
|
{ type: "checkout_completed", eventId: "evt_1", createdAt: iso(start), checkoutId: "cs_test_1", subscriptionId: "sub_1", customerId: "cus_1", paid: true, planId: "plus-month" },
|
|
config,
|
|
);
|
|
assert.equal(again, "duplicate");
|
|
|
|
// The renewal a month later.
|
|
const renewed = await plus.handleSubscriptionEvent(
|
|
{ type: "invoice_paid", eventId: "evt_2", createdAt: iso(start + 30 * day), subscriptionId: "sub_1", customerId: "cus_1", invoiceId: "in_2", periodEnd: iso(start + 60 * day), amount: { amount: 500, currency: "CHF" } },
|
|
config,
|
|
);
|
|
assert.equal(renewed, "handled");
|
|
assert.equal(await passUntil("actor-plus"), iso(start + 60 * day));
|
|
const standing = await plus.plusStanding("actor-plus", new Date(start + 31 * day));
|
|
assert.deepEqual(standing, { standing: { state: "renews", date: iso(start + 60 * day) }, manageable: true, tier: "plus" });
|
|
});
|
|
|
|
test("a failed payment shows in Settings and keeps what was paid; a cancelled subscription stops renewing", async () => {
|
|
const config = subscriptionConfig(ENV);
|
|
assert.ok(config);
|
|
const now = Date.now();
|
|
const before = await passUntil("actor-plus");
|
|
|
|
const failed = await plus.handleSubscriptionEvent(
|
|
{ type: "payment_failed", eventId: "evt_3", createdAt: iso(now + 60 * day), subscriptionId: "sub_1", customerId: "cus_1", invoiceId: "in_3", nextAttemptAt: null },
|
|
config,
|
|
);
|
|
assert.equal(failed, "handled");
|
|
assert.equal(await passUntil("actor-plus"), before, "a failed payment takes nothing away");
|
|
assert.equal((await plus.plusStanding("actor-plus", new Date(now + 31 * day))).standing.state, "payment_failed");
|
|
|
|
const ended = await plus.handleSubscriptionEvent(
|
|
{
|
|
type: "subscription_ended",
|
|
eventId: "evt_4",
|
|
createdAt: iso(now + 61 * day),
|
|
subscription: { id: "sub_1", customerId: "cus_1", status: "canceled", periodEnd: before, cancelAtPeriodEnd: false, cancelAt: null, endedAt: iso(now + 61 * day), planId: "plus-month" },
|
|
},
|
|
config,
|
|
);
|
|
assert.equal(ended, "handled");
|
|
assert.equal(await passUntil("actor-plus"), before, "the paid period is kept");
|
|
assert.notEqual((await plus.plusStanding("actor-plus", new Date(now + 31 * day))).standing.state, "renews");
|
|
|
|
// Stripe moves a subscription's period on when it bills, paid or not: a
|
|
// `past_due` update names a period nobody paid for, and gives nothing.
|
|
const pastDue = await plus.handleSubscriptionEvent(
|
|
{
|
|
type: "subscription_updated",
|
|
eventId: "evt_5",
|
|
createdAt: iso(now + 62 * day),
|
|
subscription: { id: "sub_1", customerId: "cus_1", status: "past_due", periodEnd: iso(now + 90 * day), cancelAtPeriodEnd: false, cancelAt: null, endedAt: null, planId: "plus-month" },
|
|
},
|
|
config,
|
|
);
|
|
assert.equal(pastDue, "handled");
|
|
assert.equal(await passUntil("actor-plus"), before, "an unpaid period moved the pass");
|
|
});
|
|
|
|
test("an invoice for a subscription Heidi has not linked yet is answered, and changes nothing", async () => {
|
|
const config = subscriptionConfig(ENV);
|
|
assert.ok(config);
|
|
const outcome = await plus.handleSubscriptionEvent(
|
|
{ type: "invoice_paid", eventId: "evt_9", createdAt: new Date().toISOString(), subscriptionId: "sub_unknown", customerId: null, invoiceId: null, periodEnd: null, amount: null },
|
|
config,
|
|
);
|
|
assert.equal(outcome, "unknown-subscription");
|
|
});
|
|
|
|
test("the owner's page lists what Plus and Max need and points at «Stripe einrichten», never a value", () => {
|
|
const rail = (env: Record<string, string>) => readiness(env).rails.find((r) => r.id === "plus");
|
|
const off = rail({});
|
|
assert.equal(off?.on, false);
|
|
assert.deepEqual(
|
|
off?.checks.filter((c) => !c.set && !c.optional).map((c) => c.name),
|
|
["HEIDI_SALES_ENABLED=1", "STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET", "HEIDI_PLUS_MONTH_CHF"],
|
|
);
|
|
// No price is proposed in code: the owner decides them.
|
|
assert.equal(off?.checks.some((c) => c.proposal), false);
|
|
assert.ok(off?.checks.some((c) => c.name === "HEIDI_MAX_MONTH_CHF" && c.optional));
|
|
assert.ok(off?.steps.some((s) => s.includes("Stripe einrichten") && s.includes("invoice.paid") && s.includes("customer.subscription.deleted")));
|
|
|
|
const dump = JSON.stringify(readiness(ENV));
|
|
for (const value of Object.values(KEYS)) assert.equal(dump.includes(value), false, `${value} reached the page`);
|
|
});
|
|
|
|
// ── Heidi Max ──────────────────────────────────────────────────────────────
|
|
|
|
const MAX_PRICES = { HEIDI_MAX_MONTH_CHF: "30", HEIDI_MAX_YEAR_CHF: "240", HEIDI_MAX_INTRO_CHF: "20", HEIDI_MAX_INTRO_MONTHS: "3" };
|
|
const BOTH = { ...ENV, ...MAX_PRICES };
|
|
|
|
test("Max is offered only when the owner priced it, with its own saving and intro", () => {
|
|
assert.equal(plus.subscriptionOffer(ENV, true).tiers.max, undefined, "Max shown without a price");
|
|
assert.deepEqual(tierPlans("max", {}), []);
|
|
const max = plus.subscriptionOffer(BOTH, true).tiers.max;
|
|
assert.ok(max);
|
|
assert.deepEqual(
|
|
max.plans.map((p) => p.id),
|
|
["max-month", "max-year"],
|
|
);
|
|
// 240 a year is 20 a month against 30: a third less.
|
|
assert.equal(max.pricing.yearPerMonth?.amount, 2000);
|
|
assert.equal(max.pricing.savePercent, 33);
|
|
assert.deepEqual(max.pricing.intro, { amount: { amount: 2000, currency: "CHF" }, months: 3 });
|
|
assert.equal(subscriptionConfig(BOTH)?.plans.length, 4);
|
|
});
|
|
|
|
test("a TEST key is test mode, and the page says so; a live key is not", () => {
|
|
assert.equal(plus.subscriptionOffer(BOTH, true).testMode, true);
|
|
assert.equal(plus.subscriptionOffer({ ...BOTH, STRIPE_SECRET_KEY: "sk_live_0123456789" }, true).testMode, false);
|
|
assert.equal(plus.subscriptionOffer({ ...BOTH, STRIPE_SECRET_KEY: "" }, true).why, "no-key");
|
|
});
|
|
|
|
test("a Max checkout gives Max: its caps and its weekly Rückblick; a switch in the portal moves the tier with the Price", async () => {
|
|
const { tierOf } = await import("./tier.ts");
|
|
const config = subscriptionConfig(BOTH);
|
|
assert.ok(config);
|
|
const start = Date.now();
|
|
const actor = "actor-max";
|
|
assert.equal(await tierOf(actor), "free");
|
|
|
|
await pg.query(
|
|
"insert into pay_checkouts (id, actor_id, provider, plan_id, amount, currency) values ('cs_test_max', $1, 'stripe', 'max-year', 24000, 'CHF')",
|
|
[actor],
|
|
);
|
|
stripe.subscription = {
|
|
id: "sub_max",
|
|
customer: "cus_max",
|
|
status: "active",
|
|
cancel_at_period_end: false,
|
|
metadata: { plan_id: "max-year" },
|
|
items: { data: [{ current_period_end: unix(start + 365 * day) }] },
|
|
};
|
|
const started = await plus.handleSubscriptionEvent(
|
|
{ type: "checkout_completed", eventId: "evt_max_1", createdAt: iso(start), checkoutId: "cs_test_max", subscriptionId: "sub_max", customerId: "cus_max", paid: true, planId: "max-year" },
|
|
config,
|
|
);
|
|
assert.equal(started, "handled");
|
|
const tier = await tierOf(actor);
|
|
assert.equal(tier, "max");
|
|
assert.equal(capsFor(tier, {}).daily, capsFor("plus", {}).daily * 3);
|
|
assert.equal(reviewEveryDays(tier), 7);
|
|
assert.equal((await plus.plusStanding(actor)).tier, "max");
|
|
|
|
// Down to Plus in Stripe's portal: the subscription's metadata still says
|
|
// max-year; the Price it is on now says plus-month.
|
|
const raw = (lookup: string) =>
|
|
JSON.stringify({ data: { object: { id: "sub_max", items: { data: [{ price: { id: "price_x", lookup_key: lookup, metadata: {} } }] } } } });
|
|
const down = plus.withPlanFromPrice(
|
|
{
|
|
type: "subscription_updated",
|
|
eventId: "evt_max_2",
|
|
createdAt: iso(start + day),
|
|
subscription: { id: "sub_max", customerId: "cus_max", status: "active", periodEnd: iso(start + 30 * day), cancelAtPeriodEnd: false, cancelAt: null, endedAt: null, planId: "max-year" },
|
|
},
|
|
raw("heidi-plus-month"),
|
|
);
|
|
assert.equal(down.type === "subscription_updated" && down.subscription.planId, "plus-month");
|
|
assert.equal(await plus.handleSubscriptionEvent(down, config), "handled");
|
|
assert.equal(await tierOf(actor), "plus");
|
|
assert.equal(reviewEveryDays(await tierOf(actor)), 30);
|
|
|
|
// And back up to Max.
|
|
const up = plus.withPlanFromPrice(
|
|
{
|
|
type: "subscription_updated",
|
|
eventId: "evt_max_3",
|
|
createdAt: iso(start + 2 * day),
|
|
subscription: { id: "sub_max", customerId: "cus_max", status: "active", periodEnd: iso(start + 30 * day), cancelAtPeriodEnd: false, cancelAt: null, endedAt: null, planId: "max-year" },
|
|
},
|
|
raw("heidi-max-month"),
|
|
);
|
|
assert.equal(await plus.handleSubscriptionEvent(up, config), "handled");
|
|
assert.equal(await tierOf(actor), "max");
|
|
});
|
|
|
|
test("a Price Heidi did not make leaves the plan as the event says it", () => {
|
|
const event = {
|
|
type: "subscription_updated" as const,
|
|
eventId: "evt_x",
|
|
createdAt: null,
|
|
subscription: { id: "sub_x", customerId: null, status: "active" as const, periodEnd: null, cancelAtPeriodEnd: false, cancelAt: null, endedAt: null, planId: "plus-year" },
|
|
};
|
|
const raw = JSON.stringify({ data: { object: { items: { data: [{ price: { id: "price_other", lookup_key: "someone-else", metadata: {} } }] } } } });
|
|
assert.deepEqual(plus.withPlanFromPrice(event, raw), event);
|
|
assert.deepEqual(plus.withPlanFromPrice(event, "not json"), event);
|
|
});
|