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
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/16205-a-paid-checkout-deploys-the-buyer-s-forg → main 0 commits fork
24 files
changed +674
−56
- docs/features/pricing.md
- src/actions/codes.ts
- src/actions/order.ts
- src/billing/at_cost.ts
- src/billing/codes.ts
- src/billing/orders.ts
- src/billing/plan_words.ts
- src/billing/sold.ts
- src/billing/stripe.ts
- src/contract/openapi/routes/postApiV1Codes.ts
- src/core/migration-pins/20261127200000-order-quote.pin
- src/core/migrations/20261127200000-order-quote.ts
- src/spawn/door.ts
- src/spawn/order_quote.ts
- src/tui/screens/codes.ts
- src/tui/screens/sold.ts
- src/web/pages/billing.ts
- src/web/pages/pricing.ts
- test/at-cost.test.ts
- test/billing-tui.test.ts
- test/data-browser.test.ts
- test/one-door.test.ts
- test/order-cloud.test.ts
- test/palette-roster.test.ts
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 | ||
| 26 | 26 | lapse sentence `/terms` also prints, and the Terms and Privacy links. With no |
| 27 | 27 | payment provider the page says paid plans are not on sale yet and shows the steps |
| 28 | 28 | 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 @@ | ||
| 11 | 11 | import type { App } from "../app.ts"; |
| 12 | 12 | import { tellPlan } from "../billing/notice.ts"; |
| 13 | 13 | 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, | |
| 15 | 15 | releaseCode, revokeCode, takeTry, type Code, type CodeRefusal, type Listed, |
| 16 | 16 | } from "../billing/codes.ts"; |
| 17 | 17 | import { putEntitlement } from "../billing/store.ts"; |
| @@ -20,9 +20,10 @@ import { clientBucket } from "../http/peer.ts"; | ||
| 20 | 20 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 21 | 21 | import { FREE, getPlan, getPlans } from "../settings/plans.ts"; |
| 22 | 22 | |
| 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"; | |
| 24 | 24 | |
| 25 | 25 | 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)", | |
| 26 | 27 | bad_plan: "A code gives a plan other than free: name one of the paid plans", |
| 27 | 28 | bad_uses: `Uses is a whole number from 1 to ${MAX_USES}`, |
| 28 | 29 | 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> = { | ||
| 33 | 34 | const admin = (a: User | undefined): Result<User, "not_found"> => (a?.isAdmin === true && a.kind !== "agent" ? ok(a) : err("not_found")); |
| 34 | 35 | |
| 35 | 36 | export interface CodePlan { |
| 37 | readonly kind: CodeKind; | |
| 36 | 38 | readonly plan: string; |
| 37 | 39 | readonly note: string; |
| 38 | 40 | readonly uses: number; |
| @@ -43,6 +45,9 @@ export interface CodePlan { | ||
| 43 | 45 | export function planCode(app: App, actor: User | undefined, input: Record<string, unknown>, now = new Date()): Result<CodePlan, CodeError> { |
| 44 | 46 | const who = admin(actor); |
| 45 | 47 | 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"; | |
| 46 | 51 | const plan = typeof input["plan"] === "string" ? getPlan(app.db, input["plan"]) : undefined; |
| 47 | 52 | if (plan === undefined || plan.key === FREE) return err("bad_plan"); |
| 48 | 53 | const rawUses = input["uses"]; |
| @@ -54,7 +59,7 @@ export function planCode(app: App, actor: User | undefined, input: Record<string | ||
| 54 | 59 | if (note === undefined || note.length > MAX_NOTE || /[\u0000-\u001f\u007f]/.test(note)) return err("bad_note"); |
| 55 | 60 | const expiry = expiryOf(input["expires"], now); |
| 56 | 61 | 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 }) }); | |
| 58 | 63 | } |
| 59 | 64 | |
| 60 | 65 | /** 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 | ||
| 74 | 79 | } |
| 75 | 80 | |
| 76 | 81 | /** 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)}`; | |
| 78 | 84 | |
| 79 | 85 | /** An admin makes a code. The plain code is in this answer and nowhere else. */ |
| 80 | 86 | 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 | ||
| 82 | 88 | if (!planned.ok) return planned; |
| 83 | 89 | const who = actor as User; |
| 84 | 90 | 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 }); | |
| 87 | 93 | } |
| 88 | 94 | |
| 89 | 95 | /** An admin revokes a code: no new uses; forges already made keep their plan. */ |
src/actions/order.ts +22 −4
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | import type { App } from "../app.ts"; |
| 25 | 25 | import { checkoutOf } from "../billing/checkout.ts"; |
| 26 | 26 | 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"; | |
| 27 | 28 | import { putEntitlement } from "../billing/store.ts"; |
| 28 | 29 | import { heldOf } from "../perf/held.ts"; |
| 29 | 30 | import type { User } from "../core/users.ts"; |
| @@ -31,6 +32,7 @@ import { publicOrigin } from "../core/public_origin.ts"; | ||
| 31 | 32 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 32 | 33 | import { isChildName } from "../core/proposal_token.ts"; |
| 33 | 34 | import type { Ctx } from "../http/context.ts"; |
| 35 | import { atCostCode, quoteFor } from "../spawn/order_quote.ts"; | |
| 34 | 36 | import { nameTaken, spawnDoor } from "../spawn/door.ts"; |
| 35 | 37 | import { FREE, getPlan, type Plan } from "../settings/plans.ts"; |
| 36 | 38 | import { reissueClaimFor } from "./spawn.ts"; |
| @@ -40,7 +42,7 @@ import { askMaking, failOrder, mailLink, openLink } from "../spawn/making.ts"; | ||
| 40 | 42 | export { makingWatch } from "../spawn/making.ts"; |
| 41 | 43 | |
| 42 | 44 | export interface Refusal { |
| 43 | readonly field: "name" | "email" | "plan" | "place" | "form"; | |
| 45 | readonly field: "name" | "email" | "plan" | "place" | "code" | "form"; | |
| 44 | 46 | readonly message: string; |
| 45 | 47 | } |
| 46 | 48 | |
| @@ -96,7 +98,7 @@ export interface Placed { | ||
| 96 | 98 | } |
| 97 | 99 | |
| 98 | 100 | /** 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>> { | |
| 100 | 102 | const plan = typeof input.plan === "string" ? getPlan(app.db, input.plan) : undefined; |
| 101 | 103 | if (plan === undefined || plan.key === FREE || plan.priceUsd <= 0) return err({ field: "plan", message: "Pick one of the paid plans" }); |
| 102 | 104 | const email = emailOf(input.email); |
| @@ -109,12 +111,22 @@ export async function placeOrder(app: App, input: { name: unknown; plan: unknown | ||
| 109 | 111 | 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" }); |
| 110 | 112 | const refused = await nameRefusal(app, name, plan, now, place); |
| 111 | 113 | 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; | |
| 112 | 124 | const id = newId(); |
| 113 | 125 | 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" }); | |
| 115 | 127 | const origin = publicOrigin(app.config.url, url.origin); |
| 116 | 128 | 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, | |
| 118 | 130 | successUrl: `${origin}/pricing/done?order=${id}`, cancelUrl: `${origin}/pricing`, |
| 119 | 131 | // The checkout stops being payable before the name's hold lapses. |
| 120 | 132 | expiresAt: Math.floor((now + CHECKOUT_MS) / 1000), |
| @@ -144,6 +156,12 @@ export async function settleOrder(app: App, id: string, paid: { customer?: strin | ||
| 144 | 156 | return o.state === "paid" ? makeForge(app, id, "paid") : o; |
| 145 | 157 | } |
| 146 | 158 | 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 | } | |
| 147 | 165 | return makeForge(app, id, "paid"); |
| 148 | 166 | } |
| 149 | 167 |
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}$/; | ||
| 15 | 15 | export const MAX_USES = 1000; |
| 16 | 16 | export const MAX_NOTE = 80; |
| 17 | 17 | |
| 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"; | |
| 19 | 24 | |
| 20 | 25 | export const CODE_WORDS: Record<CodeRefusal, string> = { |
| 21 | 26 | unknown: "That code is not one this forge knows", |
| 22 | 27 | used_up: "That code has been used as many times as it allows", |
| 23 | 28 | expired: "That code has expired", |
| 24 | 29 | 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", | |
| 25 | 31 | }; |
| 26 | 32 | |
| 27 | 33 | export interface Code { |
| 28 | 34 | readonly id: string; |
| 29 | 35 | readonly plan: string; |
| 36 | readonly kind: CodeKind; | |
| 30 | 37 | readonly note: string; |
| 31 | 38 | readonly uses: number; |
| 32 | 39 | readonly used: number; |
| @@ -42,12 +49,12 @@ export interface Redeemed { | ||
| 42 | 49 | } |
| 43 | 50 | |
| 44 | 51 | 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; | |
| 46 | 53 | revoked_at: string | null; made_by: string; made_at: string; |
| 47 | 54 | } |
| 48 | 55 | |
| 49 | 56 | 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, | |
| 51 | 58 | ...(r.expires_at === null ? {} : { expiresAt: r.expires_at }), |
| 52 | 59 | ...(r.revoked_at === null ? {} : { revokedAt: r.revoked_at }), |
| 53 | 60 | madeBy: r.made_by, madeAt: r.made_at, |
| @@ -69,6 +76,7 @@ function randomGroup(): string { | ||
| 69 | 76 | |
| 70 | 77 | export interface NewCode { |
| 71 | 78 | plan: string; |
| 79 | kind?: CodeKind; | |
| 72 | 80 | note: string; |
| 73 | 81 | uses: number; |
| 74 | 82 | expiresAt?: string; |
| @@ -81,8 +89,8 @@ export function insertCode(db: Database, n: NewCode, now = new Date()): { code: | ||
| 81 | 89 | const id = crypto.randomUUID().slice(0, 8); |
| 82 | 90 | const at = now.toISOString(); |
| 83 | 91 | 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"); | |
| 86 | 94 | return { code, row: getCode(db, id)! }; |
| 87 | 95 | } |
| 88 | 96 | |
| @@ -97,16 +105,27 @@ const refusalOf = (c: Code, now: Date): CodeRefusal | undefined => | ||
| 97 | 105 | : c.used >= c.uses ? "used_up" |
| 98 | 106 | : undefined; |
| 99 | 107 | |
| 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> { | |
| 102 | 113 | const code = normalizeCode(input); |
| 103 | 114 | const r = code === undefined ? undefined : db.query<Row, [string]>("SELECT * FROM gift_code WHERE hash = ?1").get(hashCode(code)); |
| 104 | 115 | if (!r) return err("unknown"); |
| 105 | 116 | 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); | |
| 107 | 122 | return why === undefined ? ok(c) : err(why); |
| 108 | 123 | } |
| 109 | 124 | |
| 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 | ||
| 110 | 129 | /** Spend one use, in one statement: the last use goes to one caller only. */ |
| 111 | 130 | export function claimCode(db: Database, input: unknown, now = new Date()): Result<Code, CodeRefusal> { |
| 112 | 131 | const seen = lookupCode(db, input, now); |
| @@ -114,13 +133,22 @@ export function claimCode(db: Database, input: unknown, now = new Date()): Resul | ||
| 114 | 133 | const done = db |
| 115 | 134 | .query( |
| 116 | 135 | `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)`, | |
| 118 | 137 | ) |
| 119 | 138 | .run(seen.value.id, now.toISOString()); |
| 120 | 139 | if (done.changes === 0) return lookupCode(db, input, now); |
| 121 | 140 | return ok({ ...seen.value, used: seen.value.used + 1 }); |
| 122 | 141 | } |
| 123 | 142 | |
| 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 | ||
| 124 | 152 | /** Give a use back: the forge it was for was not made. */ |
| 125 | 153 | export function releaseCode(db: Database, id: string): void { |
| 126 | 154 | 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 { | ||
| 51 | 51 | readonly resentAt: number | null; |
| 52 | 52 | /** The place chosen for a forge on a cloud account; empty for the plan's default. */ |
| 53 | 53 | 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; | |
| 54 | 63 | } |
| 55 | 64 | |
| 56 | 65 | interface Row { |
| 57 | 66 | id: string; name: string; plan: string; price_usd: number; paid_at: number; email: string; state: OrderState; ticket_hash: string; session_id: string; |
| 58 | 67 | 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; | |
| 60 | 69 | } |
| 61 | 70 | |
| 62 | 71 | const fromRow = (r: Row): Order => ({ |
| 63 | 72 | 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, |
| 64 | 73 | 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, | |
| 66 | 75 | }); |
| 67 | 76 | |
| 68 | 77 | export const newId = (): string => `ord_${crypto.randomUUID().replace(/-/g, "")}`; |
| @@ -104,13 +113,13 @@ export const pendingCount = (db: Database, now: number): number => | ||
| 104 | 113 | db.query<{ n: number }, [number]>("SELECT COUNT(*) AS n FROM forge_order WHERE state = 'pending' AND hold_until > ?1").get(now)?.n ?? 0; |
| 105 | 114 | |
| 106 | 115 | /** 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 { | |
| 108 | 117 | return db.transaction(() => { |
| 109 | 118 | if (nameHeld(db, o.name, now)) return false; |
| 110 | 119 | 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 ?? ""); | |
| 114 | 123 | return true; |
| 115 | 124 | })(); |
| 116 | 125 | } |
| @@ -196,6 +205,14 @@ export function soldOrders(db: Database): Order[] { | ||
| 196 | 205 | return db.query<Row, []>("SELECT * FROM forge_order WHERE state = 'spawned' AND session_id != ''").all().map(fromRow); |
| 197 | 206 | } |
| 198 | 207 | |
| 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 | ||
| 199 | 216 | /** Say on a made order what became of its forge (a lapse); its state does not change. */ |
| 200 | 217 | export function noteOrder(db: Database, id: string, reason: string): void { |
| 201 | 218 | 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 | ||
| 61 | 61 | */ |
| 62 | 62 | export const monthlyPrice = (usd: number): string => (usd === 0 ? "Free" : `$${usd} a month`); |
| 63 | 63 | |
| 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 | ||
| 64 | 69 | export function planWords(p: Plan, links: BillingLinks = {}, startUsd = 0, askUsd: number = ASK_USD): PlanWords { |
| 65 | 70 | const free = p.priceUsd === 0; |
| 66 | 71 | 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 { | ||
| 70 | 70 | readonly plan: string; |
| 71 | 71 | readonly planName: string; |
| 72 | 72 | readonly priceUsd: number; |
| 73 | /** Said beside the plan on the checkout page: a dearer place's surcharge, or "at cost". */ | |
| 74 | readonly note?: string; | |
| 73 | 75 | readonly email: string; |
| 74 | 76 | readonly successUrl: string; |
| 75 | 77 | readonly cancelUrl: string; |
| @@ -156,7 +158,7 @@ export function stripeClient(key: string, fetchFn: typeof fetch = fetch): Stripe | ||
| 156 | 158 | currency: "usd", |
| 157 | 159 | unit_amount: Math.round(req.priceUsd * 100), |
| 158 | 160 | recurring: { interval: "month" }, |
| 159 | product_data: { name: `${req.planName} forge` }, | |
| 161 | product_data: { name: `${req.planName} forge${req.note === undefined ? "" : ` (${req.note})`}` }, | |
| 160 | 162 | }, |
| 161 | 163 | }], |
| 162 | 164 | 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"; | ||
| 3 | 3 | export const route: Route = { |
| 4 | 4 | method: "post", |
| 5 | 5 | 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", | |
| 8 | 8 | auth: true, |
| 9 | 9 | 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)" }, | |
| 12 | 12 | refuses: [404, 422], |
| 13 | 13 | }; |
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( | ||
| 445 | 445 | if (typeof placeIn !== "string" || placeIn.length > MAX_ID) return invalid("place", "must be a place id, provider:datacenter:size (GET /api/v1/places)"); |
| 446 | 446 | const asked = placeIn.trim(); |
| 447 | 447 | 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 }; | |
| 449 | 449 | if (where.where === "cloud") { |
| 450 | 450 | const room = (at: string) => cloudPlacement(ctx.app, where, { orderId: "", ...cloud, place: at }).room?.(); |
| 451 | 451 | 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 | ||
| 25 | 25 | const rows = read.value.codes.map((c) => { |
| 26 | 26 | const state = c.revokedAt !== undefined ? "revoked" : c.used >= c.uses ? "used up" : ""; |
| 27 | 27 | 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 }; | |
| 29 | 29 | }); |
| 30 | 30 | return { rows, ids: read.value.codes.map((c) => c.id), plans: read.value.plans }; |
| 31 | 31 | } |
| @@ -33,10 +33,11 @@ export function codeRows(f: Session): { rows: ListRow[]; ids: string[]; plans: s | ||
| 33 | 33 | export function codesScreen(f: Session, ctx: Ctx): Screen { |
| 34 | 34 | const state = new ListState(); |
| 35 | 35 | let plan = 0; |
| 36 | let kind: "plan" | "at_cost" = "plan"; | |
| 36 | 37 | let note = ""; |
| 37 | 38 | const screen: Screen = { |
| 38 | 39 | 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")], | |
| 40 | 41 | async load(signal) { |
| 41 | 42 | live(f, signal, { where: (e) => e.kind.startsWith("billing.code.") }, () => ctx.invalidate()); |
| 42 | 43 | }, |
| @@ -46,7 +47,7 @@ export function codesScreen(f: Session, ctx: Ctx): Screen { | ||
| 46 | 47 | state.clamp(rows.length); |
| 47 | 48 | const [head, body] = split(area, "v", [len(2), fill(1)]); |
| 48 | 49 | 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); | |
| 50 | 51 | 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); |
| 51 | 52 | else drawList(s, body!, c, state, rows); |
| 52 | 53 | }, |
| @@ -57,9 +58,14 @@ export function codesScreen(f: Session, ctx: Ctx): Screen { | ||
| 57 | 58 | ctx.invalidate(); |
| 58 | 59 | return true; |
| 59 | 60 | } |
| 61 | if (e.key === "c") { | |
| 62 | kind = kind === "plan" ? "at_cost" : "plan"; | |
| 63 | ctx.invalidate(); | |
| 64 | return true; | |
| 65 | } | |
| 60 | 66 | if (e.key === "n") { |
| 61 | 67 | 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}`)); | |
| 63 | 69 | note = made.ok ? `Shown once: ${made.value.code} ${made.value.link}` : made.error === "not_found" ? "Not found." : `${CODE_ERRORS[made.error]}.`; |
| 64 | 70 | ctx.invalidate(); |
| 65 | 71 | 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"; | ||
| 16 | 16 | import { lapseRule } from "../../billing/lapse_rule.ts"; |
| 17 | 17 | import { lapseNotice } from "../../billing/lapse_words.ts"; |
| 18 | 18 | import { failedOrders } from "../../billing/orders.ts"; |
| 19 | import { money, soldRows } from "../../billing/sold.ts"; | |
| 19 | 20 | import { CODE_ERRORS, makeCode, readCodes, revoke, type CodeError } from "../../actions/codes.ts"; |
| 20 | 21 | import { publicOrigin } from "../../core/public_origin.ts"; |
| 21 | 22 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| @@ -58,7 +59,7 @@ function codesSection(ctx: Ctx, shown: Shown | undefined, r: Refused | undefined | ||
| 58 | 59 | return html`<li class="row" data-code="${c.id}"> |
| 59 | 60 | <dl class="row-fields"> |
| 60 | 61 | <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> | |
| 62 | 63 | <dt class="sr-only">Used</dt> |
| 63 | 64 | <dd class="small">${c.used} of ${c.uses} used${state === "" ? "" : ` · ${state}`} · <span class="muted">${redeemed}</span></dd> |
| 64 | 65 | </dl> |
| @@ -80,6 +81,7 @@ function codesSection(ctx: Ctx, shown: Shown | undefined, r: Refused | undefined | ||
| 80 | 81 | ${copyField("gift-link", shown.link, "The link to send", "Copy the link")} |
| 81 | 82 | </div>`} |
| 82 | 83 | <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" }] })))} | |
| 83 | 85 | ${selectField(planChoice(kept(r, { label: "Plan it gives", name: "plan", type: "select", options: plans.map((p, i) => ({ value: p, label: p, selected: i === 0 })) })))} |
| 84 | 86 | ${formField(kept(r, { label: "Uses", name: "uses", type: "number", value: "1" }))} |
| 85 | 87 | ${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 | ||
| 97 | 99 | const planChoice = (o: FieldOptions) => ({ ...o, options: [...(o.options ?? [])] }); |
| 98 | 100 | |
| 99 | 101 | /** 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" }; | |
| 101 | 103 | |
| 102 | 104 | const codeWords = (e: CodeError): string => (e === "not_found" ? "Not found" : CODE_ERRORS[e]); |
| 103 | 105 | |
| 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 | ||
| 104 | 127 | /** The Payment links section: one https field per size a paid plan sits on, saved in one submit. */ |
| 105 | 128 | function linksSection(ctx: Ctx, r: Refused | undefined): Html | null { |
| 106 | 129 | const links = readBillingLinks(ctx.app, ctx.auth.user); |
| @@ -263,7 +286,7 @@ function billingView(ctx: Ctx, shown?: Shown, status = 200, refusal?: Refused): | ||
| 263 | 286 | </form> |
| 264 | 287 | </li>`)}</ul> |
| 265 | 288 | </section>`; |
| 266 | const body = html`${stripe}${orders}<section class="settings-block"> | |
| 289 | const body = html`${stripe}${orders}${soldSection(ctx)}<section class="settings-block"> | |
| 267 | 290 | <h2>Plans</h2> |
| 268 | 291 | <p class="muted small">Choose the plan each forge is on.</p> |
| 269 | 292 | ${rows.length === 0 |
| @@ -292,7 +315,7 @@ export async function billingMakeCode(ctx: Ctx): Promise<Response> { | ||
| 292 | 315 | if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return notFoundPage(ctx); |
| 293 | 316 | const form = await readForm(ctx, "admin"); |
| 294 | 317 | 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") }; | |
| 296 | 319 | const made = makeCode(ctx.app, ctx.auth.user, values, publicOrigin(ctx.app.config.url, ctx.url.origin)); |
| 297 | 320 | if (!made.ok) return made.error === "not_found" ? notFoundPage(ctx) : billingView(ctx, undefined, 422, refused(form, { [CODE_FIELD[made.error]]: `${codeWords(made.error)}.` })); |
| 298 | 321 | return billingView(ctx, { code: made.value.code, link: made.value.link }); |
src/web/pages/pricing.ts +75 −13
| @@ -10,13 +10,16 @@ | ||
| 10 | 10 | import { setCookie } from "../../auth/cookies.ts"; |
| 11 | 11 | import { deliverLink, mayView, NO_PROVIDER, placeOrder, reconcileOrder, resendLink, type Refusal } from "../../actions/order.ts"; |
| 12 | 12 | 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"; | |
| 13 | 16 | import { getPaidPlacement } from "../../settings/paid_placement.ts"; |
| 14 | 17 | import { mailerOf } from "../../actions/verify.ts"; |
| 15 | 18 | import { getBaseDomain } from "../../settings/pinned_domain.ts"; |
| 16 | 19 | import { limitValue } from "../../settings/limits.ts"; |
| 17 | 20 | import { getPinned, urlOf } from "../../core/pinned.ts"; |
| 18 | 21 | 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"; | |
| 20 | 23 | import { checkoutOf } from "../../billing/checkout.ts"; |
| 21 | 24 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 22 | 25 | import { cookieValue, type Ctx } from "../../http/context.ts"; |
| @@ -50,6 +53,8 @@ interface Values { | ||
| 50 | 53 | readonly email: string; |
| 51 | 54 | /** A Places id for a forge on a cloud account; empty for the plan's default. */ |
| 52 | 55 | readonly place: string; |
| 56 | /** An at-cost code, as typed; empty for none. */ | |
| 57 | readonly code?: string; | |
| 53 | 58 | } |
| 54 | 59 | |
| 55 | 60 | /** 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 | ||
| 58 | 63 | |
| 59 | 64 | const isBuyer = (ctx: Ctx): boolean => ctx.auth.user === undefined || ctx.auth.user.kind === "user"; |
| 60 | 65 | |
| 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 { | |
| 62 | 97 | // The order this browser paid for, from its own cookie: the page that opens it needs the address |
| 63 | 98 | // of the order. |
| 64 | 99 | const held = (cookieValue(ctx.request, COOKIE) ?? "").split(".")[0] ?? ""; |
| @@ -71,7 +106,13 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie | ||
| 71 | 106 | // The paid placement is read once: it says whether paid forges run on a cloud, and feeds the list. |
| 72 | 107 | const placement = getPaidPlacement(ctx.app.db); |
| 73 | 108 | 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; | |
| 75 | 116 | const links = selling ? {} : door.links; |
| 76 | 117 | const buyable = selling || plans.some((p) => planWords(p, links, 0, door.askUsd).buy !== undefined); |
| 77 | 118 | const rows = plans.map((p: Plan) => { |
| @@ -79,13 +120,11 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie | ||
| 79 | 120 | const paid = !free && selling; |
| 80 | 121 | const words = planWords(p, links, 0, door.askUsd); |
| 81 | 122 | 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); | |
| 89 | 128 | const act = free ? btn(START_BUTTON, { formaction: "/forges/start" }) : paid ? btn(`Get ${p.name}`, { name: "plan", value: p.key, variant: "primary" }) : null; |
| 90 | 129 | const count = ` Up to ${p.forges} ${p.forges === 1 ? "forge" : "forges"}.`; |
| 91 | 130 | 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 | ||
| 114 | 153 | }) |
| 115 | 154 | : null} |
| 116 | 155 | ${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} | |
| 117 | 167 | <dl class="status-rows">${rows}</dl> |
| 118 | 168 | </form> |
| 119 | 169 | <div class="muted small" data-after-pay> |
| @@ -132,13 +182,16 @@ export function pricingPage(ctx: Ctx): Response { | ||
| 132 | 182 | const rendering = performance.now(); |
| 133 | 183 | const door = getDoorSettings(ctx.app.db); |
| 134 | 184 | 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); | |
| 135 | 188 | const response = page({ |
| 136 | 189 | ctx, |
| 137 | 190 | title: "Pricing and your own forge", |
| 138 | 191 | description: "What each forge plan costs and the CPU, memory, disk and crew credit it includes.", |
| 139 | 192 | tight: true, |
| 140 | 193 | 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)), | |
| 142 | 195 | }); |
| 143 | 196 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 144 | 197 | return response; |
| @@ -156,12 +209,21 @@ export async function pricingOrder(ctx: Ctx): Promise<Response> { | ||
| 156 | 209 | if (!isBuyer(ctx)) return notFoundPage(ctx); |
| 157 | 210 | const form = await readForm(ctx, ctx.auth.user === undefined ? undefined : "admin"); |
| 158 | 211 | 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) }; | |
| 160 | 213 | 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 | } | |
| 161 | 223 | if (plan === FREE) return redirect(`/forges/new?name=${encodeURIComponent(values.name.slice(0, 38))}`); |
| 162 | 224 | const verdict = takeDoor(ctx.app, "plan", ctx.request); |
| 163 | 225 | 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); | |
| 165 | 227 | if (!placed.ok) { |
| 166 | 228 | const status = placed.error.message === NO_PROVIDER ? 409 : 422; |
| 167 | 229 | 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"; | ||
| 19 | 19 | import { bootHostedChild } from "../src/spawn/host.ts"; |
| 20 | 20 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 21 | 21 | import { billingRows, billingScreen, entry } from "../src/tui/screens/billing.ts"; |
| 22 | import { entry as soldEntry, soldListRows } from "../src/tui/screens/sold.ts"; | |
| 22 | 23 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 23 | 24 | import { quietLogs } from "./helpers/globals.ts"; |
| 24 | 25 | import { settleApp } from "./helpers/tui.ts"; |
| @@ -221,3 +222,21 @@ test("a forge in grace shows the lapse notice on its terminal row", () => { | ||
| 221 | 222 | expect(row?.meta).not.toContain("lapsed"); |
| 222 | 223 | expect(row?.below?.[0]).toMatch(/Your payment lapsed: \d+ days? of grace remain, ending on \d{4}-\d\d-\d\d UTC/); |
| 223 | 224 | }); |
| 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
test/one-door.test.ts +4 −2
| @@ -396,7 +396,7 @@ describe("one door for making a forge", () => { | ||
| 396 | 396 | const dear = await placeOrder( |
| 397 | 397 | app, |
| 398 | 398 | { |
| 399 | name: "bought", | |
| 399 | name: "boughtdear", | |
| 400 | 400 | plan: "small", |
| 401 | 401 | email: "[email protected]", |
| 402 | 402 | address: "198.51.100.9", |
| @@ -404,7 +404,9 @@ describe("one door for making a forge", () => { | ||
| 404 | 404 | }, |
| 405 | 405 | new URL("https://forge.test/pricing"), |
| 406 | 406 | ); |
| 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); | |
| 408 | 410 | const shut = await placeOrder( |
| 409 | 411 | app, |
| 410 | 412 | { |
test/order-cloud.test.ts +123 −2
| @@ -34,11 +34,17 @@ import { | ||
| 34 | 34 | import { createRepo } from "../src/actions/repos.ts"; |
| 35 | 35 | import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts"; |
| 36 | 36 | 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"; | |
| 37 | 43 | import { changesOf, getPinned, markClaimed } from "../src/core/pinned.ts"; |
| 38 | 44 | import { retireLapsedCloud } from "../src/spawn/lapse_cloud.ts"; |
| 39 | 45 | import { priced, spendOf } from "../src/cloud/ceiling.ts"; |
| 40 | 46 | 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"; | |
| 42 | 48 | import type { Ctx } from "../src/http/context.ts"; |
| 43 | 49 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 44 | 50 | import { ok } from "../src/kernel/result.ts"; |
| @@ -46,7 +52,7 @@ import { usePlacement } from "../src/spawn/door.ts"; | ||
| 46 | 52 | import { bootHostedChild, closeHostedChildren } from "../src/spawn/host.ts"; |
| 47 | 53 | import { getPaidPlacement } from "../src/settings/paid_placement.ts"; |
| 48 | 54 | import { quietLogs } from "./helpers/globals.ts"; |
| 49 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 55 | import { ocean, seedPlaces } from "./helpers/places-fixture.ts"; | |
| 50 | 56 | |
| 51 | 57 | quietLogs(); |
| 52 | 58 | |
| @@ -405,6 +411,13 @@ describe("a paid order on a cloud account", () => { | ||
| 405 | 411 | expect(r).toMatchObject({ ok: false, error: { field: "name" } }); |
| 406 | 412 | }); |
| 407 | 413 | |
| 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 | ||
| 408 | 421 | const ctxOf = (path: string, cookie = ""): Ctx => { |
| 409 | 422 | const url = new URL(`https://forge.test${path}`); |
| 410 | 423 | 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", () => { | ||
| 491 | 504 | expect(body).toContain("<name>.forges.test on its own machine"); |
| 492 | 505 | expect(body).toContain("its machine is deleted and its data kept"); |
| 493 | 506 | }); |
| 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 | }); | |
| 494 | 615 | }); |
test/palette-roster.test.ts +1
| @@ -219,6 +219,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 219 | 219 | ["security-controls", "Security controls", "each safeguard, its state, and when it was last checked"], |
| 220 | 220 | ["billing", "Billing", "each forge's plan, and grant one by hand"], |
| 221 | 221 | ["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"], | |
| 222 | 223 | ["codes", "Gift codes", "make a code that gives a plan for free, and revoke one"], |
| 223 | 224 | ["archived", "Archived repositories", "put away, not gone: open one or restore it"], |
| 224 | 225 | ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"], |
new above
offline