Public: anyone can read this; the crew can change it.

A paid checkout deploys the buyer's forge on its own machine, and an at-cost… #16559

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/16205-a-paid-checkout-deploys-the-buyer-s-forg → main 0 commits fork

  • Merged. mason/16205-a-paid-checkout-deploys-the-buyer-s-forg was merged into main as c2b2100.

Review

Sign in to review this change.
24 files changed +674 −56
docs/features/pricing.md +12
@@ -26,3 +26,15 @@ The same words are the "After you pay" row on `/terms`, the line under the plans
2626 lapse sentence `/terms` also prints, and the Terms and Privacy links. With no
2727 payment provider the page says paid plans are not on sale yet and shows the steps
2828 as what will happen; the terminal screen hides them.
29
30 ## Price follows the place, and at-cost codes (#16205)
31
32 When paid forges run on a cloud account (Pinned forges → "paid forges run on"), the buyer may pick where it runs. The plan's price is for the plan's default place. A dearer place adds the difference to the monthly price, rounded up to the next dollar: "Show the price" renders the plans with the chosen place and says on each plan what the place adds, and the checkout line says it too ("Small forge (digitalocean:nyc3:s-2vcpu-4gb: +$12 a month)"). The amount is fixed when the order is placed and kept on the order, and the checkout charges exactly it (inline `price_data`, no dashboard setup).
33
34 An **at-cost code** is made where a gift code is (Settings → Billing → Codes, `POST /api/v1/codes` with `kind: "at_cost"`, the terminal's codes screen with `c`), with uses and an expiry as now; the link it gives is `/pricing?code=…`. A buyer with one pays the place's monthly cost plus the payment fee (`src/billing/at_cost.ts`: 2.9% and 30 cents, grossed up so the forge keeps the cost), rounded up to the next dollar: the plan row shows "was" the normal price and "at cost" with the amount. A code is for one plan and never gives a plan free: the gift door refuses it (`wrong_kind`), and a gift code is refused here. A use is held by each open checkout (name held for 30 minutes) and spent when it is paid, so one use cannot fund many pending orders; a checkout that lapses gives its use back. Revoking stops new checkouts; one already open and paid is honoured at the price it quoted. Every look at a code, by the link or by Show the price, counts a try for the client, as a gift code's does.
35
36 At-cost needs a machine to cost, so it is refused while paid forges run hosted.
37
38 Settings → Billing, and the terminal's **Sold forges** screen (admin only), list each sold forge: plan, place, what its machine costs, what the buyer pays, the provider's fee and the margin. An at-cost forge reads zero margin. Orders keep the cost they were sold at, so a catalog that moves later rewrites no past sale.
39
40 Not done yet: an at-cost subscription does not follow a place's later cost change at its next renewal. Test: `bun test test/order-cloud.test.ts test/at-cost.test.ts`.
src/actions/codes.ts +12 −6
@@ -11,7 +11,7 @@
1111 import type { App } from "../app.ts";
1212 import { tellPlan } from "../billing/notice.ts";
1313 import {
14 CODE_WORDS, MAX_NOTE, MAX_USES, insertCode, listCodes, lookupCode, noteRedeemed,
14 CODE_WORDS, MAX_NOTE, type CodeKind, MAX_USES, insertCode, listCodes, lookupCode, noteRedeemed,
1515 releaseCode, revokeCode, takeTry, type Code, type CodeRefusal, type Listed,
1616 } from "../billing/codes.ts";
1717 import { putEntitlement } from "../billing/store.ts";
@@ -20,9 +20,10 @@ import { clientBucket } from "../http/peer.ts";
2020 import { err, ok, type Result } from "../kernel/result.ts";
2121 import { FREE, getPlan, getPlans } from "../settings/plans.ts";
2222
23 export type CodeError = "not_found" | "bad_plan" | "bad_uses" | "bad_note" | "bad_expiry" | "no_such_code";
23 export type CodeError = "not_found" | "bad_kind" | "bad_plan" | "bad_uses" | "bad_note" | "bad_expiry" | "no_such_code";
2424
2525 export const CODE_ERRORS: Record<Exclude<CodeError, "not_found">, string> = {
26 bad_kind: "A code is a gift of a plan (plan) or a forge at cost (at_cost)",
2627 bad_plan: "A code gives a plan other than free: name one of the paid plans",
2728 bad_uses: `Uses is a whole number from 1 to ${MAX_USES}`,
2829 bad_note: `A note is at most ${MAX_NOTE} characters, on one line`,
@@ -33,6 +34,7 @@ export const CODE_ERRORS: Record<Exclude<CodeError, "not_found">, string> = {
3334 const admin = (a: User | undefined): Result<User, "not_found"> => (a?.isAdmin === true && a.kind !== "agent" ? ok(a) : err("not_found"));
3435
3536 export interface CodePlan {
37 readonly kind: CodeKind;
3638 readonly plan: string;
3739 readonly note: string;
3840 readonly uses: number;
@@ -43,6 +45,9 @@ export interface CodePlan {
4345 export function planCode(app: App, actor: User | undefined, input: Record<string, unknown>, now = new Date()): Result<CodePlan, CodeError> {
4446 const who = admin(actor);
4547 if (!who.ok) return who;
48 const kindIn = input["kind"];
49 if (kindIn !== undefined && kindIn !== null && kindIn !== "" && kindIn !== "plan" && kindIn !== "at_cost") return err("bad_kind");
50 const kind: CodeKind = kindIn === "at_cost" ? "at_cost" : "plan";
4651 const plan = typeof input["plan"] === "string" ? getPlan(app.db, input["plan"]) : undefined;
4752 if (plan === undefined || plan.key === FREE) return err("bad_plan");
4853 const rawUses = input["uses"];
@@ -54,7 +59,7 @@ export function planCode(app: App, actor: User | undefined, input: Record<string
5459 if (note === undefined || note.length > MAX_NOTE || /[\u0000-\u001f\u007f]/.test(note)) return err("bad_note");
5560 const expiry = expiryOf(input["expires"], now);
5661 if (expiry === null) return err("bad_expiry");
57 return ok({ plan: plan.key, note, uses: usesIn, ...(expiry === undefined ? {} : { expiresAt: expiry }) });
62 return ok({ kind, plan: plan.key, note, uses: usesIn, ...(expiry === undefined ? {} : { expiresAt: expiry }) });
5863 }
5964
6065 /** A date (end of that day, UTC) or an ISO time; undefined when none is given, null when it is not acceptable. */
@@ -74,7 +79,8 @@ export function readCodes(app: App, actor: User | undefined): Result<{ codes: Li
7479 }
7580
7681 /** The link to send: the home page with the code already filled in. */
77 export const linkFor = (origin: string, code: string): string => `${origin}/?code=${encodeURIComponent(code)}`;
82 export const linkFor = (origin: string, code: string, kind: CodeKind = "plan"): string =>
83 kind === "at_cost" ? `${origin}/pricing?code=${encodeURIComponent(code)}` : `${origin}/?code=${encodeURIComponent(code)}`;
7884
7985 /** An admin makes a code. The plain code is in this answer and nowhere else. */
8086 export function makeCode(app: App, actor: User | undefined, input: Record<string, unknown>, origin: string): Result<{ code: string; link: string; made: Code }, CodeError> {
@@ -82,8 +88,8 @@ export function makeCode(app: App, actor: User | undefined, input: Record<string
8288 if (!planned.ok) return planned;
8389 const who = actor as User;
8490 const { code, row } = insertCode(app.db, { ...planned.value, madeBy: who.id });
85 app.bus.append({ kind: "billing.code.make", actorId: who.id, payload: { id: row.id, plan: row.plan, uses: row.uses, note: row.note, ...(row.expiresAt === undefined ? {} : { expires: row.expiresAt }) } });
86 return ok({ code, link: linkFor(origin, code), made: row });
91 app.bus.append({ kind: "billing.code.make", actorId: who.id, payload: { id: row.id, kind: row.kind, plan: row.plan, uses: row.uses, note: row.note, ...(row.expiresAt === undefined ? {} : { expires: row.expiresAt }) } });
92 return ok({ code, link: linkFor(origin, code, row.kind), made: row });
8793 }
8894
8995 /** An admin revokes a code: no new uses; forges already made keep their plan. */
src/actions/order.ts +22 −4
@@ -24,6 +24,7 @@
2424 import type { App } from "../app.ts";
2525 import { checkoutOf } from "../billing/checkout.ts";
2626 import { getOrder, holdName, markResent, markShown, move, unmarkShown, pendingFrom, MAX_PENDING_PER_ADDRESS, CHECKOUT_MS, nameHeld, newId, newTicket, dropPending, pendingCount, setSession, spawnedFor, ticketFits, MAX_PENDING, type Order } from "../billing/orders.ts";
27 import { noteRedeemed, spendAtCost } from "../billing/codes.ts";
2728 import { putEntitlement } from "../billing/store.ts";
2829 import { heldOf } from "../perf/held.ts";
2930 import type { User } from "../core/users.ts";
@@ -31,6 +32,7 @@ import { publicOrigin } from "../core/public_origin.ts";
3132 import { err, ok, type Result } from "../kernel/result.ts";
3233 import { isChildName } from "../core/proposal_token.ts";
3334 import type { Ctx } from "../http/context.ts";
35 import { atCostCode, quoteFor } from "../spawn/order_quote.ts";
3436 import { nameTaken, spawnDoor } from "../spawn/door.ts";
3537 import { FREE, getPlan, type Plan } from "../settings/plans.ts";
3638 import { reissueClaimFor } from "./spawn.ts";
@@ -40,7 +42,7 @@ import { askMaking, failOrder, mailLink, openLink } from "../spawn/making.ts";
4042 export { makingWatch } from "../spawn/making.ts";
4143
4244 export interface Refusal {
43 readonly field: "name" | "email" | "plan" | "place" | "form";
45 readonly field: "name" | "email" | "plan" | "place" | "code" | "form";
4446 readonly message: string;
4547 }
4648
@@ -96,7 +98,7 @@ export interface Placed {
9698 }
9799
98100 /** Validate, hold the name, make the checkout. Nothing is held if the checkout cannot be made. */
99 export async function placeOrder(app: App, input: { name: unknown; plan: unknown; email: unknown; address: string; place?: unknown }, url: URL, now = Date.now()): Promise<Result<Placed, Refusal>> {
101 export async function placeOrder(app: App, input: { name: unknown; plan: unknown; email: unknown; address: string; place?: unknown; code?: unknown }, url: URL, now = Date.now()): Promise<Result<Placed, Refusal>> {
100102 const plan = typeof input.plan === "string" ? getPlan(app.db, input.plan) : undefined;
101103 if (plan === undefined || plan.key === FREE || plan.priceUsd <= 0) return err({ field: "plan", message: "Pick one of the paid plans" });
102104 const email = emailOf(input.email);
@@ -109,12 +111,22 @@ export async function placeOrder(app: App, input: { name: unknown; plan: unknown
109111 if (pendingFrom(app.db, input.address, now) >= MAX_PENDING_PER_ADDRESS) return err({ field: "form", message: "You have orders waiting already; finish one or try again in half an hour" });
110112 const refused = await nameRefusal(app, name, plan, now, place);
111113 if (refused !== undefined) return err(refused);
114 // What the buyer pays follows the place: the plan's price, the difference for a dearer place, or
115 // with an at-cost code the place's cost and the payment fee. The amount is fixed here and kept
116 // on the order; the checkout charges exactly it.
117 const code = atCostCode(app, input.address, input.code);
118 if (!code.ok) return err({ field: "code", message: code.error });
119 if (code.value !== undefined && code.value.plan !== plan.key) return err({ field: "code", message: `That code is for the ${getPlan(app.db, code.value.plan)?.name ?? code.value.plan} plan` });
120 const quote = quoteFor(app, plan, place, code.value !== undefined);
121 if (!quote.ok) return err({ field: code.value !== undefined ? "code" : "place", message: quote.error });
122 const q = quote.value;
123 const note = q.atCost ? "at cost" : q.surchargeUsd > 0 ? `${q.placed}: +$${q.surchargeUsd} a month` : undefined;
112124 const id = newId();
113125 const ticket = newTicket();
114 if (!holdName(app.db, { id, name, plan: plan.key, priceUsd: plan.priceUsd, email, ticket, address: input.address, place }, now)) return err({ field: "name", message: "That name is held for someone else; try another" });
126 if (!holdName(app.db, { id, name, plan: plan.key, priceUsd: q.priceUsd, email, ticket, address: input.address, place, costCents: q.costCents, placed: q.placed, codeId: code.value?.id ?? "" }, now)) return err({ field: "name", message: "That name is held for someone else; try another" });
115127 const origin = publicOrigin(app.config.url, url.origin);
116128 const made = await provider.create({
117 orderId: id, forge: name, plan: plan.key, planName: plan.name, priceUsd: plan.priceUsd, email,
129 orderId: id, forge: name, plan: plan.key, planName: plan.name, priceUsd: q.priceUsd, ...(note === undefined ? {} : { note }), email,
118130 successUrl: `${origin}/pricing/done?order=${id}`, cancelUrl: `${origin}/pricing`,
119131 // The checkout stops being payable before the name's hold lapses.
120132 expiresAt: Math.floor((now + CHECKOUT_MS) / 1000),
@@ -144,6 +156,12 @@ export async function settleOrder(app: App, id: string, paid: { customer?: strin
144156 return o.state === "paid" ? makeForge(app, id, "paid") : o;
145157 }
146158 app.bus.append({ kind: "billing.order_paid", payload: { id, forge: o.name, plan: o.plan } });
159 // An at-cost code is spent when its sale is: the price it made was quoted before the payment.
160 if (o.codeId !== "") {
161 spendAtCost(app.db, o.codeId);
162 noteRedeemed(app.db, o.codeId, o.name);
163 app.bus.append({ kind: "billing.code.redeem", payload: { id: o.codeId, forge: o.name, plan: o.plan, atCost: true } });
164 }
147165 return makeForge(app, id, "paid");
148166 }
149167
src/billing/at_cost.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * What a forge on its own machine costs the buyer (#16205): plain arithmetic, no I/O.
3 *
4 * Three prices come from one place's monthly cost. The plan's price is the default. A place dearer
5 * than the plan's default place adds the difference, rounded up to the next dollar. A buyer with an
6 * at-cost code pays the place's cost plus the payment fee, rounded up to the next dollar: the
7 * fee is taken out of what is charged, so the charge is grossed up until the forge keeps the cost.
8 */
9
10 /**
11 * The payment provider's fee: a share of every charge, and a fixed amount on it (Stripe, US cards).
12 */
13 export const FEE_PERCENT = 2.9;
14 export const FEE_FIXED_CENTS = 30;
15
16 /** Whole dollars, rounded up: the unit a subscription is priced in. */
17 const upToDollar = (cents: number): number => Math.ceil(Math.max(0, cents) / 100 - 1e-9);
18
19 /** The provider's fee on a charge of `dollars`, in cents. */
20 export const feeCents = (dollars: number): number => (dollars <= 0 ? 0 : Math.round((dollars * 100 * FEE_PERCENT) / 100) + FEE_FIXED_CENTS);
21
22 /** The monthly charge, whole dollars, of an at-cost forge on a place that costs `costCents`. */
23 export const atCostUsd = (costCents: number): number => upToDollar((Math.max(0, costCents) + FEE_FIXED_CENTS) / (1 - FEE_PERCENT / 100));
24
25 /**
26 * What a place dearer than the plan's default adds to the monthly price, whole dollars; 0 when it
27 * is not dearer.
28 */
29 export const surchargeUsd = (defaultCents: number, placeCents: number): number => (placeCents > defaultCents ? upToDollar(placeCents - defaultCents) : 0);
30
31 /** One forge's month: what it costs, what it pays, what the provider takes and what is left. */
32 export interface Margin {
33 readonly costCents: number;
34 readonly paysCents: number;
35 readonly feeCents: number;
36 /** An at-cost forge reads zero: its price is the cost and the fee, not a profit forgone. */
37 readonly marginCents: number;
38 }
39
40 export function marginOf(paysUsd: number, costCents: number, atCost: boolean): Margin {
41 const fee = feeCents(paysUsd);
42 const pays = Math.round(paysUsd * 100);
43 return { costCents, paysCents: pays, feeCents: fee, marginCents: atCost ? 0 : pays - fee - costCents };
44 }
src/billing/codes.ts +37 −9
@@ -15,18 +15,25 @@ const SHAPE = /^forge-[a-z0-9]{4}-[a-z0-9]{4}$/;
1515 export const MAX_USES = 1000;
1616 export const MAX_NOTE = 80;
1717
18 export type CodeRefusal = "unknown" | "used_up" | "expired" | "revoked";
18 /**
19 * `plan` gives a plan free; `at_cost` sells a forge on its own machine for what its place costs.
20 */
21 export type CodeKind = "plan" | "at_cost";
22
23 export type CodeRefusal = "unknown" | "used_up" | "expired" | "revoked" | "wrong_kind";
1924
2025 export const CODE_WORDS: Record<CodeRefusal, string> = {
2126 unknown: "That code is not one this forge knows",
2227 used_up: "That code has been used as many times as it allows",
2328 expired: "That code has expired",
2429 revoked: "That code was cancelled",
30 wrong_kind: "That code is not for this form: a code that sells a forge at cost is used on the pricing page, a gift code when starting a forge",
2531 };
2632
2733 export interface Code {
2834 readonly id: string;
2935 readonly plan: string;
36 readonly kind: CodeKind;
3037 readonly note: string;
3138 readonly uses: number;
3239 readonly used: number;
@@ -42,12 +49,12 @@ export interface Redeemed {
4249 }
4350
4451 interface Row {
45 id: string; plan: string; note: string; uses: number; used: number; expires_at: string | null;
52 id: string; plan: string; kind: CodeKind; note: string; uses: number; used: number; expires_at: string | null;
4653 revoked_at: string | null; made_by: string; made_at: string;
4754 }
4855
4956 const fromRow = (r: Row): Code => ({
50 id: r.id, plan: r.plan, note: r.note, uses: r.uses, used: r.used,
57 id: r.id, plan: r.plan, kind: r.kind, note: r.note, uses: r.uses, used: r.used,
5158 ...(r.expires_at === null ? {} : { expiresAt: r.expires_at }),
5259 ...(r.revoked_at === null ? {} : { revokedAt: r.revoked_at }),
5360 madeBy: r.made_by, madeAt: r.made_at,
@@ -69,6 +76,7 @@ function randomGroup(): string {
6976
7077 export interface NewCode {
7178 plan: string;
79 kind?: CodeKind;
7280 note: string;
7381 uses: number;
7482 expiresAt?: string;
@@ -81,8 +89,8 @@ export function insertCode(db: Database, n: NewCode, now = new Date()): { code:
8189 const id = crypto.randomUUID().slice(0, 8);
8290 const at = now.toISOString();
8391 db.query(
84 "INSERT INTO gift_code (id, hash, plan, note, uses, expires_at, made_by, made_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
85 ).run(id, hashCode(code), n.plan, n.note, n.uses, n.expiresAt ?? null, n.madeBy, at);
92 "INSERT INTO gift_code (id, hash, plan, note, uses, expires_at, made_by, made_at, kind) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
93 ).run(id, hashCode(code), n.plan, n.note, n.uses, n.expiresAt ?? null, n.madeBy, at, n.kind ?? "plan");
8694 return { code, row: getCode(db, id)! };
8795 }
8896
@@ -97,16 +105,27 @@ const refusalOf = (c: Code, now: Date): CodeRefusal | undefined =>
97105 : c.used >= c.uses ? "used_up"
98106 : undefined;
99107
100 /** The code a person typed, if it can be used now; nothing is spent. */
101 export function lookupCode(db: Database, input: unknown, now = new Date()): Result<Code, CodeRefusal> {
108 /**
109 * The code a person typed, if it can be used now as a code of `kind`; nothing is spent. A code of
110 * the other kind is refused as such: an at-cost code never gives a plan free.
111 */
112 export function lookupCode(db: Database, input: unknown, now = new Date(), kind: CodeKind = "plan"): Result<Code, CodeRefusal> {
102113 const code = normalizeCode(input);
103114 const r = code === undefined ? undefined : db.query<Row, [string]>("SELECT * FROM gift_code WHERE hash = ?1").get(hashCode(code));
104115 if (!r) return err("unknown");
105116 const c = fromRow(r);
106 const why = refusalOf(c, now);
117 if (c.kind !== kind) return err("wrong_kind");
118 // An at-cost code's open checkouts hold its uses until they are paid or lapse: one use cannot
119 // fund many pending orders.
120 const held = kind === "at_cost" ? heldUses(db, c.id, now.getTime()) : 0;
121 const why = refusalOf(held === 0 ? c : { ...c, used: c.used + held }, now);
107122 return why === undefined ? ok(c) : err(why);
108123 }
109124
125 /** The uses of an at-cost code that checkouts still open (pending, name held) are waiting on. */
126 export const heldUses = (db: Database, id: string, now: number): number =>
127 db.query<{ n: number }, [string, number]>("SELECT COUNT(*) AS n FROM forge_order WHERE code_id = ?1 AND state = 'pending' AND hold_until > ?2").get(id, now)?.n ?? 0;
128
110129 /** Spend one use, in one statement: the last use goes to one caller only. */
111130 export function claimCode(db: Database, input: unknown, now = new Date()): Result<Code, CodeRefusal> {
112131 const seen = lookupCode(db, input, now);
@@ -114,13 +133,22 @@ export function claimCode(db: Database, input: unknown, now = new Date()): Resul
114133 const done = db
115134 .query(
116135 `UPDATE gift_code SET used = used + 1
117 WHERE id = ?1 AND revoked_at IS NULL AND used < uses AND (expires_at IS NULL OR expires_at > ?2)`,
136 WHERE id = ?1 AND kind = 'plan' AND revoked_at IS NULL AND used < uses AND (expires_at IS NULL OR expires_at > ?2)`,
118137 )
119138 .run(seen.value.id, now.toISOString());
120139 if (done.changes === 0) return lookupCode(db, input, now);
121140 return ok({ ...seen.value, used: seen.value.used + 1 });
122141 }
123142
143 /**
144 * Spend one use of an at-cost code by its id, when its order was paid. The use was held while the
145 * checkout was open (`heldUses`), so a payment that arrives is honoured, even if the code was
146 * revoked meanwhile: the buyer was charged the price it quoted.
147 */
148 export function spendAtCost(db: Database, id: string): void {
149 db.query("UPDATE gift_code SET used = used + 1 WHERE id = ?1 AND kind = 'at_cost'").run(id);
150 }
151
124152 /** Give a use back: the forge it was for was not made. */
125153 export function releaseCode(db: Database, id: string): void {
126154 db.query("UPDATE gift_code SET used = MAX(0, used - 1) WHERE id = ?1").run(id);
src/billing/orders.ts +23 −6
@@ -51,18 +51,27 @@ export interface Order {
5151 readonly resentAt: number | null;
5252 /** The place chosen for a forge on a cloud account; empty for the plan's default. */
5353 readonly place: string;
54 /** What its machine costs a month, US dollar cents, when it was bought; 0 for a hosted forge. */
55 readonly costCents: number;
56 /**
57 * The place it was bought at, resolved (the default's id when none was chosen); empty when
58 * hosted.
59 */
60 readonly placed: string;
61 /** The at-cost code it was bought with; empty for none. */
62 readonly codeId: string;
5463 }
5564
5665 interface Row {
5766 id: string; name: string; plan: string; price_usd: number; paid_at: number; email: string; state: OrderState; ticket_hash: string; session_id: string;
5867 customer_id: string; subscription_id: string; reason: string; created_at: number; hold_until: number; updated_at: number;
59 shown_at: number | null; resent_at: number | null; place: string;
68 shown_at: number | null; resent_at: number | null; place: string; cost_cents: number; placed: string; code_id: string;
6069 }
6170
6271 const fromRow = (r: Row): Order => ({
6372 id: r.id, name: r.name, plan: r.plan, priceUsd: r.price_usd, paidAt: r.paid_at, email: r.email, state: r.state, sessionId: r.session_id, customerId: r.customer_id,
6473 subscriptionId: r.subscription_id, reason: r.reason, createdAt: r.created_at, holdUntil: r.hold_until, updatedAt: r.updated_at,
65 shownAt: r.shown_at, resentAt: r.resent_at, place: r.place,
74 shownAt: r.shown_at, resentAt: r.resent_at, place: r.place, costCents: r.cost_cents, placed: r.placed, codeId: r.code_id,
6675 });
6776
6877 export const newId = (): string => `ord_${crypto.randomUUID().replace(/-/g, "")}`;
@@ -104,13 +113,13 @@ export const pendingCount = (db: Database, now: number): number =>
104113 db.query<{ n: number }, [number]>("SELECT COUNT(*) AS n FROM forge_order WHERE state = 'pending' AND hold_until > ?1").get(now)?.n ?? 0;
105114
106115 /** Write a new pending order. The hold is checked and the row written in one transaction. False when the name is held. */
107 export function holdName(db: Database, o: { id: string; name: string; plan: string; priceUsd: number; email: string; ticket: string; address: string; place?: string }, now: number): boolean {
116 export function holdName(db: Database, o: { id: string; name: string; plan: string; priceUsd: number; email: string; ticket: string; address: string; place?: string; costCents?: number; placed?: string; codeId?: string }, now: number): boolean {
108117 return db.transaction(() => {
109118 if (nameHeld(db, o.name, now)) return false;
110119 db.query(
111 `INSERT INTO forge_order (id, name, plan, email, state, ticket_hash, created_at, hold_until, updated_at, address, price_usd, place)
112 VALUES (?1, ?2, ?3, ?4, 'pending', ?5, ?6, ?7, ?6, ?8, ?9, ?10)`,
113 ).run(o.id, o.name, o.plan, o.email, sha256(o.ticket), now, now + HOLD_MS, o.address, o.priceUsd, o.place ?? "");
120 `INSERT INTO forge_order (id, name, plan, email, state, ticket_hash, created_at, hold_until, updated_at, address, price_usd, place, cost_cents, placed, code_id)
121 VALUES (?1, ?2, ?3, ?4, 'pending', ?5, ?6, ?7, ?6, ?8, ?9, ?10, ?11, ?12, ?13)`,
122 ).run(o.id, o.name, o.plan, o.email, sha256(o.ticket), now, now + HOLD_MS, o.address, o.priceUsd, o.place ?? "", o.costCents ?? 0, o.placed ?? "", o.codeId ?? "");
114123 return true;
115124 })();
116125 }
@@ -196,6 +205,14 @@ export function soldOrders(db: Database): Order[] {
196205 return db.query<Row, []>("SELECT * FROM forge_order WHERE state = 'spawned' AND session_id != ''").all().map(fromRow);
197206 }
198207
208 /**
209 * Every bought order whose forge is made or being made, newest first: the owner's billing view
210 * reads margin from them.
211 */
212 export function soldForges(db: Database, limit = 200): Order[] {
213 return db.query<Row, [number]>("SELECT * FROM forge_order WHERE state IN ('making', 'spawned') AND session_id != '' ORDER BY paid_at DESC LIMIT ?1").all(limit).map(fromRow);
214 }
215
199216 /** Say on a made order what became of its forge (a lapse); its state does not change. */
200217 export function noteOrder(db: Database, id: string, reason: string): void {
201218 db.query("UPDATE forge_order SET reason = ?2 WHERE id = ?1 AND state = 'spawned'").run(id, reason);
src/billing/plan_words.ts +5
@@ -61,6 +61,11 @@ export function creditWords(p: Pick<Plan, "priceUsd" | "creditUsd">, startUsd: n
6161 */
6262 export const monthlyPrice = (usd: number): string => (usd === 0 ? "Free" : `$${usd} a month`);
6363
64 /**
65 * How the plan's price reads once a place is chosen: the difference added, as the sum of its parts.
66 */
67 export const surchargeParts = (planUsd: number, extraUsd: number): string => `$${planUsd} and $${extraUsd} for the place`;
68
6469 export function planWords(p: Plan, links: BillingLinks = {}, startUsd = 0, askUsd: number = ASK_USD): PlanWords {
6570 const free = p.priceUsd === 0;
6671 const buy = free ? undefined : links[p.size];
src/billing/sold.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * The owner's view of what was sold (#16205): per bought forge, its plan, its place, what its
3 * machine costs a month, what the buyer pays, and the margin. Plain rows from the orders, which
4 * keep the quote they were sold at, so a catalog that moved later rewrites no past sale. A
5 * forge sold at cost reads zero margin, and one sold before orders kept a cost reads unknown.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { marginOf, type Margin } from "./at_cost.ts";
10 import { soldForges } from "./orders.ts";
11
12 export interface SoldRow {
13 readonly forge: string;
14 readonly plan: string;
15 /** The place it runs at; empty for a forge sold hosted. */
16 readonly place: string;
17 readonly atCost: boolean;
18 /** Absent when the order kept no cost (hosted, or sold before costs were kept). */
19 readonly month?: Margin;
20 readonly paysUsd: number;
21 }
22
23 export function soldRows(db: Database): SoldRow[] {
24 return soldForges(db).map((o) => ({
25 forge: o.name,
26 plan: o.plan,
27 place: o.placed,
28 atCost: o.codeId !== "",
29 paysUsd: o.priceUsd,
30 ...(o.costCents > 0 ? { month: marginOf(o.priceUsd, o.costCents, o.codeId !== "") } : {}),
31 }));
32 }
33
34 /** Dollars and cents, with a minus sign for a loss. */
35 export const money = (cents: number): string => `${cents < 0 ? "-" : ""}$${(Math.abs(cents) / 100).toFixed(2)}`;
src/billing/stripe.ts +3 −1
@@ -70,6 +70,8 @@ export interface CheckoutRequest {
7070 readonly plan: string;
7171 readonly planName: string;
7272 readonly priceUsd: number;
73 /** Said beside the plan on the checkout page: a dearer place's surcharge, or "at cost". */
74 readonly note?: string;
7375 readonly email: string;
7476 readonly successUrl: string;
7577 readonly cancelUrl: string;
@@ -156,7 +158,7 @@ export function stripeClient(key: string, fetchFn: typeof fetch = fetch): Stripe
156158 currency: "usd",
157159 unit_amount: Math.round(req.priceUsd * 100),
158160 recurring: { interval: "month" },
159 product_data: { name: `${req.planName} forge` },
161 product_data: { name: `${req.planName} forge${req.note === undefined ? "" : ` (${req.note})`}` },
160162 },
161163 }],
162164 metadata: { order: req.orderId, forge: req.forge, plan: req.plan },
src/contract/openapi/routes/postApiV1Codes.ts +4 −4
@@ -3,11 +3,11 @@ import type { Route } from "../shared.ts";
33 export const route: Route = {
44 method: "post",
55 path: "/api/v1/codes",
6 summary: "Make a gift code that gives a plan for free. dryRun is true unless false",
7 detail: "Make a gift code that gives a plan for free (a person admin's token, admin scope). dryRun is true unless false; the plain code and its /?code= link are in the answer that makes it, once",
6 summary: "Make a gift code (a plan for free, or a forge at cost). dryRun is true unless false",
7 detail: "Make a gift code that gives a plan for free (a person admin's token, admin scope). dryRun is true unless false; the plain code and its /?code= (at cost: /pricing?code=) link are in the answer that makes it, once",
88 auth: true,
99 role: "admin",
10 body: { plan: "a paid plan key", uses: "how many times, default 1", note: "optional, up to 80 characters", expires: "optional date or time", dryRun: "true unless false" },
11 refusals: { not_found: "the token is not a person who administers the forge (404)", bad_plan: "plan is not a paid plan (422)", bad_uses: "uses is not 1 to 1000 (422)", bad_note: "note is too long (422)", bad_expiry: "expires is not a future date (422)" },
10 body: { kind: "plan (gives the plan free, default) or at_cost (sells a forge on its own machine for the place's cost, plus the payment fee, to the next dollar)", plan: "a paid plan key", uses: "how many times, default 1", note: "optional, up to 80 characters", expires: "optional date or time", dryRun: "true unless false" },
11 refusals: { bad_kind: "kind is not plan or at_cost (422)", not_found: "the token is not a person who administers the forge (404)", bad_plan: "plan is not a paid plan (422)", bad_uses: "uses is not 1 to 1000 (422)", bad_note: "note is too long (422)", bad_expiry: "expires is not a future date (422)" },
1212 refuses: [404, 422],
1313 };
src/core/migration-pins/20261127200000-order-quote.pin added +1
@@ -0,0 +1,1 @@
1 7a87046eaa6bc72fdbe29a0b73c59c5644b80adcf16a829916c61657d48bf2f5
src/core/migrations/20261127200000-order-quote.ts added +11
@@ -0,0 +1,11 @@
1 // A sale's quote (#16205): what the machine of an order costs a month (US dollar cents), the place
2 // it was bought at, and the at-cost code it was bought with, so the owner's billing view reads
3 // margin from the order and not from a catalog that has moved. A code has a kind: `plan` gives a
4 // plan free (all that existed), `at_cost` sells a forge for the place's cost. Additive; older rows
5 // keep the empty values.
6 export default `
7 ALTER TABLE forge_order ADD COLUMN cost_cents INTEGER NOT NULL DEFAULT 0;
8 ALTER TABLE forge_order ADD COLUMN placed TEXT NOT NULL DEFAULT '';
9 ALTER TABLE forge_order ADD COLUMN code_id TEXT NOT NULL DEFAULT '';
10 ALTER TABLE gift_code ADD COLUMN kind TEXT NOT NULL DEFAULT 'plan';
11 `;
src/spawn/door.ts +1 −1
@@ -445,7 +445,7 @@ export async function spawnDoor(
445445 if (typeof placeIn !== "string" || placeIn.length > MAX_ID) return invalid("place", "must be a place id, provider:datacenter:size (GET /api/v1/places)");
446446 const asked = placeIn.trim();
447447 if (asked !== "" && where.where === "hosted") return invalid("place", "a forge on this plan runs inside this forge; a place is for a paid plan on a cloud account");
448 const cloud = { plan: catalogPlan(typeof size === "string" ? size : "small"), place: asked, dearer: user?.isAdmin === true };
448 const cloud = { plan: catalogPlan(typeof size === "string" ? size : "small"), place: asked, dearer: user?.isAdmin === true || paid };
449449 if (where.where === "cloud") {
450450 const room = (at: string) => cloudPlacement(ctx.app, where, { orderId: "", ...cloud, place: at }).room?.();
451451 const full = room(asked);
src/spawn/order_quote.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * What a paid forge costs its buyer, from the place it runs at (#16205): the plan's price when the
3 * place is the plan's default, the difference added when the buyer chose a dearer one, and the
4 * place's cost plus the payment fee when they hold an at-cost code. One function answers the
5 * pricing page (to show it before anyone pays), the checkout (the amount charged) and the order
6 * (the quote it keeps for the owner's margin).
7 */
8
9 import type { App } from "../app.ts";
10 import { atCostUsd, surchargeUsd } from "../billing/at_cost.ts";
11 import { CODE_WORDS, lookupCode, takeTry, type Code } from "../billing/codes.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13 import type { Plan } from "../settings/plans.ts";
14 import { placeChoice, type PlaceChoice } from "./making.ts";
15
16 export interface Quote {
17 /** What the buyer is charged a month, whole dollars. */
18 readonly priceUsd: number;
19 /** What it would be with no code: the plan's price and the place's surcharge. */
20 readonly listUsd: number;
21 readonly surchargeUsd: number;
22 readonly atCost: boolean;
23 /** What the machine costs a month, US dollar cents; 0 when the forge runs hosted. */
24 readonly costCents: number;
25 /** The place, resolved; empty when hosted. */
26 readonly placed: string;
27 }
28
29 const AT_COST_HOSTED = "An at-cost code is for a forge on its own machine; paid forges run hosted on this forge, so it has no machine to cost";
30
31 /**
32 * The price of `plan` at `placeId` (empty for the plan's default) on `choice`, which is none when
33 * forges run hosted.
34 */
35 export function priceAt(choice: PlaceChoice | undefined, plan: Plan, placeId: string, atCost: boolean): Result<Quote, string> {
36 if (choice === undefined) {
37 if (atCost) return err(AT_COST_HOSTED);
38 return ok({ priceUsd: plan.priceUsd, listUsd: plan.priceUsd, surchargeUsd: 0, atCost: false, costCents: 0, placed: "" });
39 }
40 const place = placeId === "" ? undefined : choice.places.find((p) => p.id === placeId);
41 if (placeId !== "" && place === undefined) return err(`There is no place ${placeId.slice(0, 80)} for a ${plan.name} forge`);
42 const costCents = place?.costCents ?? choice.defaultCents;
43 const placed = place?.id ?? choice.defaultId;
44 if (atCost && costCents <= 0) return err("This forge cannot price that place yet: the catalog has no cost for it");
45 const extra = surchargeUsd(choice.defaultCents, costCents);
46 const listUsd = plan.priceUsd + extra;
47 return ok({ priceUsd: atCost ? atCostUsd(costCents) : listUsd, listUsd, surchargeUsd: extra, atCost, costCents, placed });
48 }
49
50 /**
51 * The quote for `plan` as the sale reads it: the list for its place, and whether a code was typed.
52 */
53 export function quoteFor(app: App, plan: Plan, placeId: string, atCost: boolean): Result<Quote, string> {
54 return priceAt(placeChoice(app, plan, true), plan, placeId, atCost);
55 }
56
57 /**
58 * The at-cost code a buyer typed, or the sentence that says why not. Counts one try for the
59 * client, as a gift code does, so codes cannot be guessed by trying; an empty code is none.
60 */
61 export function atCostCode(app: App, bucket: string, input: unknown): Result<Code | undefined, string> {
62 if (input === undefined || input === null || (typeof input === "string" && input.trim() === "")) return ok(undefined);
63 if (!takeTry(app.db, bucket)) return err("Too many codes tried from here; try again in a few minutes");
64 const seen = lookupCode(app.db, input, new Date(), "at_cost");
65 return seen.ok ? ok(seen.value) : err(CODE_SAYS[seen.error]);
66 }
67
68 const CODE_SAYS = { ...CODE_WORDS, wrong_kind: "That code gives a plan free: use it when starting a forge, not here" };
src/tui/screens/codes.ts +10 −4
@@ -25,7 +25,7 @@ export function codeRows(f: Session): { rows: ListRow[]; ids: string[]; plans: s
2525 const rows = read.value.codes.map((c) => {
2626 const state = c.revokedAt !== undefined ? "revoked" : c.used >= c.uses ? "used up" : "";
2727 const who = c.redeemed.map((r) => r.forge).join(", ");
28 return { title: `${c.plan}${c.note === "" ? "" : ` · ${c.note}`}`, secondary: `${c.used} of ${c.uses} used${state === "" ? "" : ` · ${state}`}`, meta: who };
28 return { title: `${c.plan}${c.kind === "at_cost" ? " · at cost" : ""}${c.note === "" ? "" : ` · ${c.note}`}`, secondary: `${c.used} of ${c.uses} used${state === "" ? "" : ` · ${state}`}`, meta: who };
2929 });
3030 return { rows, ids: read.value.codes.map((c) => c.id), plans: read.value.plans };
3131 }
@@ -33,10 +33,11 @@ export function codeRows(f: Session): { rows: ListRow[]; ids: string[]; plans: s
3333 export function codesScreen(f: Session, ctx: Ctx): Screen {
3434 const state = new ListState();
3535 let plan = 0;
36 let kind: "plan" | "at_cost" = "plan";
3637 let note = "";
3738 const screen: Screen = {
3839 title: "Gift codes",
39 keys: [binding(["j", "k"], "move cursor"), binding(["p"], "choose plan"), binding(["n"], "make a code"), binding(["x"], "revoke"), binding(["esc"], "back")],
40 keys: [binding(["j", "k"], "move cursor"), binding(["p"], "choose plan"), binding(["c"], "free or at cost"), binding(["n"], "make a code"), binding(["x"], "revoke"), binding(["esc"], "back")],
4041 async load(signal) {
4142 live(f, signal, { where: (e) => e.kind.startsWith("billing.code.") }, () => ctx.invalidate());
4243 },
@@ -46,7 +47,7 @@ export function codesScreen(f: Session, ctx: Ctx): Screen {
4647 state.clamp(rows.length);
4748 const [head, body] = split(area, "v", [len(2), fill(1)]);
4849 const chosen = plans[plan % Math.max(plans.length, 1)] ?? "";
49 s.text(head!.x, head!.y, truncate(note !== "" ? note : `Plan ${chosen}: n makes a code, p changes the plan`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
50 s.text(head!.x, head!.y, truncate(note !== "" ? note : `Plan ${chosen}, ${kind === "at_cost" ? "sold at cost" : "given free"}: n makes a code, p changes the plan, c free or at cost`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
5051 if (rows.length === 0) s.text(body!.x, body!.y, truncate("No code yet.", body!.w), style(c.mutedFg, c.bg), body!.x + body!.w);
5152 else drawList(s, body!, c, state, rows);
5253 },
@@ -57,9 +58,14 @@ export function codesScreen(f: Session, ctx: Ctx): Screen {
5758 ctx.invalidate();
5859 return true;
5960 }
61 if (e.key === "c") {
62 kind = kind === "plan" ? "at_cost" : "plan";
63 ctx.invalidate();
64 return true;
65 }
6066 if (e.key === "n") {
6167 const chosen = plans[plan % Math.max(plans.length, 1)];
62 const made = makeCode(f.app, f.user, { plan: chosen ?? "" }, publicOrigin(f.app.config.url, `http://localhost:${f.app.config.port}`));
68 const made = makeCode(f.app, f.user, { plan: chosen ?? "", kind }, publicOrigin(f.app.config.url, `http://localhost:${f.app.config.port}`));
6369 note = made.ok ? `Shown once: ${made.value.code} ${made.value.link}` : made.error === "not_found" ? "Not found." : `${CODE_ERRORS[made.error]}.`;
6470 ctx.invalidate();
6571 return true;
src/tui/screens/sold.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * Sold forges in the terminal, a forge admin's who is a person: the same `soldRows` the Billing
3 * page lists. Per bought forge its plan and place, what its machine costs a month, what the buyer
4 * pays, the provider's fee and the margin; at cost reads zero.
5 */
6
7 import { money, soldRows, type SoldRow } from "../../billing/sold.ts";
8 import type { Ctx, Screen } from "../app/app.ts";
9 import { binding } from "../app/keys.ts";
10 import type { Session } from "../session.ts";
11 import { ListState, drawList, type ListRow } from "./common.ts";
12 import type { PaletteEntry } from "./entries.ts";
13 import { emptyState } from "../ui/widgets.ts";
14
15 const isAdmin = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind !== "agent";
16
17 const rowOf = (r: SoldRow): ListRow => ({
18 title: r.forge,
19 secondary: `${r.plan} · ${r.place === "" ? "hosted here" : r.place}${r.atCost ? " · at cost" : ""}`,
20 meta:
21 r.month === undefined
22 ? `pays $${r.paysUsd} · cost not kept`
23 : `costs ${money(r.month.costCents)} · pays ${money(r.month.paysCents)} · fee ${money(r.month.feeCents)} · margin ${money(r.month.marginCents)}`,
24 });
25
26 /** Nothing for anyone but an admin who is a person. */
27 export const soldListRows = (f: Session): ListRow[] => (isAdmin(f) ? soldRows(f.app.db).map(rowOf) : []);
28
29 export function soldScreen(f: Session, ctx: Ctx): Screen {
30 const state = new ListState();
31 return {
32 title: "Sold forges",
33 keys: [binding(["j", "k"], "move cursor"), binding(["esc"], "back")],
34 render(area, s) {
35 const rows = soldListRows(f);
36 state.clamp(rows.length);
37 if (rows.length === 0) emptyState(s, area, ctx.theme.c, { title: "No forge has been sold yet.", body: "A forge bought on the pricing page appears here with its cost and margin." });
38 else drawList(s, area, ctx.theme.c, state, rows);
39 },
40 key: (e) => state.key(e, soldListRows(f).length),
41 };
42 }
43
44 /** What each bought forge costs, pays and leaves. */
45 export const entry: PaletteEntry = {
46 rank: 575,
47 id: "sold",
48 title: "Sold forges",
49 hint: "what each bought forge costs, pays and leaves",
50 offered: isAdmin,
51 run: (session, ctx) => ctx.push(soldScreen(session, ctx)),
52 };
src/web/pages/billing.ts +27 −4
@@ -16,6 +16,7 @@ import { lapseFor, type Lapse } from "../../billing/lapse.ts";
1616 import { lapseRule } from "../../billing/lapse_rule.ts";
1717 import { lapseNotice } from "../../billing/lapse_words.ts";
1818 import { failedOrders } from "../../billing/orders.ts";
19 import { money, soldRows } from "../../billing/sold.ts";
1920 import { CODE_ERRORS, makeCode, readCodes, revoke, type CodeError } from "../../actions/codes.ts";
2021 import { publicOrigin } from "../../core/public_origin.ts";
2122 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -58,7 +59,7 @@ function codesSection(ctx: Ctx, shown: Shown | undefined, r: Refused | undefined
5859 return html`<li class="row" data-code="${c.id}">
5960 <dl class="row-fields">
6061 <dt class="sr-only">Gives</dt>
61 <dd><span class="mono">${c.plan}</span> <span class="muted small">${c.note}${c.expiresAt === undefined ? "" : ` · until ${day(c.expiresAt)}`}</span></dd>
62 <dd><span class="mono">${c.plan}</span> <span class="small">${c.kind === "at_cost" ? "at cost" : "free"}</span> <span class="muted small">${c.note}${c.expiresAt === undefined ? "" : ` · until ${day(c.expiresAt)}`}</span></dd>
6263 <dt class="sr-only">Used</dt>
6364 <dd class="small">${c.used} of ${c.uses} used${state === "" ? "" : ` · ${state}`} · <span class="muted">${redeemed}</span></dd>
6465 </dl>
@@ -80,6 +81,7 @@ function codesSection(ctx: Ctx, shown: Shown | undefined, r: Refused | undefined
8081 ${copyField("gift-link", shown.link, "The link to send", "Copy the link")}
8182 </div>`}
8283 <form class="row-fields" method="post" action="${PATH}/codes" id="make-code">
84 ${selectField(planChoice(kept(r, { label: "Kind", name: "kind", type: "select", options: [{ value: "plan", label: "Gives the plan free", selected: true }, { value: "at_cost", label: "Sells it at cost" }] })))}
8385 ${selectField(planChoice(kept(r, { label: "Plan it gives", name: "plan", type: "select", options: plans.map((p, i) => ({ value: p, label: p, selected: i === 0 })) })))}
8486 ${formField(kept(r, { label: "Uses", name: "uses", type: "number", value: "1" }))}
8587 ${formField(kept(r, { label: "Note", name: "note", value: "", hint: "For Mark" }))}
@@ -97,10 +99,31 @@ function codesSection(ctx: Ctx, shown: Shown | undefined, r: Refused | undefined
9799 const planChoice = (o: FieldOptions) => ({ ...o, options: [...(o.options ?? [])] });
98100
99101 /** The field of the code form each refusal belongs beside. */
100 const CODE_FIELD: Record<Exclude<CodeError, "not_found">, string> = { bad_plan: "plan", bad_uses: "uses", bad_note: "note", bad_expiry: "expires", no_such_code: "plan" };
102 const CODE_FIELD: Record<Exclude<CodeError, "not_found">, string> = { bad_kind: "kind", bad_plan: "plan", bad_uses: "uses", bad_note: "note", bad_expiry: "expires", no_such_code: "plan" };
101103
102104 const codeWords = (e: CodeError): string => (e === "not_found" ? "Not found" : CODE_ERRORS[e]);
103105
106 /**
107 * Sold forges: per forge its plan, place, cost, what it pays and the margin; at cost reads zero,
108 * not a loss.
109 */
110 function soldSection(ctx: Ctx): Html | null {
111 if (!isPerson(ctx)) return null;
112 const sold = soldRows(ctx.app.db);
113 if (sold.length === 0) return null;
114 return html`<section class="settings-block" id="sold" data-sold>
115 <h2>Sold forges</h2>
116 <p class="muted small">A month of each: what its machine costs, what the buyer pays, the provider's fee, and what is left.</p>
117 <dl class="status-rows">${sold.map((r) => html`<div class="status-row" data-sold-forge="${r.forge}">
118 <dt class="mono">${r.forge}</dt>
119 <dd>${r.plan} · ${r.place === "" ? "hosted here" : r.place}${r.atCost ? " · at cost" : ""}</dd>
120 <dd class="status-act">${r.month === undefined
121 ? html`pays $${r.paysUsd} · cost not kept`
122 : html`costs ${money(r.month.costCents)} · pays ${money(r.month.paysCents)} · fee ${money(r.month.feeCents)} · margin ${money(r.month.marginCents)}`}</dd>
123 </div>`)}</dl>
124 </section>`;
125 }
126
104127 /** The Payment links section: one https field per size a paid plan sits on, saved in one submit. */
105128 function linksSection(ctx: Ctx, r: Refused | undefined): Html | null {
106129 const links = readBillingLinks(ctx.app, ctx.auth.user);
@@ -263,7 +286,7 @@ function billingView(ctx: Ctx, shown?: Shown, status = 200, refusal?: Refused):
263286 </form>
264287 </li>`)}</ul>
265288 </section>`;
266 const body = html`${stripe}${orders}<section class="settings-block">
289 const body = html`${stripe}${orders}${soldSection(ctx)}<section class="settings-block">
267290 <h2>Plans</h2>
268291 <p class="muted small">Choose the plan each forge is on.</p>
269292 ${rows.length === 0
@@ -292,7 +315,7 @@ export async function billingMakeCode(ctx: Ctx): Promise<Response> {
292315 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return notFoundPage(ctx);
293316 const form = await readForm(ctx, "admin");
294317 if (form instanceof Response) return form;
295 const values = { plan: field(form, "plan"), uses: field(form, "uses"), note: field(form, "note"), expires: field(form, "expires") };
318 const values = { kind: field(form, "kind"), plan: field(form, "plan"), uses: field(form, "uses"), note: field(form, "note"), expires: field(form, "expires") };
296319 const made = makeCode(ctx.app, ctx.auth.user, values, publicOrigin(ctx.app.config.url, ctx.url.origin));
297320 if (!made.ok) return made.error === "not_found" ? notFoundPage(ctx) : billingView(ctx, undefined, 422, refused(form, { [CODE_FIELD[made.error]]: `${codeWords(made.error)}.` }));
298321 return billingView(ctx, { code: made.value.code, link: made.value.link });
src/web/pages/pricing.ts +75 −13
@@ -10,13 +10,16 @@
1010 import { setCookie } from "../../auth/cookies.ts";
1111 import { deliverLink, mayView, NO_PROVIDER, placeOrder, reconcileOrder, resendLink, type Refusal } from "../../actions/order.ts";
1212 import { cloudLapseWords, lapseRule, lapseRuleWords } from "../../billing/lapse_rule.ts";
13 import type { Code } from "../../billing/codes.ts";
14 import { ok, type Result } from "../../kernel/result.ts";
15 import { atCostCode, quoteFor, type Quote } from "../../spawn/order_quote.ts";
1316 import { getPaidPlacement } from "../../settings/paid_placement.ts";
1417 import { mailerOf } from "../../actions/verify.ts";
1518 import { getBaseDomain } from "../../settings/pinned_domain.ts";
1619 import { limitValue } from "../../settings/limits.ts";
1720 import { getPinned, urlOf } from "../../core/pinned.ts";
1821 import { openLink } from "../../spawn/making.ts";
19 import { AFTER_PAYMENT_STEPS, planWords, priceLine } from "../../billing/plan_words.ts";
22 import { AFTER_PAYMENT_STEPS, monthlyPrice, planWords, priceLine, surchargeParts } from "../../billing/plan_words.ts";
2023 import { checkoutOf } from "../../billing/checkout.ts";
2124 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
2225 import { cookieValue, type Ctx } from "../../http/context.ts";
@@ -50,6 +53,8 @@ interface Values {
5053 readonly email: string;
5154 /** A Places id for a forge on a cloud account; empty for the plan's default. */
5255 readonly place: string;
56 /** An at-cost code, as typed; empty for none. */
57 readonly code?: string;
5358 }
5459
5560 /** The lapse words: for a forge on its own machine (a paid placement on a cloud, or this order's own row), else the hosted ones. */
@@ -58,7 +63,37 @@ const mailOn = (ctx: Ctx): boolean => mailerOf(ctx.app, { id: "order" }) !== und
5863
5964 const isBuyer = (ctx: Ctx): boolean => ctx.auth.user === undefined || ctx.auth.user.kind === "user";
6065
61 function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["field"], string>>, door = getDoorSettings(ctx.app.db)): Html {
66 /** What the typed code came to: none, a usable at-cost code, or the sentence that says why not. */
67 type Typed = Result<Code | undefined, string>;
68
69 /**
70 * The code a visitor typed or followed, looked up for the page. Every look counts a try for the
71 * client (`atCostCode`), so codes cannot be guessed by asking the page; a form with no code, or a
72 * forge that sells nothing at cost, looks nothing up.
73 */
74 function typedCode(ctx: Ctx, code: string): Typed {
75 if (code === "" || checkoutOf(ctx.app) === undefined || getPaidPlacement(ctx.app.db).where !== "cloud") return ok(undefined);
76 return atCostCode(ctx.app, clientBucket(ctx.request), code);
77 }
78
79 /**
80 * A plan's price cell for a paid plan once a place or a code is chosen: the one place that states
81 * it.
82 */
83 function quotedPrice(p: Plan, q: Quote): Html {
84 if (q.atCost) return html`<span class="muted small" data-list-price>was ${monthlyPrice(q.listUsd)}</span> <span data-price data-at-cost>at cost ${monthlyPrice(q.priceUsd)}</span>`;
85 return html`<span data-price>${monthlyPrice(q.priceUsd)}</span> <span class="muted small" data-surcharge>${surchargeParts(p.priceUsd, q.surchargeUsd)}</span>`;
86 }
87
88 /** A plan's price cell with nothing chosen: its price, and for a plan sold by a link, the link. */
89 function unquotedPrice(p: Plan, words: ReturnType<typeof planWords>, own: boolean, buy: string | undefined): Html {
90 if (own) return html`<span data-price>${words.price}</span>`;
91 return buy !== undefined
92 ? html`<span data-price>${words.price}</span> <a href="${buy}" data-buy rel="noopener noreferrer" target="_blank">Get ${p.name}</a>`
93 : html`<span data-price>${words.price}</span> <span class="muted">ask the operator · for organizations, <a href="https://www.espodev.com">EspoDev</a></span>`;
94 }
95
96 function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["field"], string>>, door = getDoorSettings(ctx.app.db), typed: Typed = ok(undefined)): Html {
6297 // The order this browser paid for, from its own cookie: the page that opens it needs the address
6398 // of the order.
6499 const held = (cookieValue(ctx.request, COOKIE) ?? "").split(".")[0] ?? "";
@@ -71,7 +106,13 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
71106 // The paid placement is read once: it says whether paid forges run on a cloud, and feeds the list.
72107 const placement = getPaidPlacement(ctx.app.db);
73108 const cloud = placement.where === "cloud";
74 const choice = selling ? placeChoice(ctx.app, plans.find((p) => p.key !== FREE), false, placement) : undefined;
109 // A buyer may choose a dearer place: the difference is added to the price, shown on the plan
110 // below.
111 const choice = selling ? placeChoice(ctx.app, plans.find((p) => p.key !== FREE), true, placement) : undefined;
112 // An at-cost code typed here, looked up by the caller (it counts a try for the client).
113 const codeError = !typed.ok ? `${typed.error}.` : errors["code"];
114 const atCode = typed.ok ? typed.value : undefined;
115 const codeOf = (p: Plan): boolean => atCode !== undefined && atCode.plan === p.key;
75116 const links = selling ? {} : door.links;
76117 const buyable = selling || plans.some((p) => planWords(p, links, 0, door.askUsd).buy !== undefined);
77118 const rows = plans.map((p: Plan) => {
@@ -79,13 +120,11 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
79120 const paid = !free && selling;
80121 const words = planWords(p, links, 0, door.askUsd);
81122 const buy = words.buy;
82 const price = free
83 ? html`<span data-price>${words.price}</span>`
84 : paid
85 ? html`<span data-price>${words.price}</span>`
86 : buy !== undefined
87 ? html`<span data-price>${words.price}</span> <a href="${buy}" data-buy rel="noopener noreferrer" target="_blank">Get ${p.name}</a>`
88 : html`<span data-price>${words.price}</span> <span class="muted">ask the operator · for organizations, <a href="https://www.espodev.com">EspoDev</a></span>`;
123 // What this plan costs at the place chosen: its price, with a dearer place's difference added,
124 // or the normal price struck through beside "at cost" and the amount.
125 const quote = paid && cloud && (values.place !== "" || codeOf(p)) ? quoteFor(ctx.app, p, values.place, codeOf(p)) : undefined;
126 const quoted = quote?.ok === true ? quote.value : undefined;
127 const price = quoted !== undefined && (quoted.atCost || quoted.surchargeUsd > 0) ? quotedPrice(p, quoted) : unquotedPrice(p, words, free || paid, buy);
89128 const act = free ? btn(START_BUTTON, { formaction: "/forges/start" }) : paid ? btn(`Get ${p.name}`, { name: "plan", value: p.key, variant: "primary" }) : null;
90129 const count = ` Up to ${p.forges} ${p.forges === 1 ? "forge" : "forges"}.`;
91130 return planOfferRow({ key: p.key, name: p.name, says: `${planWords(p, links, door.startUsd, door.askUsd).is}${count}`, price, action: act });
@@ -114,6 +153,17 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
114153 })
115154 : null}
116155 ${selling ? placeChoiceView(choice, values.place, errors["place"]) : null}
156 ${selling && cloud
157 ? html`${formField({
158 label: "Code (optional)",
159 name: "code",
160 value: values.code ?? "",
161 autocomplete: "off",
162 hint: "From the operator, for a price at cost.",
163 ...(codeError ? { error: codeError } : {}),
164 })}
165 <p>${btn("Show the price", { name: "preview", value: "1", size: "sm" })}</p>`
166 : null}
117167 <dl class="status-rows">${rows}</dl>
118168 </form>
119169 <div class="muted small" data-after-pay>
@@ -132,13 +182,16 @@ export function pricingPage(ctx: Ctx): Response {
132182 const rendering = performance.now();
133183 const door = getDoorSettings(ctx.app.db);
134184 const { plans, startUsd } = door;
185 // The link an at-cost code is sent as (`/pricing?code=`) fills the field in; a visitor trying
186 // codes this way spends tries, as anywhere a code is tried.
187 const asked = (ctx.url.searchParams.get("code") ?? "").slice(0, 64);
135188 const response = page({
136189 ctx,
137190 title: "Pricing and your own forge",
138191 description: "What each forge plan costs and the CPU, memory, disk and crew credit it includes.",
139192 tight: true,
140193 jsonLd: safeJson({ "@context": "https://schema.org", "@type": "Product", name: "Open Platform Forge", url: `${ctx.url.origin}/`, additionalProperty: sharedProperties(lapseRule(ctx.app.db)), offers: offerData(plans, ctx.url.origin, lapseRule(ctx.app.db), true, startUsd) }),
141 body: plansView(ctx, { name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), email: "", place: "" }, {}, door),
194 body: plansView(ctx, { name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), email: "", place: "", code: asked }, {}, door, typedCode(ctx, asked)),
142195 });
143196 notePhase(ctx.request, "render", performance.now() - rendering);
144197 return response;
@@ -156,12 +209,21 @@ export async function pricingOrder(ctx: Ctx): Promise<Response> {
156209 if (!isBuyer(ctx)) return notFoundPage(ctx);
157210 const form = await readForm(ctx, ctx.auth.user === undefined ? undefined : "admin");
158211 if (form instanceof Response) return form;
159 const values: Values = { name: field(form, "name").trim().slice(0, 60), email: field(form, "email").trim().slice(0, 254), place: field(form, "place").trim().slice(0, 200) };
212 const values: Values = { name: field(form, "name").trim().slice(0, 60), email: field(form, "email").trim().slice(0, 254), place: field(form, "place").trim().slice(0, 200), code: field(form, "code").trim().slice(0, 64) };
160213 const plan = field(form, "plan");
214 // "Show the price": the same page again with the place and code chosen, nothing held, nothing
215 // paid.
216 if (field(form, "preview") !== "") {
217 const verdict = takeDoor(ctx.app, "plan", ctx.request);
218 if (!verdict.allowed) return page({ ctx, title: "Get your own forge", body: plansView(ctx, values, { form: `Too many tries from here; try again in ${verdict.retryAfter}s` }) }, 429);
219 const res = page({ ctx, title: "Get your own forge", body: plansView(ctx, values, {}, getDoorSettings(ctx.app.db), typedCode(ctx, values.code ?? "")) });
220 res.headers.set("cache-control", "no-store");
221 return res;
222 }
161223 if (plan === FREE) return redirect(`/forges/new?name=${encodeURIComponent(values.name.slice(0, 38))}`);
162224 const verdict = takeDoor(ctx.app, "plan", ctx.request);
163225 if (!verdict.allowed) return page({ ctx, title: "Get your own forge", body: plansView(ctx, values, { form: `Too many tries from here; try again in ${verdict.retryAfter}s` }) }, 429);
164 const placed = await placeOrder(ctx.app, { name: values.name, plan, email: values.email, address: clientBucket(ctx.request), place: values.place }, ctx.url);
226 const placed = await placeOrder(ctx.app, { name: values.name, plan, email: values.email, address: clientBucket(ctx.request), place: values.place, code: values.code }, ctx.url);
165227 if (!placed.ok) {
166228 const status = placed.error.message === NO_PROVIDER ? 409 : 422;
167229 return page({ ctx, title: "Get your own forge", body: plansView(ctx, values, { [placed.error.field]: `${placed.error.message}.` }) }, status);
test/at-cost.test.ts added +84
@@ -0,0 +1,84 @@
1 /**
2 * At-cost codes and the price of a place (#16205): the arithmetic that prices a forge on its own
3 * machine, and the one rule that keeps the two kinds of code apart: a code that sells a forge at
4 * cost never gives a plan free.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { giftOf, makeCode, planCode } from "../src/actions/codes.ts";
12 import { atCostUsd, feeCents, marginOf, surchargeUsd } from "../src/billing/at_cost.ts";
13 import { claimCode, lookupCode } from "../src/billing/codes.ts";
14 import { createUser, getUserByName } from "../src/core/users.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 describe("the prices", () => {
20 test("at cost is the cost and the payment fee, grossed up, to the next whole dollar", () => {
21 // $13.00 of machine: (1300 + 30) / 0.971 = 1369.7 cents -> $14.
22 expect(atCostUsd(1300)).toBe(14);
23 // Never below what the machine costs once the fee is taken out of the charge.
24 for (const cents of [1, 99, 500, 1300, 2500, 8481, 12345]) {
25 const pays = atCostUsd(cents);
26 expect(pays * 100 - feeCents(pays)).toBeGreaterThanOrEqual(cents);
27 expect(Number.isInteger(pays)).toBe(true);
28 }
29 });
30
31 test("a dearer place adds the difference rounded up, a cheaper or equal one adds nothing", () => {
32 expect(surchargeUsd(1300, 2500)).toBe(12);
33 expect(surchargeUsd(1300, 1301)).toBe(1);
34 expect(surchargeUsd(1300, 1300)).toBe(0);
35 expect(surchargeUsd(1300, 800)).toBe(0);
36 });
37
38 test("margin is what is paid less the fee and the cost; an at-cost forge reads zero", () => {
39 expect(marginOf(20, 1300, false)).toEqual({ costCents: 1300, paysCents: 2000, feeCents: 88, marginCents: 612 });
40 expect(marginOf(14, 1300, true).marginCents).toBe(0);
41 });
42 });
43
44 describe("a code's kind", () => {
45 let dir = "";
46 let app: App;
47 const admin = () => getUserByName(app.db, "alice")!;
48
49 beforeAll(async () => {
50 dir = await mkdtemp(join(tmpdir(), "forge-at-cost-"));
51 app = createApp({ dataDir: dir, port: 0, forgeRepo: "alice/forge", url: "https://forge.test" });
52 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
53 if (!made.ok) throw new Error(made.error);
54 });
55
56 afterAll(async () => {
57 app.close();
58 await rm(dir, { recursive: true, force: true });
59 });
60
61 test("a kind is plan or at_cost, and only an admin who is a person makes either", () => {
62 expect(planCode(app, admin(), { plan: "small", kind: "free" })).toEqual({ ok: false, error: "bad_kind" });
63 expect(planCode(app, admin(), { plan: "small", kind: "at_cost" })).toMatchObject({ ok: true, value: { kind: "at_cost" } });
64 expect(planCode(app, admin(), { plan: "small" })).toMatchObject({ ok: true, value: { kind: "plan" } });
65 expect(planCode(app, undefined, { plan: "small", kind: "at_cost" })).toEqual({ ok: false, error: "not_found" });
66 });
67
68 test("an at-cost code is never a gift: the gift door and its claim refuse it, and it is spent nowhere", () => {
69 const made = makeCode(app, admin(), { plan: "small", kind: "at_cost", uses: 3 }, "https://forge.test");
70 if (!made.ok) throw new Error(made.error);
71 const request = new Request("https://forge.test/forges/new", { headers: { "x-forwarded-for": "198.51.100.9" } });
72 expect(giftOf(app, request, made.value.code)).toEqual({ ok: false, error: "wrong_kind" });
73 expect(claimCode(app.db, made.value.code)).toEqual({ ok: false, error: "wrong_kind" });
74 expect(lookupCode(app.db, made.value.code).ok).toBe(false);
75 expect(lookupCode(app.db, made.value.code, new Date(), "at_cost")).toMatchObject({ ok: true, value: { kind: "at_cost", used: 0 } });
76 });
77
78 test("a gift code is not an at-cost code either", () => {
79 const made = makeCode(app, admin(), { plan: "small" }, "https://forge.test");
80 if (!made.ok) throw new Error(made.error);
81 expect(lookupCode(app.db, made.value.code, new Date(), "at_cost")).toEqual({ ok: false, error: "wrong_kind" });
82 expect(made.value.link).toBe(`https://forge.test/?code=${encodeURIComponent(made.value.code)}`);
83 });
84 });
test/billing-tui.test.ts +19
@@ -19,6 +19,7 @@ import { usePlacement, useProbe } from "../src/spawn/door.ts";
1919 import { bootHostedChild } from "../src/spawn/host.ts";
2020 import { createForgeApp } from "../src/tui/forge.ts";
2121 import { billingRows, billingScreen, entry } from "../src/tui/screens/billing.ts";
22 import { entry as soldEntry, soldListRows } from "../src/tui/screens/sold.ts";
2223 import { headlessTerminal } from "../src/tui/term/terminal.ts";
2324 import { quietLogs } from "./helpers/globals.ts";
2425 import { settleApp } from "./helpers/tui.ts";
@@ -221,3 +222,21 @@ test("a forge in grace shows the lapse notice on its terminal row", () => {
221222 expect(row?.meta).not.toContain("lapsed");
222223 expect(row?.below?.[0]).toMatch(/Your payment lapsed: \d+ days? of grace remain, ending on \d{4}-\d\d-\d\d UTC/);
223224 });
225
226 test("Sold forges: an admin's terminal lists each sold forge's cost, pay and margin; no one else is offered it", () => {
227 const now = Date.now();
228 app.db
229 .query(
230 `INSERT INTO forge_order (id, name, plan, email, state, ticket_hash, session_id, created_at, hold_until, updated_at, price_usd, cost_cents, placed, code_id)
231 VALUES ('ord_sold1', 'soldone', 'small', '[email protected]', 'spawned', 'h', 'cs_1', ?1, ?1, ?1, 20, 1300, 'digitalocean:nyc3:s-1vcpu-2gb', '')`,
232 )
233 .run(now);
234 const admin = open(alice).session;
235 expect(soldEntry.offered(admin)).toBe(true);
236 expect(soldEntry.offered(open(bob).session)).toBe(false);
237 const [row] = soldListRows(admin);
238 expect(row).toMatchObject({ title: "soldone", secondary: "small · digitalocean:nyc3:s-1vcpu-2gb" });
239 expect(row?.meta).toBe("costs $13.00 · pays $20.00 · fee $0.88 · margin $6.12");
240 expect(soldListRows(open(bob).session)).toEqual([]);
241 app.db.query("DELETE FROM forge_order WHERE id = 'ord_sold1'").run();
242 });
test/data-browser.test.ts +1
@@ -45,6 +45,7 @@ const AUDITED_CLEAR: string[] = [
4545 "engine_observation.body",
4646 "feed_chip.value",
4747 "fleet_operation.value",
48 "forge_order.code_id",
4849 "gift_redeem.code_id",
4950 "issue.body",
5051 "oauth_flow.detail",
test/one-door.test.ts +4 −2
@@ -396,7 +396,7 @@ describe("one door for making a forge", () => {
396396 const dear = await placeOrder(
397397 app,
398398 {
399 name: "bought",
399 name: "boughtdear",
400400 plan: "small",
401401 email: "[email protected]",
402402 address: "198.51.100.9",
@@ -404,7 +404,9 @@ describe("one door for making a forge", () => {
404404 },
405405 new URL("https://forge.test/pricing"),
406406 );
407 expect(dear).toMatchObject({ ok: false, error: { field: "place" } });
407 // A dearer place is no longer refused (#16205): its difference is added to the price.
408 if (!dear.ok) throw new Error(dear.error.message);
409 expect(getOrder(app.db, dear.value.id)!.priceUsd).toBeGreaterThan(getPlan(app.db, "small")!.priceUsd);
408410 const shut = await placeOrder(
409411 app,
410412 {
test/order-cloud.test.ts +123 −2
@@ -34,11 +34,17 @@ import {
3434 import { createRepo } from "../src/actions/repos.ts";
3535 import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts";
3636 import { getOrder } from "../src/billing/orders.ts";
37 import { makeCode } from "../src/actions/codes.ts";
38 import { atCostUsd } from "../src/billing/at_cost.ts";
39 import { getCode, listCodes, takeTry } from "../src/billing/codes.ts";
40 import { soldRows } from "../src/billing/sold.ts";
41 import { readPlaces } from "../src/cloud/places_read.ts";
42 import { getPlan } from "../src/settings/plans.ts";
3743 import { changesOf, getPinned, markClaimed } from "../src/core/pinned.ts";
3844 import { retireLapsedCloud } from "../src/spawn/lapse_cloud.ts";
3945 import { priced, spendOf } from "../src/cloud/ceiling.ts";
4046 import { defaultPlace } from "../src/actions/pinned.ts";
41 import { pricingDone, pricingPage } from "../src/web/pages/pricing.ts";
47 import { pricingDone, pricingOrder, pricingPage } from "../src/web/pages/pricing.ts";
4248 import type { Ctx } from "../src/http/context.ts";
4349 import { createUser, getUserByName } from "../src/core/users.ts";
4450 import { ok } from "../src/kernel/result.ts";
@@ -46,7 +52,7 @@ import { usePlacement } from "../src/spawn/door.ts";
4652 import { bootHostedChild, closeHostedChildren } from "../src/spawn/host.ts";
4753 import { getPaidPlacement } from "../src/settings/paid_placement.ts";
4854 import { quietLogs } from "./helpers/globals.ts";
49 import { seedPlaces } from "./helpers/places-fixture.ts";
55 import { ocean, seedPlaces } from "./helpers/places-fixture.ts";
5056
5157 quietLogs();
5258
@@ -405,6 +411,13 @@ describe("a paid order on a cloud account", () => {
405411 expect(r).toMatchObject({ ok: false, error: { field: "name" } });
406412 });
407413
414 /** A same-origin form post, as the pricing page sends it. */
415 const formCtx = (fields: Record<string, string>): Ctx => {
416 const url = new URL("https://forge.test/pricing/order");
417 const request = new Request(url.href, { method: "POST", headers: { origin: url.origin, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(fields).toString() });
418 return { app, request, url, params: {}, auth: { user: undefined, scope: undefined, via: "none" }, theme: undefined } as Ctx;
419 };
420
408421 const ctxOf = (path: string, cookie = ""): Ctx => {
409422 const url = new URL(`https://forge.test${path}`);
410423 return { app, request: new Request(url.href, { headers: new Headers(cookie === "" ? {} : { cookie }) }), url, params: {}, auth: { user: undefined, scope: undefined, via: "none" }, theme: undefined } as Ctx;
@@ -491,4 +504,112 @@ describe("a paid order on a cloud account", () => {
491504 expect(body).toContain("&lt;name&gt;.forges.test on its own machine");
492505 expect(body).toContain("its machine is deleted and its data kept");
493506 });
507
508 test("price follows the place: a dearer place adds the difference, rounded up, to the plan's price, and the order keeps what it costs", async () => {
509 const json = (o: unknown): Response => new Response(JSON.stringify(o), { status: 200 });
510 const bigger = { slug: "s-2vcpu-4gb", memory: 4096, vcpus: 2, disk: 80, transfer: 4, price_monthly: 24, available: true, regions: ["nyc3"] };
511 await readPlaces(app.db, "digitalocean", async (url) => json(String(url).includes("/sizes") ? { sizes: [...ocean.sizes, bigger] } : { regions: ocean.regions }), "t");
512 const dearer = "digitalocean:nyc3:s-2vcpu-4gb";
513 const cheap = defaultPlace(app, "digitalocean", "small").place!;
514 expect(cheap.costCents).toBeLessThan(2500);
515 const extra = Math.ceil((2500 - cheap.costCents) / 100);
516 const small = getPlan(app.db, "small")!;
517 const placed = await placeOrder(app, { name: "dearone", plan: "small", email: "[email protected]", address: "198.51.100.170", place: dearer }, new URL("https://forge.test/pricing"));
518 if (!placed.ok) throw new Error(placed.error.message);
519 const o = getOrder(app.db, placed.value.id)!;
520 expect(o).toMatchObject({ priceUsd: small.priceUsd + extra, costCents: 2500, placed: dearer, codeId: "" });
521 const plain = await placeOrder(app, { name: "plainone", plan: "small", email: "[email protected]", address: "198.51.100.171" }, new URL("https://forge.test/pricing"));
522 if (!plain.ok) throw new Error(plain.error.message);
523 expect(getOrder(app.db, plain.value.id)).toMatchObject({ priceUsd: small.priceUsd, costCents: cheap.costCents, placed: cheap.id });
524 // "Show the price" says it before anyone pays, on the plan: its price and the place's part.
525 const shownPrice = await (await pricingOrder(formCtx({ preview: "1", place: dearer }))).text();
526 expect(shownPrice).toContain(`$${small.priceUsd + extra} a month`);
527 expect(shownPrice).toContain(`$${small.priceUsd} and $${extra} for the place`);
528 });
529
530 test("an at-cost code sells the place's cost and the payment fee to the next dollar, shows the normal price struck through, and is spent when the sale is paid", async () => {
531 const cheap = defaultPlace(app, "digitalocean", "small").place!;
532 const small = getPlan(app.db, "small")!;
533 const made = makeCode(app, admin(), { kind: "at_cost", plan: "small", uses: 1, note: "for Mark" }, "https://forge.test");
534 if (!made.ok) throw new Error(made.error);
535 expect(made.value.link).toBe(`https://forge.test/pricing?code=${encodeURIComponent(made.value.code)}`);
536 expect(listCodes(app.db)[0]).toMatchObject({ kind: "at_cost", used: 0 });
537 const paying = atCostUsd(cheap.costCents);
538 // A shown page names it and strikes the normal price.
539 const shown = await (await pricingPage(ctxOf(`/pricing?code=${made.value.code}`))).text();
540 expect(shown).toContain(`data-list-price>was $${small.priceUsd} a month`);
541 expect(shown).toContain(`at cost $${paying} a month`);
542 // A code for another plan, and a gift code, are refused where they do not belong.
543 const wrong = await placeOrder(app, { name: "wrongplan", plan: "medium", email: "[email protected]", address: "198.51.100.172", code: made.value.code }, new URL("https://forge.test/pricing"));
544 expect(wrong).toMatchObject({ ok: false, error: { field: "code" } });
545 const gift = makeCode(app, admin(), { plan: "small", uses: 1 }, "https://forge.test");
546 if (!gift.ok) throw new Error(gift.error);
547 const refused = await placeOrder(app, { name: "giftishere", plan: "small", email: "[email protected]", address: "198.51.100.173", code: gift.value.code }, new URL("https://forge.test/pricing"));
548 expect(refused).toMatchObject({ ok: false, error: { field: "code" } });
549 // The at-cost order is charged exactly the at-cost price, and a use is spent when it is paid.
550 const charged: number[] = [];
551 useCheckout(app, { ...fake, create: async (req) => (charged.push(req.priceUsd), fake.create(req)) });
552 const placed = await placeOrder(app, { name: "atcostone", plan: "small", email: "[email protected]", address: "198.51.100.174", code: made.value.code }, new URL("https://forge.test/pricing"));
553 useCheckout(app, fake);
554 if (!placed.ok) throw new Error(placed.error.message);
555 expect(charged).toEqual([paying]);
556 expect(getCode(app.db, made.value.made.id)?.used).toBe(0);
557 const o = getOrder(app.db, placed.value.id)!;
558 expect(o).toMatchObject({ priceUsd: paying, codeId: made.value.made.id, costCents: cheap.costCents });
559 await settleSession(app, { id: o.sessionId, metadata: { order: o.id }, customer: "cus_a", subscription: "sub_a", payment_status: "paid" });
560 expect(getCode(app.db, made.value.made.id)?.used).toBe(1);
561 expect(listCodes(app.db).find((c) => c.id === made.value.made.id)?.redeemed.map((r) => r.forge)).toEqual(["atcostone"]);
562 // Used up: the next buyer is told so, before anything is held.
563 const again = await placeOrder(app, { name: "atcosttwo", plan: "small", email: "[email protected]", address: "198.51.100.175", code: made.value.code }, new URL("https://forge.test/pricing"));
564 expect(again).toMatchObject({ ok: false, error: { field: "code", message: "That code has been used as many times as it allows" } });
565 // The owner's view: the forge, its place, its cost, what it pays, and zero margin, not a loss.
566 const row = soldRows(app.db).find((r) => r.forge === "atcostone")!;
567 expect(row).toMatchObject({ atCost: true, place: cheap.id, paysUsd: paying });
568 expect(row.month?.marginCents).toBe(0);
569 expect(row.month?.costCents).toBe(cheap.costCents);
570 });
571
572 test("a code cannot be guessed through the page: every look, by the link or by Show the price, counts a try", async () => {
573 app.db.query("DELETE FROM gift_try").run();
574 const guess = (n: number) => `forge-aaaa-${String(n).padStart(4, "0")}`;
575 const tries = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM gift_try").get()!.n;
576 // Show the price: each code looked up is a try, empty or no code is none.
577 for (let i = 0; i < 3; i++) await (await pricingOrder(formCtx({ preview: "1", code: guess(i) }))).text();
578 await (await pricingOrder(formCtx({ preview: "1", code: "" }))).text();
579 expect(tries()).toBe(3);
580 // Spent tries: the page no longer says whether a code is known.
581 app.db.query("DELETE FROM gift_try").run();
582 for (let i = 0; i < 10; i++) takeTry(app.db, "unknown");
583 const spent = await (await pricingOrder(formCtx({ preview: "1", code: guess(99) }))).text();
584 expect(spent).toContain("Too many codes tried");
585 expect(spent).not.toContain("not one this forge knows");
586 app.db.query("DELETE FROM gift_try").run();
587 let shown = "";
588 for (let i = 0; i < 12; i++) shown = await (await pricingPage(ctxOf(`/pricing?code=${guess(i)}`))).text();
589 expect(shown).toContain("Too many codes tried");
590 app.db.query("DELETE FROM gift_try").run();
591 });
592
593 test("one use of an at-cost code funds one checkout at a time: an open order holds it, and a lapsed one gives it back", async () => {
594 const made = makeCode(app, admin(), { kind: "at_cost", plan: "small", uses: 1 }, "https://forge.test");
595 if (!made.ok) throw new Error(made.error);
596 const url = new URL("https://forge.test/pricing");
597 const first = await placeOrder(app, { name: "holdone", plan: "small", email: "[email protected]", address: "198.51.100.191", code: made.value.code }, url);
598 expect(first.ok).toBe(true);
599 const second = await placeOrder(app, { name: "holdtwo", plan: "small", email: "[email protected]", address: "198.51.100.192", code: made.value.code }, url);
600 expect(second).toMatchObject({ ok: false, error: { field: "code", message: "That code has been used as many times as it allows" } });
601 // The first buyer walks away: its hold lapses and the use is free again.
602 app.db.query("UPDATE forge_order SET hold_until = ?1 WHERE id = ?2").run(Date.now() - 1, first.ok ? first.value.id : "");
603 const third = await placeOrder(app, { name: "holdthree", plan: "small", email: "[email protected]", address: "198.51.100.193", code: made.value.code }, url);
604 expect(third.ok).toBe(true);
605 });
606
607 test("at cost has no machine to cost when paid forges run hosted", async () => {
608 expect(changePaidPlacement(app, admin(), "hosted").ok).toBe(true);
609 const made = makeCode(app, admin(), { kind: "at_cost", plan: "small" }, "https://forge.test");
610 if (!made.ok) throw new Error(made.error);
611 const r = await placeOrder(app, { name: "hostedcost", plan: "small", email: "[email protected]", address: "198.51.100.176", code: made.value.code }, new URL("https://forge.test/pricing"));
612 expect(r).toMatchObject({ ok: false, error: { field: "code" } });
613 expect(changePaidPlacement(app, admin(), "digitalocean/main").ok).toBe(true);
614 });
494615 });
test/palette-roster.test.ts +1
@@ -219,6 +219,7 @@ test("a site-admin person is offered the whole roster", () => {
219219 ["security-controls", "Security controls", "each safeguard, its state, and when it was last checked"],
220220 ["billing", "Billing", "each forge's plan, and grant one by hand"],
221221 ["lapsed", "Lapsed forges", "forges asleep until paid, when their data goes, pay again"],
222 ["sold", "Sold forges", "what each bought forge costs, pays and leaves"],
222223 ["codes", "Gift codes", "make a code that gives a plan for free, and revoke one"],
223224 ["archived", "Archived repositories", "put away, not gone: open one or restore it"],
224225 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs