From 72083b62f5ec9bb906b82ddb1c98ee29f7f1f494 Mon Sep 17 00:00:00 2001 From: JasonYv Date: Sat, 31 Oct 2026 22:01:37 +0800 Subject: [PATCH 01/26] feat: let a seller set where an order can ship and what shipping costs Checkout needs to know whether an address can be shipped to and what it costs before Stripe is asked for anything. A seller now groups countries into zones in the admin, each with a rate per currency and an optional amount from which it ships free; a country in no zone cannot be ordered to. The migration also adds what an order records at checkout (its cart, company, tax number, zone, tax mode, the digest of the buyer's link, the carrier, when its payment page lapses) and the settings and secrets checkout reads. The export carries the zones, and leaves an order's cart and link digest behind. --- src/plugins/shop/index.ts | 12 + src/plugins/shop/lib/export.ts | 19 ++ src/plugins/shop/lib/shipping-records.ts | 260 ++++++++++++++++++ src/plugins/shop/lib/shipping.ts | 165 +++++++++++ src/plugins/shop/migrations/0004_checkout.sql | 72 +++++ src/plugins/shop/plugin.json | 98 ++++++- test/shop/export.test.ts | 73 ++++- test/shop/helpers.ts | 3 + test/shop/schema.test.ts | 13 + test/shop/shipping.test.ts | 259 +++++++++++++++++ 10 files changed, 960 insertions(+), 14 deletions(-) create mode 100644 src/plugins/shop/lib/shipping-records.ts create mode 100644 src/plugins/shop/lib/shipping.ts create mode 100644 src/plugins/shop/migrations/0004_checkout.sql create mode 100644 test/shop/shipping.test.ts diff --git a/src/plugins/shop/index.ts b/src/plugins/shop/index.ts index 9cbd61c..db6a11a 100644 --- a/src/plugins/shop/index.ts +++ b/src/plugins/shop/index.ts @@ -24,6 +24,11 @@ import { import { INQUIRY_EMAILS_JOB, sendInquiryEmails } from './lib/inquiry-jobs.js'; import { renderData } from './lib/render-data.js'; import { runScheduledTick } from './lib/scheduled.js'; +import { + loadShippingZone, + removeShippingZone, + saveShippingZone, +} from './lib/shipping-records.js'; import { loadVariant, onProductDeleted, @@ -33,6 +38,7 @@ import { import shopSql from './migrations/0001_shop.sql'; import ordersSql from './migrations/0002_orders.sql'; import inquiriesSql from './migrations/0003_inquiries.sql'; +import checkoutSql from './migrations/0004_checkout.sql'; import manifest from './plugin.json'; import { cartPage, cartUpdate } from './routes/cart.js'; import { cartInquiry } from './routes/inquiry.js'; @@ -52,6 +58,7 @@ export const shop = definePlugin({ { id: 'plugin:shop:0001_shop', sql: shopSql }, { id: 'plugin:shop:0002_orders', sql: ordersSql }, { id: 'plugin:shop:0003_inquiries', sql: inquiriesSql }, + { id: 'plugin:shop:0004_checkout', sql: checkoutSql }, ], hooks: { scheduled, @@ -65,6 +72,11 @@ export const shop = definePlugin({ save: (record, ctx) => saveVariant(record, ctx), remove: (id, ctx) => removeVariant(id, ctx), }, + shipping: { + load: loadShippingZone, + save: (record, ctx) => saveShippingZone(record, ctx), + remove: removeShippingZone, + }, }, // What the shop holds travels with a site export: leaving Mallok must not // mean leaving the catalogue, the orders or the inquiries behind. diff --git a/src/plugins/shop/lib/export.ts b/src/plugins/shop/lib/export.ts index b90a81a..b30f0e3 100644 --- a/src/plugins/shop/lib/export.ts +++ b/src/plugins/shop/lib/export.ts @@ -10,6 +10,7 @@ * settings.json the shop's own settings, as the admin has them * variants.json with the slug of the product each belongs to * prices.json with each variant's SKU + * shipping-zones.json, shipping-countries.json, shipping-rates.json * stock-adjustments.json the ledger of every change of stock * orders.json, order-lines.json * payment-events.json every payment acted on, and what was done @@ -103,6 +104,21 @@ const TABLES: readonly ExportedTable[] = [ LEFT JOIN p_shop_variant AS v ON v.id = p.variant_id ORDER BY p.variant_id, p.currency LIMIT ?`, }, + { + name: 'shipping-zones', + table: 'p_shop_shipping_zone', + sql: 'SELECT * FROM p_shop_shipping_zone ORDER BY sort_order, name, id LIMIT ?', + }, + { + name: 'shipping-countries', + table: 'p_shop_shipping_country', + sql: 'SELECT * FROM p_shop_shipping_country ORDER BY country LIMIT ?', + }, + { + name: 'shipping-rates', + table: 'p_shop_shipping_rate', + sql: 'SELECT * FROM p_shop_shipping_rate ORDER BY zone_id, currency LIMIT ?', + }, { name: 'stock-adjustments', table: 'p_shop_stock_adjustment', @@ -112,6 +128,9 @@ const TABLES: readonly ExportedTable[] = [ name: 'orders', table: 'p_shop_order', sql: 'SELECT * FROM p_shop_order ORDER BY created_at, id LIMIT ?', + // The cart an order came from and the digest of the buyer's link: the + // one was a credential, the other is a credential's fingerprint. + without: ['cart_id', 'access_hash'], }, { name: 'order-lines', diff --git a/src/plugins/shop/lib/shipping-records.ts b/src/plugins/shop/lib/shipping-records.ts new file mode 100644 index 0000000..95ef4cd --- /dev/null +++ b/src/plugins/shop/lib/shipping-records.ts @@ -0,0 +1,260 @@ +/** + * The admin's form for shipping zones: a `records` panel, which Mallok draws + * and never writes itself. A zone has a name, the countries in it, and a rate + * in each currency it can be paid in. + * + * A country is in one zone at most. The key of `p_shop_shipping_country` + * says so; a save that would put one in a second zone is answered with the + * zone it is in already, read from the table — first before the write, and + * again if the write still met one, since two saves can cross. + */ + +import type { + MoneyValue, + PluginContext, + PluginRecordInput, +} from 'mallok/worker'; +import { type Currency, isCurrency } from './currency.js'; +import { isKnownCountry } from './shipping.js'; + +type SaveResult = + | { readonly id: string } + | { readonly errors: Readonly> }; + +interface RateRow { + readonly price: MoneyValue | null; + readonly free_over: MoneyValue | null; +} + +export async function loadShippingZone( + id: string, + ctx: PluginContext, +): Promise | null> { + const [zoneResult, countryResult, rateResult] = await ctx.db.batch< + Record + >([ + ctx.db + .prepare('SELECT name, sort_order FROM p_shop_shipping_zone WHERE id = ?') + .bind(id), + ctx.db + .prepare( + 'SELECT country FROM p_shop_shipping_country WHERE zone_id = ? ORDER BY country', + ) + .bind(id), + ctx.db + .prepare( + `SELECT currency, amount_minor, free_over_minor FROM p_shop_shipping_rate + WHERE zone_id = ? ORDER BY currency`, + ) + .bind(id), + ]); + const zone = (zoneResult?.results ?? [])[0]; + if (zone === undefined) { + return null; + } + return { + name: zone.name, + countries: (countryResult?.results ?? []).map((row) => row.country), + rates: (rateResult?.results ?? []).map((row) => ({ + price: { amount: row.amount_minor, currency: row.currency }, + free_over: + row.free_over_minor === null + ? null + : { amount: row.free_over_minor, currency: row.currency }, + })), + sort_order: zone.sort_order, + }; +} + +function textOf(value: unknown): string { + return typeof value === 'string' ? value.trim() : ''; +} + +/** The values of a zone as the form sent them, or what is wrong with them. */ +function check(values: Readonly>): + | { + readonly ok: true; + readonly name: string; + readonly countries: string[]; + readonly rates: { + currency: Currency; + amountMinor: number; + freeOverMinor: number | null; + }[]; + readonly sortOrder: number; + } + | { readonly ok: false; readonly errors: Record } { + const errors: Record = {}; + const name = textOf(values.name); + if (name === '' || name.length > 100) { + errors.name = 'A zone needs a name of up to 100 characters.'; + } + + const listed = Array.isArray(values.countries) ? values.countries : []; + const countries = [ + ...new Set(listed.map((entry) => textOf(entry).toUpperCase())), + ]; + const unknown = countries.filter((code) => !isKnownCountry(code)); + if (countries.length === 0) { + errors.countries = 'A zone needs at least one country.'; + } else if (unknown.length > 0) { + errors.countries = `Not a country code: ${unknown.join(', ')}. Use the two-letter ISO code, such as DE.`; + } + + const rows = (Array.isArray(values.rates) ? values.rates : []) as RateRow[]; + const rates: { + currency: Currency; + amountMinor: number; + freeOverMinor: number | null; + }[] = []; + rows.forEach((row, index) => { + const price = row.price; + if (price === null || !isCurrency(price.currency)) { + errors[`rates.${index}.price`] = 'Each rate needs an amount.'; + return; + } + if (rates.some((rate) => rate.currency === price.currency)) { + errors[`rates.${index}.price`] = + `There is a rate in ${price.currency} already.`; + return; + } + const freeOver = row.free_over; + if (freeOver !== null && freeOver.currency !== price.currency) { + errors[`rates.${index}.free_over`] = + `The amount past which shipping is free has to be in ${price.currency}, like the rate.`; + return; + } + if (freeOver !== null && freeOver.amount <= 0) { + errors[`rates.${index}.free_over`] = + 'Leave it empty for no free shipping, or give an amount above nothing.'; + return; + } + rates.push({ + currency: price.currency, + amountMinor: price.amount, + freeOverMinor: freeOver === null ? null : freeOver.amount, + }); + }); + if (rows.length === 0) { + errors.rates = 'A zone needs a rate in at least one currency.'; + } + + const sortOrder = + typeof values.sort_order === 'number' && Number.isInteger(values.sort_order) + ? values.sort_order + : 0; + + return Object.keys(errors).length > 0 + ? { ok: false, errors } + : { ok: true, name, countries, rates, sortOrder }; +} + +/** The countries of a list that are in another zone, with that zone's name. */ +async function takenElsewhere( + db: D1Database, + zoneId: string, + countries: readonly string[], +): Promise { + const { results } = await db + .prepare( + `SELECT c.country AS country, z.name AS zone + FROM p_shop_shipping_country AS c + JOIN p_shop_shipping_zone AS z ON z.id = c.zone_id + WHERE c.zone_id <> ? + AND c.country IN (SELECT value FROM json_each(?)) + ORDER BY c.country`, + ) + .bind(zoneId, JSON.stringify(countries)) + .all<{ country: string; zone: string }>(); + return results.map((row) => `${row.country} (${row.zone})`); +} + +export async function saveShippingZone( + record: PluginRecordInput, + ctx: PluginContext, + now: Date = new Date(), +): Promise { + const checked = check(record.values); + if (!checked.ok) { + return { errors: checked.errors }; + } + const id = record.id ?? crypto.randomUUID(); + const elsewhere = await takenElsewhere(ctx.db, id, checked.countries); + if (elsewhere.length > 0) { + return { + errors: { + countries: `Already in another zone: ${elsewhere.join(', ')}. A country is in one zone at most.`, + }, + }; + } + + const nowIso = now.toISOString(); + const countries = JSON.stringify(checked.countries); + try { + await ctx.db.batch([ + ctx.db + .prepare( + `INSERT INTO p_shop_shipping_zone (id, name, sort_order, created_at, updated_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT (id) DO UPDATE SET + name = excluded.name, sort_order = excluded.sort_order, + updated_at = excluded.updated_at`, + ) + .bind(id, checked.name, checked.sortOrder, nowIso, nowIso), + ctx.db + .prepare('DELETE FROM p_shop_shipping_country WHERE zone_id = ?') + .bind(id), + ctx.db + .prepare( + `INSERT INTO p_shop_shipping_country (country, zone_id) + SELECT value, ? FROM json_each(?)`, + ) + .bind(id, countries), + ctx.db + .prepare('DELETE FROM p_shop_shipping_rate WHERE zone_id = ?') + .bind(id), + ctx.db + .prepare( + `INSERT INTO p_shop_shipping_rate + (zone_id, currency, amount_minor, free_over_minor) + SELECT ?, json_extract(value, '$.currency'), + json_extract(value, '$.amountMinor'), + json_extract(value, '$.freeOverMinor') + FROM json_each(?)`, + ) + .bind(id, JSON.stringify(checked.rates)), + ]); + } catch (error) { + // Another save took a country between this one's reading and its write. + // Which one is read again, rather than guessed from the error's text. + const crossed = await takenElsewhere(ctx.db, id, checked.countries); + if (crossed.length > 0) { + return { + errors: { + countries: `Already in another zone: ${crossed.join(', ')}. A country is in one zone at most.`, + }, + }; + } + throw error; + } + return { id }; +} + +/** + * Removes a zone, its countries and its rates. An order shipped to it keeps + * the zone's name, which it was given as a snapshot. + */ +export async function removeShippingZone( + id: string, + ctx: PluginContext, +): Promise { + await ctx.db.batch([ + ctx.db + .prepare('DELETE FROM p_shop_shipping_rate WHERE zone_id = ?') + .bind(id), + ctx.db + .prepare('DELETE FROM p_shop_shipping_country WHERE zone_id = ?') + .bind(id), + ctx.db.prepare('DELETE FROM p_shop_shipping_zone WHERE id = ?').bind(id), + ]); +} diff --git a/src/plugins/shop/lib/shipping.ts b/src/plugins/shop/lib/shipping.ts new file mode 100644 index 0000000..7f28f40 --- /dev/null +++ b/src/plugins/shop/lib/shipping.ts @@ -0,0 +1,165 @@ +/** + * What shipping an order costs. + * + * A seller groups the countries they ship to into zones, and gives each zone + * a fixed rate in each currency, and if they like an amount past which it + * ships free. A country in no zone is one the shop does not ship to, and + * cannot be checked out to. + * + * Every product weighs something (`weight_grams`), so a rate by weight can be + * added later without new data; a fixed rate per zone is what was decided + * (design §20). + */ + +import { CURRENCIES, type Currency, isCurrency } from './currency.js'; + +/** A zone's rate in one currency. */ +export interface ShippingRate { + readonly zoneId: string; + readonly zoneName: string; + readonly currency: Currency; + readonly amountMinor: number; + /** Goods coming to this much or more ship free. Null when nothing does. */ + readonly freeOverMinor: number | null; +} + +export function isCountryCode(value: string): boolean { + return /^[A-Z]{2}$/.test(value); +} + +/** + * A country's name in a language, for a page or an email. The code itself + * when the runtime does not know the region: a name is a convenience, and a + * code is never wrong. + */ +export function countryName(code: string, locale: string): string { + try { + return ( + new Intl.DisplayNames([locale], { type: 'region', fallback: 'code' }).of( + code, + ) ?? code + ); + } catch { + return code; + } +} + +/** + * Whether the runtime knows a code as a region. `Intl.DisplayNames` answers + * an unknown code with the code itself, which is how one is told apart. + */ +export function isKnownCountry(code: string): boolean { + if (!isCountryCode(code)) { + return false; + } + try { + return ( + new Intl.DisplayNames(['en'], { type: 'region', fallback: 'none' }).of( + code, + ) !== undefined + ); + } catch { + return false; + } +} + +/** The rate for a country in a currency: one row, or none. */ +export function shippingRateStatement( + db: D1Database, + country: string, + currency: Currency, +): D1PreparedStatement { + return db + .prepare( + `SELECT z.id AS zone_id, z.name AS zone_name, r.currency AS currency, + r.amount_minor AS amount_minor, + r.free_over_minor AS free_over_minor + FROM p_shop_shipping_country AS c + JOIN p_shop_shipping_zone AS z ON z.id = c.zone_id + JOIN p_shop_shipping_rate AS r ON r.zone_id = z.id AND r.currency = ? + WHERE c.country = ?`, + ) + .bind(currency, country); +} + +export function rateOf(row: unknown): ShippingRate | null { + if (row === null || typeof row !== 'object') { + return null; + } + const value = row as Record; + const currency = String(value.currency ?? ''); + if ( + typeof value.zone_id !== 'string' || + typeof value.zone_name !== 'string' || + !isCurrency(currency) || + typeof value.amount_minor !== 'number' + ) { + return null; + } + return { + zoneId: value.zone_id, + zoneName: value.zone_name, + currency, + amountMinor: value.amount_minor, + freeOverMinor: + typeof value.free_over_minor === 'number' ? value.free_over_minor : null, + }; +} + +/** The countries the shop ships to, with the currencies each can be paid in. */ +export function shippingCountriesStatement( + db: D1Database, +): D1PreparedStatement { + return db.prepare( + `SELECT c.country AS country, + (SELECT json_group_array(r.currency) FROM p_shop_shipping_rate AS r + WHERE r.zone_id = c.zone_id) AS currencies + FROM p_shop_shipping_country AS c + ORDER BY c.country`, + ); +} + +export interface ShippingCountry { + readonly code: string; + readonly currencies: readonly Currency[]; +} + +export function shippingCountriesOf( + rows: readonly unknown[], +): ShippingCountry[] { + return rows.flatMap((row) => { + const value = row as { country?: unknown; currencies?: unknown }; + if (typeof value.country !== 'string') { + return []; + } + let currencies: unknown = []; + try { + currencies = JSON.parse(String(value.currencies ?? '[]')); + } catch { + currencies = []; + } + return [ + { + code: value.country, + currencies: CURRENCIES.filter( + (currency) => + Array.isArray(currencies) && currencies.includes(currency), + ), + }, + ]; + }); +} + +/** + * What shipping costs for goods of a value, at a rate. Free past the rate's + * threshold, which compares the goods alone: shipping does not count towards + * its own waiver, and neither would a tax. + */ +export function shippingCostMinor( + rate: Pick, + goodsMinor: number, +): number { + return rate.freeOverMinor !== null && goodsMinor >= rate.freeOverMinor + ? 0 + : rate.amountMinor; +} diff --git a/src/plugins/shop/migrations/0004_checkout.sql b/src/plugins/shop/migrations/0004_checkout.sql new file mode 100644 index 0000000..bdb9974 --- /dev/null +++ b/src/plugins/shop/migrations/0004_checkout.sql @@ -0,0 +1,72 @@ +-- Shop plugin: what checkout needs — more about an order, and the zones an +-- order can be shipped to. +-- +-- Mallok's migrator drops whole-line comments and then splits on semicolons, +-- so a comment must have a line to itself, and none here contains a +-- semicolon. A migration is applied once, in one batch with the record of +-- its having been applied, so the columns added here cannot be added twice. + +-- The cart an order was placed from. Emptied once the order is paid, not +-- before: a payment that fails must not cost the buyer their cart +ALTER TABLE p_shop_order ADD COLUMN cart_id TEXT; + +-- A digest of the secret in the link the buyer is sent to follow their +-- order. The secret itself is in the link and nowhere in the database +ALTER TABLE p_shop_order ADD COLUMN access_hash TEXT; + +-- Who is buying: the shop sells to businesses +ALTER TABLE p_shop_order ADD COLUMN company TEXT NOT NULL DEFAULT ''; + +-- The buyer's VAT or other tax number, when they gave one +ALTER TABLE p_shop_order ADD COLUMN tax_id TEXT NOT NULL DEFAULT ''; + +-- Who carries the order, beside its tracking number +ALTER TABLE p_shop_order ADD COLUMN carrier TEXT; + +-- The zone the order was shipped to, by name, as it was when the order was +-- placed: a snapshot, like the lines +ALTER TABLE p_shop_order ADD COLUMN shipping_zone TEXT NOT NULL DEFAULT ''; + +-- none: no tax is charged. stripe: Stripe calculates it at checkout, and the +-- order's tax and total are known once the payment is +ALTER TABLE p_shop_order ADD COLUMN tax_mode TEXT NOT NULL DEFAULT 'none'; + +-- When the Checkout session the order was sent to stops taking payment +ALTER TABLE p_shop_order ADD COLUMN stripe_session_expires_at TEXT; + +-- For a payment the shop had to refuse: the refund a person made of it +ALTER TABLE p_shop_stripe_event ADD COLUMN refund_id TEXT; + +CREATE TABLE IF NOT EXISTS p_shop_shipping_zone ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + sort_order INTEGER NOT NULL DEFAULT 0 + CHECK (typeof(sort_order) = 'integer'), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +-- A country belongs to one zone at most: the key says so. A country in no +-- zone cannot be shipped to +CREATE TABLE IF NOT EXISTS p_shop_shipping_country ( + -- ISO 3166-1 alpha-2, upper case + country TEXT PRIMARY KEY CHECK (length(country) = 2 AND country = upper(country)), + zone_id TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS p_shop_shipping_country_zone + ON p_shop_shipping_country (zone_id); + +-- What shipping to a zone costs, in each currency it can be paid in +CREATE TABLE IF NOT EXISTS p_shop_shipping_rate ( + zone_id TEXT NOT NULL, + currency TEXT NOT NULL, + amount_minor INTEGER NOT NULL + CHECK (typeof(amount_minor) = 'integer' AND amount_minor >= 0), + -- An order whose goods come to this much or more ships free. Null when + -- nothing does + free_over_minor INTEGER + CHECK (free_over_minor IS NULL + OR (typeof(free_over_minor) = 'integer' AND free_over_minor > 0)), + PRIMARY KEY (zone_id, currency) +); diff --git a/src/plugins/shop/plugin.json b/src/plugins/shop/plugin.json index 10fb67c..9a1337c 100644 --- a/src/plugins/shop/plugin.json +++ b/src/plugins/shop/plugin.json @@ -53,16 +53,31 @@ }, "inquiry_recipient": { "type": "string", - "label": "Inquiry recipient", - "help": "The address that is told by email when a cart is sent as an inquiry. The email is sent from the site's own address (Settings → Email) and is answered straight to the buyer. Left empty, inquiries are only listed here in the admin.", - "group": "Inquiries" + "label": "Notification email", + "help": "Where the shop tells the seller what needs them: a cart sent as an inquiry, a new order, an order paid for after its stock had gone, a payment that has to be refunded. The email is sent from the site's own address (Settings → Email). Left empty, all of it is only listed here in the admin.", + "group": "Notifications" }, "inquiry_acknowledge": { "type": "boolean", "label": "Confirm to the buyer by email", "help": "Sends the buyer an email saying their request arrived, in their language. Off by default: the form has no challenge in front of it, so anyone can have that email sent to an address that is not theirs.", "default": false, - "group": "Inquiries" + "group": "Notifications" + }, + "order_no_prefix": { + "type": "string", + "label": "Order number prefix", + "help": "What every order's number begins with, followed by the date and eight characters: ND-261031-7K3M9QXA. Up to six capital letters or digits.", + "default": "ND", + "group": "Orders" + }, + "tax_mode": { + "type": "select", + "label": "Tax", + "help": "none: prices are without tax and no tax is charged; the buyer settles any import duty and tax. stripe: Stripe Tax calculates tax at checkout where your account is registered to collect it, for a fee Stripe charges per transaction.", + "choices": ["none", "stripe"], + "default": "none", + "group": "Orders" } }, "panels": [ @@ -314,6 +329,79 @@ } } ] + }, + { + "id": "shipping", + "label": "Shipping zones", + "type": "records", + "table": "p_shop_shipping_zone", + "columns": [ + { + "field": "name", + "label": "Zone", + "sortable": true + }, + { + "field": "sort_order", + "label": "Order" + }, + { + "field": "updated_at", + "label": "Changed", + "type": "datetime" + } + ], + "search": ["name"], + "orderBy": "updated_at", + "fields": { + "name": { + "type": "string", + "label": "Name", + "required": true, + "help": "What the buyer sees beside the rate: Europe, United Kingdom." + }, + "countries": { + "type": "string[]", + "label": "Countries", + "required": true, + "help": "Two-letter ISO codes, such as DE or GB. A country is in one zone at most; one in no zone cannot be shipped to." + }, + "rates": { + "type": "rows", + "label": "Rates", + "max": 3, + "required": true, + "help": "What shipping to this zone costs in each currency it can be paid in. An order in a currency the zone has no rate in cannot be shipped there.", + "fields": { + "price": { + "type": "money", + "label": "Rate", + "required": true, + "currencies": ["USD", "EUR", "GBP"] + }, + "free_over": { + "type": "money", + "label": "Free from", + "currencies": ["USD", "EUR", "GBP"], + "help": "Goods coming to this much or more ship free. Empty: never free." + } + } + }, + "sort_order": { + "type": "number", + "label": "Order", + "default": 0, + "help": "Lower first in the list a buyer chooses a country from." + } + } + } + ], + "secrets": { + "stripe_secret_key": { + "label": "Stripe secret key" + }, + "stripe_webhook_secret": { + "label": "Stripe webhook signing secret" } - ] + } } diff --git a/test/shop/export.test.ts b/test/shop/export.test.ts index 29c0189..0282fad 100644 --- a/test/shop/export.test.ts +++ b/test/shop/export.test.ts @@ -125,6 +125,22 @@ async function fill(): Promise { at, ); await db().batch([ + db() + .prepare( + `INSERT INTO p_shop_shipping_zone (id, name, sort_order, created_at, updated_at) + VALUES ('zone-uk', 'United Kingdom', 2, ?, ?), + ('zone-eu', 'Europe', 1, ?, ?)`, + ) + .bind(LATER, LATER, EARLIER, EARLIER), + db().prepare( + `INSERT INTO p_shop_shipping_country (country, zone_id) + VALUES ('GB', 'zone-uk'), ('FR', 'zone-eu'), ('DE', 'zone-eu')`, + ), + db().prepare( + `INSERT INTO p_shop_shipping_rate (zone_id, currency, amount_minor, free_over_minor) + VALUES ('zone-uk', 'GBP', 3900, NULL), ('zone-eu', 'USD', 4900, 100000), + ('zone-eu', 'EUR', 4500, 90000)`, + ), db() .prepare( `INSERT INTO p_shop_stock_adjustment @@ -250,6 +266,9 @@ describe('the shop in a site export', () => { 'shop/payment-events.json', 'shop/prices.json', 'shop/settings.json', + 'shop/shipping-countries.json', + 'shop/shipping-rates.json', + 'shop/shipping-zones.json', 'shop/stock-adjustments.json', 'shop/variants.json', ]); @@ -272,13 +291,24 @@ describe('the shop in a site export', () => { 'stock-adjustments', 'SELECT * FROM p_shop_stock_adjustment ORDER BY created_at, id', ], - ['orders', 'SELECT * FROM p_shop_order ORDER BY created_at, id'], ['order-lines', 'SELECT * FROM p_shop_order_line ORDER BY order_id, id'], [ 'payment-events', 'SELECT * FROM p_shop_stripe_event ORDER BY processed_at, event_id', ], ['outbox', 'SELECT * FROM p_shop_outbox ORDER BY seq'], + [ + 'shipping-zones', + 'SELECT * FROM p_shop_shipping_zone ORDER BY sort_order, name, id', + ], + [ + 'shipping-countries', + 'SELECT * FROM p_shop_shipping_country ORDER BY country', + ], + [ + 'shipping-rates', + 'SELECT * FROM p_shop_shipping_rate ORDER BY zone_id, currency', + ], [ 'inquiry-lines', 'SELECT * FROM p_shop_inquiry_line ORDER BY inquiry_id, position', @@ -293,10 +323,24 @@ describe('the shop in a site export', () => { 'manual:1', 'order_paid:o-1:cs-10', ]); + // An order whole, but for the cart it came from and the digest of the + // buyer's link. + expect(rowsOf(files, 'orders')).toEqual( + (await table('SELECT * FROM p_shop_order ORDER BY created_at, id')).map( + ({ cart_id: _cart, access_hash: _link, ...kept }) => kept, + ), + ); expect(rowsOf(files, 'orders').map((row) => row.id)).toEqual([ 'o-1', 'o-2', ]); + expect(rowsOf(files, 'shipping-zones').map((row) => row.id)).toEqual([ + 'zone-eu', + 'zone-uk', + ]); + expect( + rowsOf(files, 'shipping-countries').map((row) => row.country), + ).toEqual(['DE', 'FR', 'GB']); expect(rowsOf(files, 'order-lines').map((row) => row.id)).toEqual([ 'o-1:cs-10', 'o-1:cs-16', @@ -399,8 +443,10 @@ describe('the shop in a site export', () => { // A rate, which is fetched again, and the scheduler's state. expect(everything).not.toContain('0.87654321'); expect(everything).not.toContain('rates_tried_at'); + // No file of carts, exchange rates or the scheduler's state. Shipping + // rates are the seller's prices, and go. expect(files.map((file) => file.path).join(' ')).not.toMatch( - /cart|rate|state/, + /shop\/(carts?|cart-lines|rates|exchange-rates|state)\.json/, ); }); @@ -435,11 +481,14 @@ describe('the shop in a site export', () => { 'variant_id currency amount_minor source rate_used updated_at', p_shop_stock_adjustment: 'id variant_id delta reason ref_id created_at', p_shop_order: - 'id order_no status currency subtotal_minor shipping_minor tax_minor total_minor stripe_session_id stripe_payment_intent_id email shipping_address locale tracking_no created_at updated_at', + 'id order_no status currency subtotal_minor shipping_minor tax_minor total_minor stripe_session_id stripe_payment_intent_id email shipping_address locale tracking_no created_at updated_at cart_id access_hash company tax_id carrier shipping_zone tax_mode stripe_session_expires_at', p_shop_order_line: 'id order_id variant_id sku_snapshot name_snapshot unit_price_minor quantity', p_shop_stripe_event: - 'event_id type order_id payment_intent_id outcome processed_at', + 'event_id type order_id payment_intent_id outcome processed_at refund_id', + p_shop_shipping_zone: 'id name sort_order created_at updated_at', + p_shop_shipping_country: 'country zone_id', + p_shop_shipping_rate: 'zone_id currency amount_minor free_over_minor', p_shop_outbox: 'seq id topic order_id ref created_at handled_at', p_shop_inquiry: 'id inquiry_no status name email company phone message locale currency country line_count subtotal_minor subtotal cart_id ip_hash notified_at acknowledged_at created_at updated_at', @@ -466,6 +515,9 @@ describe('the shop in a site export', () => { tables: { variants: { file: 'shop/variants.json', rows: 3 }, prices: { file: 'shop/prices.json', rows: 4 }, + 'shipping-zones': { file: 'shop/shipping-zones.json', rows: 2 }, + 'shipping-countries': { file: 'shop/shipping-countries.json', rows: 3 }, + 'shipping-rates': { file: 'shop/shipping-rates.json', rows: 3 }, 'stock-adjustments': { file: 'shop/stock-adjustments.json', rows: 2 }, orders: { file: 'shop/orders.json', rows: 2 }, 'order-lines': { file: 'shop/order-lines.json', rows: 2 }, @@ -484,7 +536,7 @@ describe('the shop in a site export', () => { it('exports an empty shop as files that are empty and valid', async () => { const files = await exported(); - expect(files).toHaveLength(11); + expect(files).toHaveLength(14); expect(files[1]?.text).toBe('{}\n'); for (const file of files.slice(2)) { expect(file.text, file.path).toBe('[]\n'); @@ -497,7 +549,7 @@ describe('the shop in a site export', () => { } ).tables, ).map((entry) => entry.rows), - ).toEqual([0, 0, 0, 0, 0, 0, 0, 0, 0]); + ).toEqual([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); }); it('writes a row to a line, to every reader of lines', async () => { @@ -554,6 +606,9 @@ describe('the shop in a site export', () => { const NAMES = [ 'variants', 'prices', + 'shipping-zones', + 'shipping-countries', + 'shipping-rates', 'stock-adjustments', 'orders', 'order-lines', @@ -573,7 +628,7 @@ describe('the shop in a site export', () => { // As many as there may be, in every table. await expect( exportShopFiles(holding(counts(7)), options), - ).resolves.toHaveLength(11); + ).resolves.toHaveLength(14); // One more than that, in this one. await expect( exportShopFiles(holding(counts(8)), options), @@ -589,7 +644,7 @@ describe('the shop in a site export', () => { await fill(); // Three variants and four prices, really read. - await expect(exported({ rowLimit: 4 })).resolves.toHaveLength(11); + await expect(exported({ rowLimit: 4 })).resolves.toHaveLength(14); await expect(exported({ rowLimit: 3 })).rejects.toThrow( /^The shop's prices have more than 3 rows/, ); @@ -604,7 +659,7 @@ describe('the shop in a site export', () => { .slice(2) .reduce((total, file) => total + file.text.length * 2, 0); - await expect(exported({ byteLimit: size })).resolves.toHaveLength(11); + await expect(exported({ byteLimit: size })).resolves.toHaveLength(14); await expect(exported({ byteLimit: size - 1 })).rejects.toThrow( /^The shop's inquiry-lines bring the export past \d+ bytes of text/, ); diff --git a/test/shop/helpers.ts b/test/shop/helpers.ts index e067a2f..5715997 100644 --- a/test/shop/helpers.ts +++ b/test/shop/helpers.ts @@ -335,6 +335,9 @@ export async function setRate( export async function clearShopTables(): Promise { await db().batch( [ + 'p_shop_shipping_rate', + 'p_shop_shipping_country', + 'p_shop_shipping_zone', 'p_shop_inquiry_line', 'p_shop_inquiry', 'p_shop_outbox', diff --git a/test/shop/schema.test.ts b/test/shop/schema.test.ts index 86f9e9a..8011664 100644 --- a/test/shop/schema.test.ts +++ b/test/shop/schema.test.ts @@ -38,6 +38,9 @@ describe('the shop schema', () => { 'p_shop_outbox', 'p_shop_price', 'p_shop_rate', + 'p_shop_shipping_country', + 'p_shop_shipping_rate', + 'p_shop_shipping_zone', 'p_shop_state', 'p_shop_stock_adjustment', 'p_shop_stripe_event', @@ -53,6 +56,7 @@ describe('the shop schema', () => { 'plugin:shop:0001_shop', 'plugin:shop:0002_orders', 'plugin:shop:0003_inquiries', + 'plugin:shop:0004_checkout', ]); }); @@ -115,6 +119,11 @@ describe('the shop schema', () => { }; expect(await columns('p_shop_order')).toEqual([ + // A digest of the secret in the buyer's link, never the secret. + 'access_hash', + 'carrier', + 'cart_id', + 'company', 'created_at', 'currency', 'email', @@ -123,11 +132,15 @@ describe('the shop schema', () => { 'order_no', 'shipping_address', 'shipping_minor', + 'shipping_zone', 'status', 'stripe_payment_intent_id', + 'stripe_session_expires_at', 'stripe_session_id', 'subtotal_minor', + 'tax_id', 'tax_minor', + 'tax_mode', 'total_minor', 'tracking_no', 'updated_at', diff --git a/test/shop/shipping.test.ts b/test/shop/shipping.test.ts new file mode 100644 index 0000000..38aeb4a --- /dev/null +++ b/test/shop/shipping.test.ts @@ -0,0 +1,259 @@ +import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { + countryName, + isKnownCountry, + rateOf, + shippingCostMinor, + shippingCountriesOf, + shippingCountriesStatement, + shippingRateStatement, +} from '../../src/plugins/shop/lib/shipping.js'; +import { api, clearShopTables, db, ensureSite, holdWrites } from './helpers.js'; + +const PANEL = '/_mallok/api/plugins/shop/panels/shipping'; + +function zone(values: Record): Promise { + return api('POST', `${PANEL}/records`, { + values: { + name: 'Europe', + countries: ['DE', 'FR'], + rates: [ + { + price: { amount: 4500, currency: 'EUR' }, + free_over: { amount: 90000, currency: 'EUR' }, + }, + { price: { amount: 4900, currency: 'USD' }, free_over: null }, + ], + sort_order: 1, + ...values, + }, + }); +} + +async function errorsOf(response: Response): Promise> { + expect(response.status).toBe(422); + return ((await response.json()) as { errors: Record }).errors; +} + +describe('shipping', () => { + describe('a country', () => { + it('is named in the page’s language, and is its code where it has no name', () => { + expect(countryName('DE', 'en')).toBe('Germany'); + expect(countryName('DE', 'de')).toBe('Deutschland'); + expect(countryName('GB', 'fr')).toBe('Royaume-Uni'); + expect(countryName('QZ', 'en')).toBe('QZ'); + }); + + it('is known by its two-letter code, in capitals, and no other way', () => { + expect(isKnownCountry('DE')).toBe(true); + expect(isKnownCountry('de')).toBe(false); + expect(isKnownCountry('QZ')).toBe(false); + expect(isKnownCountry('DEU')).toBe(false); + expect(isKnownCountry('')).toBe(false); + }); + }); + + describe('what it costs', () => { + const rate = { amountMinor: 4500, freeOverMinor: 90000 }; + + it('is the zone’s rate below the amount past which it is free', () => { + expect(shippingCostMinor(rate, 89999)).toBe(4500); + }); + + it('is nothing from that amount up', () => { + expect(shippingCostMinor(rate, 90000)).toBe(0); + expect(shippingCostMinor(rate, 250000)).toBe(0); + }); + + it('is always the rate where nothing ships free', () => { + expect( + shippingCostMinor({ amountMinor: 4500, freeOverMinor: null }, 10 ** 9), + ).toBe(4500); + }); + }); + + describe('zones in the admin', () => { + beforeAll(ensureSite); + beforeEach(clearShopTables); + + it('are saved with their countries and rates, and read back as the form sends them', async () => { + const created = await zone({ countries: ['de', 'FR', 'DE', ' fr '] }); + expect(created.status).toBe(201); + const { id } = (await created.json()) as { id: string }; + + const loaded = await api('GET', `${PANEL}/records/${id}`); + + expect(await loaded.json()).toMatchObject({ + values: { + name: 'Europe', + // Upper case, once each. + countries: ['DE', 'FR'], + rates: [ + { + price: { amount: 4500, currency: 'EUR' }, + free_over: { amount: 90000, currency: 'EUR' }, + }, + { price: { amount: 4900, currency: 'USD' }, free_over: null }, + ], + sort_order: 1, + }, + }); + }); + + it('give a country its rate in a currency, and nothing in a currency they have no rate in', async () => { + await zone({}); + const read = async (country: string, currency: 'EUR' | 'GBP') => + rateOf( + (await shippingRateStatement(db(), country, currency).all()) + .results[0] ?? null, + ); + + expect(await read('DE', 'EUR')).toEqual({ + zoneId: expect.any(String), + zoneName: 'Europe', + currency: 'EUR', + amountMinor: 4500, + freeOverMinor: 90000, + }); + expect(await read('DE', 'GBP')).toBeNull(); + // A country in no zone is not shipped to. + expect(await read('GB', 'EUR')).toBeNull(); + }); + + it('list the countries shipped to, with the currencies each can be paid in', async () => { + await zone({}); + await zone({ + name: 'United Kingdom', + countries: ['GB'], + rates: [{ price: { amount: 3900, currency: 'GBP' }, free_over: null }], + }); + + const { results } = await shippingCountriesStatement(db()).all(); + + expect(shippingCountriesOf(results)).toEqual([ + { code: 'DE', currencies: ['USD', 'EUR'] }, + { code: 'FR', currencies: ['USD', 'EUR'] }, + { code: 'GB', currencies: ['GBP'] }, + ]); + }); + + it.each([ + [{ name: ' ' }, 'name'], + [{ countries: [] }, 'countries'], + [{ countries: ['DE', 'QZ', 'Germany'] }, 'countries'], + [{ rates: [] }, 'rates'], + [ + { + rates: [ + { price: { amount: 4500, currency: 'EUR' }, free_over: null }, + { price: { amount: 4600, currency: 'EUR' }, free_over: null }, + ], + }, + 'rates.1.price', + ], + [ + { + rates: [ + { + price: { amount: 4500, currency: 'EUR' }, + free_over: { amount: 90000, currency: 'USD' }, + }, + ], + }, + 'rates.0.free_over', + ], + ])('refuse %j, beside the field %s', async (values, field) => { + const errors = await errorsOf(await zone(values)); + + expect(Object.keys(errors)).toContain(field); + const { results } = await db() + .prepare('SELECT COUNT(*) AS n FROM p_shop_shipping_zone') + .all<{ n: number }>(); + expect(results[0]?.n).toBe(0); + }); + + it('put a country in one zone at most, and say which zone has it', async () => { + await zone({}); + + const errors = await errorsOf( + await zone({ name: 'Western Europe', countries: ['FR', 'ES'] }), + ); + + expect(errors.countries).toBe( + 'Already in another zone: FR (Europe). A country is in one zone at most.', + ); + }); + + it('put a country in one zone at most when two saves claim it at once', async () => { + // Both read "nobody has FR" before either writes; the table's key + // refuses the second, which reads again to say who has it. + const gate = holdWrites((sql) => + sql.includes('INSERT INTO p_shop_shipping_zone'), + ); + let answers: Response[]; + try { + const both = Promise.all([ + zone({ name: 'One', countries: ['FR'] }), + zone({ name: 'Two', countries: ['FR'] }), + ]); + await gate.arrived(2); + gate.open(); + answers = await both; + } finally { + gate.restore(); + } + + expect(answers.map((answer) => answer.status).sort()).toEqual([201, 422]); + const { results } = await db() + .prepare( + 'SELECT z.name AS name FROM p_shop_shipping_country AS c JOIN p_shop_shipping_zone AS z ON z.id = c.zone_id', + ) + .all<{ name: string }>(); + expect(results).toHaveLength(1); + // The refused save left no zone behind. + const zones = await db() + .prepare('SELECT COUNT(*) AS n FROM p_shop_shipping_zone') + .first<{ n: number }>(); + expect(zones?.n).toBe(1); + }); + + it('move a country by saving the zone without it, then the other with it', async () => { + const created = await zone({}); + const { id } = (await created.json()) as { id: string }; + const edited = await api('PUT', `${PANEL}/records/${id}`, { + values: { + name: 'Europe', + countries: ['DE'], + rates: [ + { price: { amount: 4500, currency: 'EUR' }, free_over: null }, + ], + sort_order: 1, + }, + }); + expect(edited.status).toBe(200); + + const other = await zone({ name: 'France', countries: ['FR'] }); + + expect(other.status).toBe(201); + }); + + it('take their countries and rates with them when deleted', async () => { + const created = await zone({}); + const { id } = (await created.json()) as { id: string }; + + const removed = await api('DELETE', `${PANEL}/records/${id}`); + + expect(removed.ok).toBe(true); + for (const table of [ + 'p_shop_shipping_zone', + 'p_shop_shipping_country', + 'p_shop_shipping_rate', + ]) { + const row = await db() + .prepare(`SELECT COUNT(*) AS n FROM ${table}`) + .first<{ n: number }>(); + expect(row?.n, table).toBe(0); + } + }); + }); +}); From b03ddec96418e676a602bba2fa31e2e5195c7556 Mon Sep 17 00:00:00 2001 From: JasonYv Date: Sat, 31 Oct 2026 22:01:37 +0800 Subject: [PATCH 02/26] feat: hold every payment to its order, and settle lapsed and oversold orders A payment is now checked against the order's currency and total before it is taken; one that does not fit is refused and owed a refund, as a payment for a cancelled order already was. With Stripe calculating tax, the tax is what the payment came to beyond the goods and the shipping. A lapsed Checkout session cancels the order it was for, so a pending order does not hold its prices for ever. An oversold order is refunded, or restocked and fulfilled; it can no longer simply be cancelled, which left a payment taken and nobody owing it back. A refund may leave the stock alone when the goods stay with the buyer, shipping records the carrier, and a cancellation says why on what it owes. --- src/plugins/shop/lib/order-fulfilment.ts | 273 +++++++++++++++++++-- src/plugins/shop/lib/order-state.ts | 9 +- src/plugins/shop/lib/orders.ts | 208 ++++++++++++++-- src/plugins/shop/lib/outbox.ts | 4 +- src/plugins/shop/lib/stripe-webhook.ts | 84 +++++++ test/shop/order-fulfilment.test.ts | 287 +++++++++++++++++++++++ test/shop/order-state.test.ts | 8 +- test/shop/orders.test.ts | 125 ++++++++++ test/shop/stripe-webhook.test.ts | 163 ++++++++++++- 9 files changed, 1108 insertions(+), 53 deletions(-) diff --git a/src/plugins/shop/lib/order-fulfilment.ts b/src/plugins/shop/lib/order-fulfilment.ts index 652083b..8584434 100644 --- a/src/plugins/shop/lib/order-fulfilment.ts +++ b/src/plugins/shop/lib/order-fulfilment.ts @@ -1,6 +1,7 @@ /** * What a person does to an order after it is placed: ship it, mark it - * delivered, cancel it, refund it. + * delivered, cancel it, refund it, or fulfil one that was oversold once its + * stock is back. * * Every change is checked against the state machine in `order-state.ts`, and * then written only if the order is still in the status that was checked. Two @@ -13,7 +14,7 @@ */ import { changedProductGroups, type StockRow } from './availability.js'; -import { ORDER_STILL_IN_STATUS } from './order-guard.js'; +import { ORDER_STILL_IN_STATUS, type SqlCondition } from './order-guard.js'; import { assertTransition, type OrderStatus } from './order-state.js'; import { OrderNotFoundError } from './orders.js'; import { orderChangedOutbox } from './outbox.js'; @@ -34,10 +35,18 @@ async function statusOf(db: D1Database, orderId: string): Promise { return row.status as OrderStatus; } +/** The order was not as read by the time the write ran: nothing changed. */ +export class OrderChangedError extends Error { + constructor(orderId: string) { + super( + `Order ${orderId} changed while it was being updated; nothing was written`, + ); + this.name = 'OrderChangedError'; + } +} + function changedUnderneath(orderId: string): Error { - return new Error( - `Order ${orderId} changed while it was being updated; nothing was written`, - ); + return new OrderChangedError(orderId); } /** Moves an order to `to`, if the state machine allows it from where it is. */ @@ -45,40 +54,76 @@ async function move( db: D1Database, input: OrderChange, to: Exclude, - trackingNo: string | null = null, + extra: { + readonly trackingNo?: string | null; + readonly carrier?: string | null; + /** Said on the outbox row: why an order was cancelled. */ + readonly ref?: string | null; + /** Something else about the order that must still hold. */ + readonly andIf?: SqlCondition; + /** The status already read, when the caller has read it. */ + readonly from?: OrderStatus; + } = {}, ): Promise { const { orderId, now } = input; - const from = await statusOf(db, orderId); + const from = extra.from ?? (await statusOf(db, orderId)); assertTransition(from, to); + const andIf: SqlCondition = extra.andIf ?? { sql: '1 = 1', binds: [] }; const results = await db.batch>([ - orderChangedOutbox(db, { orderId, from, to, now }), + orderChangedOutbox(db, { + orderId, + from, + to, + now, + ref: extra.ref ?? null, + ...(extra.andIf === undefined ? {} : { andIf: extra.andIf }), + }), // Last: the outbox row tests the status this statement changes. db .prepare( `UPDATE p_shop_order - SET status = ?, tracking_no = COALESCE(?, tracking_no), updated_at = ? - WHERE id = ? AND status = ? + SET status = ?, tracking_no = COALESCE(?, tracking_no), + carrier = COALESCE(?, carrier), updated_at = ? + WHERE id = ? AND status = ? AND ${andIf.sql} RETURNING id`, ) - .bind(to, trackingNo, now.toISOString(), orderId, from), + .bind( + to, + extra.trackingNo ?? null, + extra.carrier ?? null, + now.toISOString(), + orderId, + from, + ...andIf.binds, + ), ]); if ((results[1]?.results ?? []).length === 0) { throw changedUnderneath(orderId); } } -/** Ships a paid order: records the tracking number and moves it on. */ +/** + * Ships a paid order: records the tracking number, and the carrier when one + * is named, and moves it on. + */ export async function shipOrder( db: D1Database, - input: OrderChange & { readonly trackingNo: string }, + input: OrderChange & { + readonly trackingNo: string; + readonly carrier?: string | null; + }, ): Promise { const trackingNo = input.trackingNo.trim(); if (trackingNo === '') { // "Shipped" with nothing to track helps neither support nor the buyer. throw new Error('A tracking number is required to ship an order'); } - await move(db, input, 'shipped', trackingNo); + const carrier = input.carrier?.trim() ?? ''; + await move(db, input, 'shipped', { + trackingNo, + carrier: carrier === '' ? null : carrier, + }); } export async function markDelivered( @@ -88,17 +133,95 @@ export async function markDelivered( await move(db, input, 'delivered'); } +/** Why an order that was never paid for stopped waiting for its payment. */ +export type CancelReason = + /** Its Checkout session expired with nothing paid. */ + | 'expired' + /** Stripe would not open a Checkout session for it. */ + | 'failed' + /** The seller cancelled it. */ + | 'seller'; + /** - * Cancels an order that has not been paid for, or one that was oversold. + * Cancels an order that has not been paid for. * * A paid order is not cancelled, it is refunded: its stock and its money - * both have to go back. + * both have to go back. An oversold one is refunded too, or restocked and + * fulfilled; cancelling it would leave its payment owed to nobody. + * + * The reason is on the outbox row, which is how what follows knows whether + * the buyer is to be told: they are when the seller cancelled, and not when + * they simply let the payment page lapse. */ export async function cancelOrder( db: D1Database, - input: OrderChange, + input: OrderChange & { readonly reason?: CancelReason }, ): Promise { - await move(db, input, 'cancelled'); + await move(db, input, 'cancelled', { ref: input.reason ?? 'seller' }); +} + +/** + * Cancels the order a Checkout session was for, once Stripe says the session + * has expired: nothing can be paid through it any more. + * + * Only while the order is still waiting for that session. An order paid + * meanwhile is not touched, and nor is one recorded against another session. + * One with no session on record is cancelled too: a session naming it was + * opened, and only the write that would have recorded it failed. + * + * Returns what it found rather than throwing, because each answer is a + * normal one for a webhook to receive: Stripe also reports a session that + * expired after its order was cancelled by hand. + */ +export async function expireOrder( + db: D1Database, + input: OrderChange & { readonly sessionId: string }, +): Promise<'cancelled' | 'not_pending' | 'other_session'> { + const { orderId } = input; + const row = await db + .prepare('SELECT status, stripe_session_id FROM p_shop_order WHERE id = ?') + .bind(orderId) + .first<{ status: string; stripe_session_id: string | null }>(); + if (row === null) { + throw new OrderNotFoundError(orderId); + } + if (row.status !== 'pending') { + return 'not_pending'; + } + if ( + row.stripe_session_id !== null && + row.stripe_session_id !== input.sessionId + ) { + return 'other_session'; + } + try { + await move(db, input, 'cancelled', { + ref: 'expired', + from: 'pending', + andIf: { + sql: `(SELECT stripe_session_id IS NULL OR stripe_session_id = ? + FROM p_shop_order WHERE id = ?)`, + binds: [input.sessionId, orderId], + }, + }); + return 'cancelled'; + } catch (error) { + if (!(error instanceof OrderChangedError)) { + throw error; + } + // Paid, or given a session, between the reading and the write. + const now = await db + .prepare('SELECT status FROM p_shop_order WHERE id = ?') + .bind(orderId) + .first<{ status: string }>(); + if (now !== null && now.status !== 'pending') { + return 'not_pending'; + } + if (now !== null) { + return 'other_session'; + } + throw error; + } } function restockedVariants( @@ -119,8 +242,9 @@ function restockedVariants( } /** - * Records a refund: the order moves to `refunded` and the stock it took goes - * back, in one batch. + * Records a refund: the order moves to `refunded` and, unless the caller + * says the goods are not coming back, the stock it took goes back — in one + * batch. * * The stock returned is what the ledger says the payment took, not what the * order asked for. An oversold order took nothing, so it gets nothing back; @@ -135,12 +259,22 @@ function restockedVariants( */ export async function refundOrder( db: D1Database, - input: OrderChange, + input: OrderChange & { + /** + * Whether what the payment took goes back to stock: yes when the goods + * never left or have come back, no when they stay with the buyer. Yes + * unless the caller says otherwise. + */ + readonly restock?: boolean; + }, ): Promise<{ availabilityChanged: readonly string[] }> { const { orderId } = input; const nowIso = input.now.toISOString(); const from = await statusOf(db, orderId); assertTransition(from, 'refunded'); + // Bound into the two stock statements: with 0 they match no row, and the + // refund is recorded with the stock left as it is. + const restock = input.restock === false ? 0 : 1; const results = await db.batch>([ restockedVariants(db, orderId), @@ -159,9 +293,10 @@ export async function refundOrder( SELECT variant_id FROM p_shop_stock_adjustment WHERE ref_id = ? AND reason = 'order_paid' ) + AND ? = 1 AND ${ORDER_STILL_IN_STATUS}`, ) - .bind(orderId, nowIso, orderId, orderId, from), + .bind(orderId, nowIso, orderId, restock, orderId, from), // As with a payment, the row's id is built from what it records: a // second refund of the same order cannot be written. db @@ -172,9 +307,10 @@ export async function refundOrder( -a.delta, 'refund', a.ref_id, ? FROM p_shop_stock_adjustment AS a WHERE a.ref_id = ? AND a.reason = 'order_paid' + AND ? = 1 AND ${ORDER_STILL_IN_STATUS}`, ) - .bind(nowIso, orderId, orderId, from), + .bind(nowIso, orderId, restock, orderId, from), orderChangedOutbox(db, { orderId, from, to: 'refunded', now: input.now }), // Last: every statement above tests the status this one changes. db @@ -197,3 +333,94 @@ export async function refundOrder( ), }; } + +function orderedVariants(db: D1Database, orderId: string): D1PreparedStatement { + return db + .prepare( + `SELECT v.id, v.product_group, v.stock, v.moq, v.stock_policy + FROM p_shop_variant AS v + WHERE v.id IN ( + SELECT variant_id FROM p_shop_order_line WHERE order_id = ? + ) + ORDER BY v.id`, + ) + .bind(orderId); +} + +/** + * Fulfils an order that was paid for after its stock had gone, once a + * person has restocked it: the stock is taken now, as the payment would have + * taken it, and the order becomes `paid`, to ship like any other. + * + * One batch, conditional on the order still being oversold. A line whose + * stock is still short trips the stock's `CHECK` and takes the whole batch + * with it: nothing is taken, the order stays oversold, and this throws. + * + * Returns the products whose availability the stock it took changed. + */ +export async function fulfilOversold( + db: D1Database, + input: OrderChange, +): Promise<{ availabilityChanged: readonly string[] }> { + const { orderId } = input; + const nowIso = input.now.toISOString(); + const from = await statusOf(db, orderId); + if (from !== 'oversold') { + // `paid` is reached from `pending` too, by a payment. This is not one. + throw new Error(`Illegal order transition: ${from} → paid`); + } + assertTransition(from, 'paid'); + + const results = await db.batch>([ + orderedVariants(db, orderId), + db + .prepare( + `UPDATE p_shop_variant + SET stock = stock - ( + SELECT l.quantity FROM p_shop_order_line AS l + WHERE l.order_id = ? AND l.variant_id = p_shop_variant.id + ), + updated_at = ? + WHERE stock_policy = 'track' + AND id IN ( + SELECT variant_id FROM p_shop_order_line WHERE order_id = ? + ) + AND ${ORDER_STILL_IN_STATUS}`, + ) + .bind(orderId, nowIso, orderId, orderId, from), + // The same ledger row a payment writes: an oversold order never wrote + // one, and a refund afterwards gives back what it records. + db + .prepare( + `INSERT INTO p_shop_stock_adjustment + (id, variant_id, delta, reason, ref_id, created_at) + SELECT 'order_paid:' || l.order_id || ':' || l.variant_id, + l.variant_id, -l.quantity, 'order_paid', l.order_id, ? + FROM p_shop_order_line AS l + JOIN p_shop_variant AS v ON v.id = l.variant_id + WHERE l.order_id = ? AND v.stock_policy = 'track' + AND ${ORDER_STILL_IN_STATUS}`, + ) + .bind(nowIso, orderId, orderId, from), + orderChangedOutbox(db, { orderId, from, to: 'paid', now: input.now }), + // Last: every statement above tests the status this one changes. + db + .prepare( + `UPDATE p_shop_order SET status = 'paid', updated_at = ? + WHERE id = ? AND status = ? + RETURNING id`, + ) + .bind(nowIso, orderId, from), + orderedVariants(db, orderId), + ]); + + if ((results[4]?.results ?? []).length === 0) { + throw changedUnderneath(orderId); + } + return { + availabilityChanged: changedProductGroups( + (results[0]?.results ?? []) as unknown as StockRow[], + (results[5]?.results ?? []) as unknown as StockRow[], + ), + }; +} diff --git a/src/plugins/shop/lib/order-state.ts b/src/plugins/shop/lib/order-state.ts index a8fd58a..e86b1ee 100644 --- a/src/plugins/shop/lib/order-state.ts +++ b/src/plugins/shop/lib/order-state.ts @@ -6,8 +6,11 @@ * reconciliation and fulfilment incidents — shipping before payment clears, or * marking a refunded order as delivered. * - * `oversold` means payment succeeded but the stock had already been sold. Such - * an order can only be refunded or cancelled by hand. It must never ship. + * `oversold` means payment succeeded but the stock had already been sold. It + * must never ship as it is. A person either refunds it, or restocks and + * fulfils it, which takes the stock then and makes it `paid`. It is never + * just cancelled: that would leave a payment taken and nobody owing a refund + * of it (design §20). */ export const ORDER_STATUSES = [ @@ -27,7 +30,7 @@ const TRANSITIONS: Readonly> = { paid: ['shipped', 'refunded'], shipped: ['delivered', 'refunded'], delivered: ['refunded'], - oversold: ['refunded', 'cancelled'], + oversold: ['refunded', 'paid'], cancelled: [], refunded: [], }; diff --git a/src/plugins/shop/lib/orders.ts b/src/plugins/shop/lib/orders.ts index 353451f..39e3685 100644 --- a/src/plugins/shop/lib/orders.ts +++ b/src/plugins/shop/lib/orders.ts @@ -63,17 +63,27 @@ type SuccessfulCart = Extract; /** The Stripe event that confirms a payment. */ export const PAYMENT_EVENT_TYPE = 'payment_intent.succeeded'; -/** What an order's number begins with. */ -const ORDER_NO_PREFIX = 'ND'; +/** What an order's number begins with, unless a shop sets its own. */ +export const DEFAULT_ORDER_NO_PREFIX = 'ND'; + +/** A prefix a shop may set: up to six capitals or digits. */ +export function orderNoPrefixOf(setting: unknown): string { + return typeof setting === 'string' && /^[A-Z0-9]{1,6}$/.test(setting) + ? setting + : DEFAULT_ORDER_NO_PREFIX; +} /** * The number a buyer sees: the date and a random suffix, so it says nothing * about how many orders the shop takes. */ -function newOrderNo(now: Date): string { - return newReference(ORDER_NO_PREFIX, now); +function newOrderNo(now: Date, prefix: string): string { + return newReference(prefix, now); } +/** none: no tax is charged. stripe: Stripe calculates it at checkout. */ +export type TaxMode = 'none' | 'stripe'; + /** * Places an order that is waiting for payment. * @@ -94,6 +104,15 @@ export async function createPendingOrder( readonly shippingMinor?: number; readonly taxMinor?: number; readonly now: Date; + /** What checkout records beside the address. */ + readonly cartId?: string | null; + readonly company?: string; + readonly taxId?: string; + readonly shippingZone?: string; + readonly taxMode?: TaxMode; + /** The digest of the secret in the buyer's link to their order. */ + readonly accessHash?: string | null; + readonly orderNoPrefix?: string; }, ): Promise<{ id: string; orderNo: string; totalMinor: number }> { const { cart } = input; @@ -117,7 +136,10 @@ export async function createPendingOrder( } const id = crypto.randomUUID(); - const orderNo = newOrderNo(input.now); + const orderNo = newOrderNo( + input.now, + orderNoPrefixOf(input.orderNoPrefix ?? DEFAULT_ORDER_NO_PREFIX), + ); const shippingMinor = input.shippingMinor ?? 0; const taxMinor = input.taxMinor ?? 0; // Added up from the lines being written, so an order's subtotal can never @@ -134,8 +156,9 @@ export async function createPendingOrder( `INSERT INTO p_shop_order (id, order_no, status, currency, subtotal_minor, shipping_minor, tax_minor, total_minor, email, shipping_address, locale, + cart_id, company, tax_id, shipping_zone, tax_mode, access_hash, created_at, updated_at) - VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .bind( id, @@ -148,6 +171,12 @@ export async function createPendingOrder( input.email, JSON.stringify(input.shippingAddress), input.locale, + input.cartId ?? null, + input.company ?? '', + input.taxId ?? '', + input.shippingZone ?? '', + input.taxMode ?? 'none', + input.accessHash ?? null, nowIso, nowIso, ), @@ -202,7 +231,15 @@ export interface OrderDetail { readonly shippingAddress: Partial; readonly locale: string; readonly trackingNo: string | null; + readonly carrier: string | null; + readonly company: string; + readonly taxId: string; + readonly shippingZone: string; + readonly taxMode: TaxMode; + /** The cart the order was placed from; null for one placed otherwise. */ + readonly cartId: string | null; readonly stripePaymentIntentId: string | null; + readonly stripeSessionId: string | null; readonly createdAt: string; readonly updatedAt: string; readonly lines: readonly OrderLine[]; @@ -226,7 +263,14 @@ interface OrderRow { shipping_address: string; locale: string; tracking_no: string | null; + carrier: string | null; + company: string; + tax_id: string; + shipping_zone: string; + tax_mode: string; + cart_id: string | null; stripe_payment_intent_id: string | null; + stripe_session_id: string | null; created_at: string; updated_at: string; } @@ -274,7 +318,9 @@ export async function getOrder( .prepare( `SELECT id, order_no, status, currency, subtotal_minor, shipping_minor, tax_minor, total_minor, email, shipping_address, locale, - tracking_no, stripe_payment_intent_id, created_at, updated_at + tracking_no, carrier, company, tax_id, shipping_zone, + tax_mode, cart_id, stripe_payment_intent_id, + stripe_session_id, created_at, updated_at FROM p_shop_order WHERE ${column} = ?`, ) .bind(key), @@ -323,7 +369,14 @@ export async function getOrder( shippingAddress: parseAddress(row.shipping_address), locale: row.locale, trackingNo: row.tracking_no, + carrier: row.carrier, + company: row.company, + taxId: row.tax_id, + shippingZone: row.shipping_zone, + taxMode: row.tax_mode === 'stripe' ? 'stripe' : 'none', + cartId: row.cart_id, stripePaymentIntentId: row.stripe_payment_intent_id, + stripeSessionId: row.stripe_session_id, createdAt: row.created_at, updatedAt: row.updated_at, lines: ((lineResult?.results ?? []) as LineRow[]).map((line) => ({ @@ -344,6 +397,40 @@ export async function getOrder( }; } +/** + * Records the Checkout session an order was sent to pay through, and when + * it stops taking payment. Only on an order still waiting for its payment: + * a webhook that got there first has the last word. + * + * Returns false when the order had moved on, with nothing written. + */ +export async function recordCheckoutSession( + db: D1Database, + input: { + readonly orderId: string; + readonly sessionId: string; + readonly expiresAt: Date; + readonly now: Date; + }, +): Promise { + const row = await db + .prepare( + `UPDATE p_shop_order + SET stripe_session_id = ?, stripe_session_expires_at = ?, + updated_at = ? + WHERE id = ? AND status = 'pending' + RETURNING id`, + ) + .bind( + input.sessionId, + input.expiresAt.toISOString(), + input.now.toISOString(), + input.orderId, + ) + .first<{ id: string }>(); + return row !== null; +} + /** * What a call to `markOrderPaid` did. * @@ -375,10 +462,24 @@ interface PaymentInput { readonly eventId: string; readonly paymentIntentId: string; readonly now: Date; + /** + * What the payment came to, as Stripe reports it: whole minor units, and + * the currency in Stripe's lower case. When given, a payment that does not + * fit the order is refused rather than paid (`amountFits`). + */ + readonly amountMinor?: number; + readonly currency?: string; } interface PaymentState { - readonly order: { readonly status: OrderStatus } | null; + readonly order: { + readonly status: OrderStatus; + readonly currency: string; + readonly subtotalMinor: number; + readonly shippingMinor: number; + readonly totalMinor: number; + readonly taxMode: TaxMode; + } | null; /** * This payment is on record already: the same event, or another event of * the same type about the same payment intent. @@ -414,21 +515,79 @@ async function readPaymentState( ) .bind(input.eventId, PAYMENT_EVENT_TYPE, input.paymentIntentId), db - .prepare('SELECT status FROM p_shop_order WHERE id = ?') + .prepare( + `SELECT status, currency, subtotal_minor, shipping_minor, total_minor, + tax_mode + FROM p_shop_order WHERE id = ?`, + ) .bind(input.orderId), db.prepare(`SELECT ${ORDER_SHORT_OF_STOCK} AS short`).bind(input.orderId), ]); const order = (orderResult?.results ?? [])[0] as - | { status: string } + | { + status: string; + currency: string; + subtotal_minor: number; + shipping_minor: number; + total_minor: number; + tax_mode: string; + } | undefined; return { - order: order === undefined ? null : { status: order.status as OrderStatus }, + order: + order === undefined + ? null + : { + status: order.status as OrderStatus, + currency: order.currency, + subtotalMinor: order.subtotal_minor, + shippingMinor: order.shipping_minor, + totalMinor: order.total_minor, + taxMode: order.tax_mode === 'stripe' ? 'stripe' : 'none', + }, seen: (seenResult?.results ?? []).length > 0, shortOfStock: (shortResult?.results ?? [])[0]?.short === 1, }; } +/** + * Whether a payment fits the order it names: the same currency, and the + * amount the order comes to. With Stripe calculating tax the order does not + * know its tax until it is paid, so the payment has to come to at least the + * goods and the shipping, and what it comes to beyond them is the tax. + * + * A payment that does not fit is not taken for the order: it is recorded as + * refused, for a person to look at and refund. Checkout sets every amount + * from the server and Stripe's own conversion is switched off, so a + * mismatch is never a buyer's doing — it is a fault, and the order must not + * be marked paid on the strength of it. + */ +export function amountFits( + order: NonNullable, + payment: { readonly amountMinor?: number; readonly currency?: string }, +): boolean { + if (payment.amountMinor === undefined || payment.currency === undefined) { + return true; + } + if (payment.currency.toUpperCase() !== order.currency) { + return false; + } + return order.taxMode === 'stripe' + ? payment.amountMinor >= order.subtotalMinor + order.shippingMinor + : payment.amountMinor === order.totalMinor; +} + +/** The tax a payment carries, when Stripe calculated it; null otherwise. */ +function paidTaxMinor( + order: NonNullable, + payment: { readonly amountMinor?: number }, +): number | null { + return order.taxMode === 'stripe' && payment.amountMinor !== undefined + ? payment.amountMinor - order.subtotalMinor - order.shippingMinor + : null; +} + function variantsOfOrder(db: D1Database, orderId: string): D1PreparedStatement { return db .prepare( @@ -479,6 +638,8 @@ async function writePaid( db: D1Database, input: PaymentInput, from: OrderStatus, + /** The tax the payment carries, to be the order's; null to leave it. */ + taxMinor: number | null = null, ): Promise { const { orderId } = input; const nowIso = input.now.toISOString(); @@ -530,11 +691,14 @@ async function writePaid( db .prepare( `UPDATE p_shop_order - SET status = 'paid', stripe_payment_intent_id = ?, updated_at = ? + SET status = 'paid', stripe_payment_intent_id = ?, updated_at = ?, + tax_minor = COALESCE(?, tax_minor), + total_minor = COALESCE(? + subtotal_minor + shipping_minor, + total_minor) WHERE id = ? AND status = ? RETURNING id`, ) - .bind(input.paymentIntentId, nowIso, orderId, from), + .bind(input.paymentIntentId, nowIso, taxMinor, taxMinor, orderId, from), variantsOfOrder(db, orderId), ]); @@ -682,11 +846,12 @@ export async function markOrderPaid( return { outcome: 'duplicate', status: from, availabilityChanged: [] }; } - const action: PaymentAction = !canTransition(from, 'paid') - ? 'refuse' - : state.shortOfStock - ? 'oversold' - : 'pay'; + const action: PaymentAction = + !canTransition(from, 'paid') || !amountFits(state.order, input) + ? 'refuse' + : state.shortOfStock + ? 'oversold' + : 'pay'; // Thrown twice running by the same write: a real failure, to be retried // by whoever delivered the event. if (failed?.action === action && failed.times >= 2) { @@ -695,7 +860,12 @@ export async function markOrderPaid( try { if (action === 'pay') { - const paid = await writePaid(db, input, from); + const paid = await writePaid( + db, + input, + from, + paidTaxMinor(state.order, input), + ); if (paid !== null) { return paid; } diff --git a/src/plugins/shop/lib/outbox.ts b/src/plugins/shop/lib/outbox.ts index 09bd20a..de56fe8 100644 --- a/src/plugins/shop/lib/outbox.ts +++ b/src/plugins/shop/lib/outbox.ts @@ -72,6 +72,8 @@ export function orderChangedOutbox( readonly now: Date; /** Something else that must also hold for the change to be made. */ readonly andIf?: SqlCondition; + /** What the change needs said about it: why an order was cancelled. */ + readonly ref?: string | null; }, ): D1PreparedStatement { const topic: OutboxTopic = `order.${input.to}`; @@ -81,7 +83,7 @@ export function orderChangedOutbox( id: `${topic}:${input.orderId}`, topic, orderId: input.orderId, - ref: null, + ref: input.ref ?? null, now: input.now, }, { diff --git a/src/plugins/shop/lib/stripe-webhook.ts b/src/plugins/shop/lib/stripe-webhook.ts index 08a5d6b..12e3ee8 100644 --- a/src/plugins/shop/lib/stripe-webhook.ts +++ b/src/plugins/shop/lib/stripe-webhook.ts @@ -23,9 +23,16 @@ * wrote. A route drains the order's outbox after any outcome that names an * order, `duplicate` included: a duplicate is what a redelivery looks like * after a first attempt that paid the order and then died. + * + * Two event types are acted on. `payment_intent.succeeded` pays an order; + * checkout only offers payment methods that settle at once, so it is the + * only word on a payment there is. `checkout.session.expired` cancels the + * order a lapsed payment page was for, which is what stops a pending order + * from holding its prices for ever. */ import { z } from 'zod'; +import { expireOrder } from './order-fulfilment.js'; import type { OrderStatus } from './order-state.js'; import { markOrderPaid, @@ -72,6 +79,12 @@ export type WebhookOutcome = readonly orderId: string; readonly orderStatus: OrderStatus; } + /** The order's payment page lapsed unpaid, and the order is cancelled. */ + | { + readonly status: 200; + readonly kind: 'expired'; + readonly orderId: string; + } /** This payment had been dealt with before. */ | { readonly status: 200; @@ -96,11 +109,26 @@ const paymentSchema = z.object({ data: z.object({ object: z.object({ id: z.string().min(1).max(255), + // "Amount that this PaymentIntent collects", in minor units, and its + // currency in lower case: what the order is held to (`amountFits`). + amount_received: z.number().int().nonnegative(), + currency: z.string().regex(/^[a-z]{3}$/), metadata: z.record(z.string(), z.string()).nullish(), }), }), }); +const sessionSchema = z.object({ + data: z.object({ + object: z.object({ + id: z.string().min(1).max(255), + metadata: z.record(z.string(), z.string()).nullish(), + }), + }), +}); + +export const CHECKOUT_EXPIRED_EVENT = 'checkout.session.expired'; + const MALFORMED: WebhookOutcome = { status: 400, kind: 'rejected', @@ -139,6 +167,9 @@ export async function handleStripeWebhook( return MALFORMED; } + if (envelope.data.type === CHECKOUT_EXPIRED_EVENT) { + return sessionExpired(db, json, input.now); + } if (envelope.data.type !== PAYMENT_EVENT_TYPE) { return { status: 200, kind: 'ignored', reason: 'Event type not handled' }; } @@ -167,6 +198,8 @@ export async function handleStripeWebhook( orderId, eventId: envelope.data.id, paymentIntentId: payment.data.data.object.id, + amountMinor: payment.data.data.object.amount_received, + currency: payment.data.data.object.currency, now: input.now, }); @@ -211,3 +244,54 @@ export async function handleStripeWebhook( }; } } + +/** + * A Checkout session lapsed. Its order is cancelled when it is still waiting + * for that session's payment; anything else about it is left alone, and the + * delivery is answered 200 — a retry would find the same. + */ +async function sessionExpired( + db: D1Database, + json: unknown, + now: Date, +): Promise { + const session = sessionSchema.safeParse(json); + if (!session.success) { + return MALFORMED; + } + const orderId = session.data.data.object.metadata?.order_id ?? ''; + if (orderId === '') { + return { + status: 200, + kind: 'ignored', + reason: 'Session carries no order id', + }; + } + try { + const result = await expireOrder(db, { + orderId, + sessionId: session.data.data.object.id, + now, + }); + return result === 'cancelled' + ? { status: 200, kind: 'expired', orderId } + : { + status: 200, + kind: 'ignored', + reason: + result === 'not_pending' + ? 'Order is no longer waiting for payment' + : 'Order is waiting for another session', + }; + } catch (error) { + if (error instanceof OrderNotFoundError) { + return { status: 200, kind: 'unmatched', orderId }; + } + return { + status: 500, + kind: 'failed', + orderId, + reason: error instanceof Error ? error.message : String(error), + }; + } +} diff --git a/test/shop/order-fulfilment.test.ts b/test/shop/order-fulfilment.test.ts index b6d7056..a01655c 100644 --- a/test/shop/order-fulfilment.test.ts +++ b/test/shop/order-fulfilment.test.ts @@ -3,6 +3,8 @@ import type { CartLine } from '../../src/plugins/shop/lib/cart.js'; import { priceCart } from '../../src/plugins/shop/lib/cart-pricing.js'; import { cancelOrder, + expireOrder, + fulfilOversold, markDelivered, refundOrder, shipOrder, @@ -12,6 +14,7 @@ import { getOrder, markOrderPaid, OrderNotFoundError, + recordCheckoutSession, } from '../../src/plugins/shop/lib/orders.js'; import { atTheSameMoment, @@ -78,6 +81,22 @@ async function statusOf(orderId: string): Promise { return (await getOrder(db(), { id: orderId }))?.status; } +/** An order paid for after its stock had gone: stock 0, then the payment. */ +async function oversoldOrder(): Promise<{ id: string; orderNo: string }> { + const order = await makeOrder(); + await setStock('dn50', 0); + await markOrderPaid(db(), { + orderId: order.id, + eventId: `evt_${order.id}`, + paymentIntentId: `pi_${order.id}`, + now: NOW, + }); + if ((await statusOf(order.id)) !== 'oversold') { + throw new Error('The fixture order was not oversold'); + } + return order; +} + async function reasons(orderId: string): Promise { const { results } = await db() .prepare( @@ -150,6 +169,28 @@ describe('shipOrder', () => { expect(detail?.updatedAt).toBe(LATER.toISOString()); }); + it('records the carrier when one is named, and none when it is blank', async () => { + const named = await paidOrder(); + await shipOrder(db(), { + orderId: named.id, + trackingNo: 'T-1', + carrier: ' DHL Express ', + now: LATER, + }); + const blank = await paidOrder(); + await shipOrder(db(), { + orderId: blank.id, + trackingNo: 'T-2', + carrier: ' ', + now: LATER, + }); + + expect((await getOrder(db(), { id: named.id }))?.carrier).toBe( + 'DHL Express', + ); + expect((await getOrder(db(), { id: blank.id }))?.carrier).toBeNull(); + }); + it('owes the buyer a shipping notice from the moment the order ships', async () => { // Written in the same batch as the change: a notice sent afterwards // would be lost whenever the request died in between. @@ -265,6 +306,35 @@ describe('cancelOrder', () => { expect(await statusOf(order.id)).toBe('cancelled'); }); + it('says on what it owes why the order was cancelled', async () => { + // What follows reads it: a buyer is told when the seller cancelled, and + // not when they let the payment page lapse. + const bySeller = await makeOrder(); + const lapsed = await makeOrder(); + + await cancelOrder(db(), { orderId: bySeller.id, now: LATER }); + await cancelOrder(db(), { + orderId: lapsed.id, + reason: 'expired', + now: LATER, + }); + + const refs = (await outboxRows()).map((row) => [row.order_id, row.ref]); + expect(refs).toEqual([ + [bySeller.id, 'seller'], + [lapsed.id, 'expired'], + ]); + }); + + it('refuses to cancel an oversold order — its payment has to go back', async () => { + const order = await oversoldOrder(); + + await expect( + cancelOrder(db(), { orderId: order.id, now: LATER }), + ).rejects.toThrow(/transition/i); + expect(await statusOf(order.id)).toBe('oversold'); + }); + it('refuses to cancel a paid order — that is a refund', async () => { const order = await paidOrder(); @@ -288,6 +358,99 @@ describe('cancelOrder', () => { }); }); +describe('expireOrder', () => { + async function withSession(sessionId: string): Promise<{ id: string }> { + const order = await makeOrder(); + await recordCheckoutSession(db(), { + orderId: order.id, + sessionId, + expiresAt: LATER, + now: NOW, + }); + return order; + } + + it('cancels an order still waiting for the session that lapsed', async () => { + const order = await withSession('cs_1'); + + expect( + await expireOrder(db(), { + orderId: order.id, + sessionId: 'cs_1', + now: LATER, + }), + ).toBe('cancelled'); + expect(await statusOf(order.id)).toBe('cancelled'); + }); + + it('leaves the order alone when it is given another session meanwhile', async () => { + // Between the reading and the write: the write has to ask again. + const order = await withSession('cs_1'); + const database = interceptBatches({ + before: async () => { + await db() + .prepare( + "UPDATE p_shop_order SET stripe_session_id = 'cs_2' WHERE id = ?", + ) + .bind(order.id) + .run(); + }, + }); + + expect( + await expireOrder(database, { + orderId: order.id, + sessionId: 'cs_1', + now: LATER, + }), + ).toBe('other_session'); + expect(await statusOf(order.id)).toBe('pending'); + expect(await owed(order.id)).toEqual([]); + }); + + it('leaves the order alone when it is paid meanwhile', async () => { + const order = await withSession('cs_1'); + const database = interceptBatches({ + before: async () => { + await markOrderPaid(db(), { + orderId: order.id, + eventId: 'evt_meanwhile', + paymentIntentId: 'pi_meanwhile', + now: NOW, + }); + }, + }); + + expect( + await expireOrder(database, { + orderId: order.id, + sessionId: 'cs_1', + now: LATER, + }), + ).toBe('not_pending'); + expect(await statusOf(order.id)).toBe('paid'); + expect(await owed(order.id)).toEqual(['order.paid']); + }); + + it('passes on a failure that is not the order having changed', async () => { + const order = await withSession('cs_1'); + const database = interceptBatches({ + before: () => { + throw new Error('D1 is unreachable'); + }, + }); + + await expect( + expireOrder(database, { + orderId: order.id, + sessionId: 'cs_1', + now: LATER, + }), + ).rejects.toThrow('D1 is unreachable'); + expect(await statusOf(order.id)).toBe('pending'); + }); +}); + describe('refundOrder', () => { it('returns the stock that was taken when the order was paid', async () => { const order = await paidOrder(); @@ -333,6 +496,23 @@ describe('refundOrder', () => { expect(await reasons(order.id)).toEqual([]); }); + it('leaves the stock alone when the goods are not coming back', async () => { + const order = await paidOrder(); + await shipOrder(db(), { orderId: order.id, trackingNo: 'T-1', now: NOW }); + + await refundOrder(db(), { orderId: order.id, restock: false, now: LATER }); + + expect(await statusOf(order.id)).toBe('refunded'); + expect(await stockOf('dn50')).toBe(90); + // The ledger has nothing to undo: the stock went with the goods. + expect(await reasons(order.id)).toEqual(['order_paid']); + expect(await owed(order.id)).toEqual([ + 'order.paid', + 'order.shipped', + 'order.refunded', + ]); + }); + it('refuses to refund an order that was never paid', async () => { const order = await makeOrder(); @@ -448,3 +628,110 @@ describe('refundOrder', () => { expect(result.availabilityChanged).toEqual([]); }); }); + +describe('fulfilOversold', () => { + it('takes the stock once it is back and makes the order paid', async () => { + const order = await oversoldOrder(); + await setStock('dn50', 25); + + await fulfilOversold(db(), { orderId: order.id, now: LATER }); + + expect(await statusOf(order.id)).toBe('paid'); + expect(await stockOf('dn50')).toBe(15); + expect(await reasons(order.id)).toEqual(['order_paid']); + expect(await owed(order.id)).toEqual(['order.oversold', 'order.paid']); + }); + + it('then ships, and a refund gives back what it took', async () => { + const order = await oversoldOrder(); + await setStock('dn50', 25); + await fulfilOversold(db(), { orderId: order.id, now: LATER }); + + await shipOrder(db(), { orderId: order.id, trackingNo: 'T-1', now: LATER }); + await refundOrder(db(), { orderId: order.id, now: LATER }); + + expect(await stockOf('dn50')).toBe(25); + expect(await reasons(order.id)).toEqual(['order_paid', 'refund']); + }); + + it('takes nothing while the stock is still short, and leaves the order oversold', async () => { + const order = await oversoldOrder(); + await setStock('dn50', 9); + + await expect( + fulfilOversold(db(), { orderId: order.id, now: LATER }), + ).rejects.toThrow(); + + expect(await statusOf(order.id)).toBe('oversold'); + expect(await stockOf('dn50')).toBe(9); + expect(await reasons(order.id)).toEqual([]); + expect(await owed(order.id)).toEqual(['order.oversold']); + }); + + it('refuses an order that was not oversold', async () => { + const pending = await makeOrder(); + const paid = await paidOrder(); + + await expect( + fulfilOversold(db(), { orderId: pending.id, now: LATER }), + ).rejects.toThrow(/transition/i); + await expect( + fulfilOversold(db(), { orderId: paid.id, now: LATER }), + ).rejects.toThrow(/transition/i); + expect(await statusOf(pending.id)).toBe('pending'); + expect(await stockOf('dn50')).toBe(90); + }); + + it('takes the stock once when two people fulfil it at the same moment', async () => { + const order = await oversoldOrder(); + await setStock('dn50', 25); + + const outcome = await settle([ + (database) => fulfilOversold(database, { orderId: order.id, now: LATER }), + (database) => fulfilOversold(database, { orderId: order.id, now: LATER }), + ]); + + expect(outcome.fulfilled).toBe(1); + expect(await stockOf('dn50')).toBe(15); + expect(await reasons(order.id)).toEqual(['order_paid']); + expect(await owed(order.id)).toEqual(['order.oversold', 'order.paid']); + }); + + it('refunds or fulfils, never both, when the two happen at the same moment', async () => { + const order = await oversoldOrder(); + await setStock('dn50', 25); + + const outcome = await settle([ + (database) => fulfilOversold(database, { orderId: order.id, now: LATER }), + (database) => refundOrder(database, { orderId: order.id, now: LATER }), + ]); + + expect(outcome.fulfilled).toBe(1); + const status = await statusOf(order.id); + if (status === 'paid') { + expect(await stockOf('dn50')).toBe(15); + expect(await owed(order.id)).toEqual(['order.oversold', 'order.paid']); + } else { + expect(status).toBe('refunded'); + expect(await stockOf('dn50')).toBe(25); + expect(await reasons(order.id)).toEqual([]); + expect(await owed(order.id)).toEqual([ + 'order.oversold', + 'order.refunded', + ]); + } + }); + + it('reports the product whose availability the stock it took changed', async () => { + const order = await oversoldOrder(); + await setStock('dn50', 10); + + const result = await fulfilOversold(db(), { + orderId: order.id, + now: LATER, + }); + + expect(await stockOf('dn50')).toBe(0); + expect(result.availabilityChanged).toEqual([valve.translationGroup]); + }); +}); diff --git a/test/shop/order-state.test.ts b/test/shop/order-state.test.ts index f7e567a..0bc8f52 100644 --- a/test/shop/order-state.test.ts +++ b/test/shop/order-state.test.ts @@ -27,10 +27,12 @@ describe('canTransition', () => { it('routes an oversold order out of pending', () => { expect(canTransition('pending', 'oversold')).toBe(true); - // An oversold order can only be refunded or cancelled by hand; it must - // never pretend to be paid and ship. + // An oversold order is refunded, or restocked and so paid; it never + // ships as it is. Nor is it just cancelled: its payment was taken, and + // cancelling would leave nobody owing it back. expect(canTransition('oversold', 'refunded')).toBe(true); - expect(canTransition('oversold', 'cancelled')).toBe(true); + expect(canTransition('oversold', 'paid')).toBe(true); + expect(canTransition('oversold', 'cancelled')).toBe(false); expect(canTransition('oversold', 'shipped')).toBe(false); }); diff --git a/test/shop/orders.test.ts b/test/shop/orders.test.ts index 88ca197..8f50806 100644 --- a/test/shop/orders.test.ts +++ b/test/shop/orders.test.ts @@ -1006,6 +1006,131 @@ describe('markOrderPaid', () => { }); }); + it('pays when the payment comes to the order’s total, in its currency', async () => { + const order = await pendingOrder(); + + const result = await markOrderPaid(db(), { + orderId: order.id, + eventId: 'evt_1', + paymentIntentId: 'pi_1', + amountMinor: 99_000, + currency: 'usd', + now: LATER, + }); + + expect(result.outcome).toBe('paid'); + expect(await stockOf('dn50')).toBe(90); + }); + + it('refuses a payment that does not come to the order’s total', async () => { + // Checkout sets every amount from the server, so a mismatch is a fault, + // never a buyer's doing — and never a reason to ship. + const short = await pendingOrder(); + const foreign = await pendingOrder(); + + const shortResult = await markOrderPaid(db(), { + orderId: short.id, + eventId: 'evt_short', + paymentIntentId: 'pi_short', + amountMinor: 98_999, + currency: 'usd', + now: LATER, + }); + const foreignResult = await markOrderPaid(db(), { + orderId: foreign.id, + eventId: 'evt_foreign', + paymentIntentId: 'pi_foreign', + amountMinor: 99_000, + currency: 'eur', + now: LATER, + }); + + expect(shortResult.outcome).toBe('refused'); + expect(foreignResult.outcome).toBe('refused'); + expect((await orderRow(short.id)).status).toBe('pending'); + expect((await orderRow(foreign.id)).status).toBe('pending'); + expect(await stockOf('dn50')).toBe(100); + // The money was taken all the same: each is owed a refund. + expect( + (await outboxRows()) + .filter((row) => row.topic === 'payment.refused') + .map((row) => row.ref), + ).toEqual(['pi_short', 'pi_foreign']); + }); + + it('takes the tax Stripe calculated from the payment, and makes it the order’s', async () => { + const order = await createPendingOrder(db(), { + cart: await pricedCart(), + locale: 'en', + email: EMAIL, + shippingAddress: ADDRESS, + shippingMinor: 1500, + taxMode: 'stripe', + now: NOW, + }); + + const result = await markOrderPaid(db(), { + orderId: order.id, + eventId: 'evt_1', + paymentIntentId: 'pi_1', + amountMinor: 100_500 + 20_100, + currency: 'usd', + now: LATER, + }); + + expect(result.outcome).toBe('paid'); + const row = await orderRow(order.id); + expect(row.tax_minor).toBe(20_100); + expect(row.total_minor).toBe(120_600); + expect(row.subtotal_minor + row.shipping_minor + row.tax_minor).toBe( + row.total_minor, + ); + }); + + it('refuses a taxed payment that comes to less than the goods and the shipping', async () => { + const order = await createPendingOrder(db(), { + cart: await pricedCart(), + locale: 'en', + email: EMAIL, + shippingAddress: ADDRESS, + shippingMinor: 1500, + taxMode: 'stripe', + now: NOW, + }); + + const result = await markOrderPaid(db(), { + orderId: order.id, + eventId: 'evt_1', + paymentIntentId: 'pi_1', + amountMinor: 100_499, + currency: 'usd', + now: LATER, + }); + + expect(result.outcome).toBe('refused'); + const row = await orderRow(order.id); + expect(row.status).toBe('pending'); + expect(row.tax_minor).toBe(0); + expect(row.total_minor).toBe(100_500); + }); + + it('leaves the tax alone for an order that charges none', async () => { + const order = await pendingOrder(); + + await markOrderPaid(db(), { + orderId: order.id, + eventId: 'evt_1', + paymentIntentId: 'pi_1', + amountMinor: 99_000, + currency: 'USD', + now: LATER, + }); + + const row = await orderRow(order.id); + expect(row.tax_minor).toBe(0); + expect(row.total_minor).toBe(99_000); + }); + it('reports the product whose availability the payment changed', async () => { // 15 in stock with a minimum order of 10 is orderable; 5 is not. That is // the moment the product's pages have to be purged. diff --git a/test/shop/stripe-webhook.test.ts b/test/shop/stripe-webhook.test.ts index 011e8e6..4ccccef 100644 --- a/test/shop/stripe-webhook.test.ts +++ b/test/shop/stripe-webhook.test.ts @@ -1,6 +1,10 @@ import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { priceCart } from '../../src/plugins/shop/lib/cart-pricing.js'; -import { createPendingOrder } from '../../src/plugins/shop/lib/orders.js'; +import { cancelOrder } from '../../src/plugins/shop/lib/order-fulfilment.js'; +import { + createPendingOrder, + recordCheckoutSession, +} from '../../src/plugins/shop/lib/orders.js'; import { handleStripeWebhook } from '../../src/plugins/shop/lib/stripe-webhook.js'; import { clearShopTables, @@ -50,7 +54,12 @@ async function pendingOrder(): Promise<{ id: string; orderNo: string }> { /** The event Stripe sends when a payment succeeds, for one of our orders. */ function paymentSucceeded( orderId: string | null, - overrides: { eventId?: string; paymentIntentId?: string } = {}, + overrides: { + eventId?: string; + paymentIntentId?: string; + amount?: number; + currency?: string; + } = {}, ): unknown { return { id: overrides.eventId ?? 'evt_1', @@ -60,8 +69,30 @@ function paymentSucceeded( object: { id: overrides.paymentIntentId ?? 'pi_1', object: 'payment_intent', - amount: 99_000, - currency: 'usd', + amount: overrides.amount ?? 99_000, + amount_received: overrides.amount ?? 99_000, + currency: overrides.currency ?? 'usd', + metadata: orderId === null ? {} : { order_id: orderId }, + }, + }, + }; +} + +/** The event Stripe sends when a Checkout session lapses unpaid. */ +function sessionExpired( + orderId: string | null, + sessionId = 'cs_1', + eventId = 'evt_expired', +): unknown { + return { + id: eventId, + object: 'event', + type: 'checkout.session.expired', + data: { + object: { + id: sessionId, + object: 'checkout.session', + status: 'expired', metadata: orderId === null ? {} : { order_id: orderId }, }, }, @@ -430,4 +461,128 @@ describe('handleStripeWebhook', () => { const again = await deliver(JSON.stringify(paymentSucceeded(order.id))); expect(again.kind).toBe('paid'); }); + + it('refuses a payment that does not come to the order’s total, and puts it on record', async () => { + const order = await pendingOrder(); + + const outcome = await deliver( + JSON.stringify( + paymentSucceeded(order.id, { amount: 1000, paymentIntentId: 'pi_x' }), + ), + ); + + expect(outcome).toEqual({ + status: 200, + kind: 'refused', + orderId: order.id, + orderStatus: 'pending', + }); + expect(await statusOf(order.id)).toBe('pending'); + expect(await stockOf('dn50')).toBe(100); + expect((await outboxRows()).map((row) => [row.topic, row.ref])).toEqual([ + ['payment.refused', 'pi_x'], + ]); + }); + + it('refuses a payment event that does not say what was received', async () => { + // Without the amount the order cannot be held to it, and paying it + // regardless would be paying on trust. + const order = await pendingOrder(); + const event = paymentSucceeded(order.id) as { + data: { object: Record }; + }; + delete event.data.object.amount_received; + + const outcome = await deliver(JSON.stringify(event)); + + expect(outcome.status).toBe(400); + expect(await statusOf(order.id)).toBe('pending'); + }); + + it('cancels the order when its payment page lapses', async () => { + const order = await pendingOrder(); + await recordCheckoutSession(db(), { + orderId: order.id, + sessionId: 'cs_1', + expiresAt: NOW, + now: NOW, + }); + + const outcome = await deliver( + JSON.stringify(sessionExpired(order.id, 'cs_1')), + ); + + expect(outcome).toEqual({ + status: 200, + kind: 'expired', + orderId: order.id, + }); + expect(await statusOf(order.id)).toBe('cancelled'); + // Said to have lapsed: the buyer is not written to about it. + expect((await outboxRows()).map((row) => [row.topic, row.ref])).toEqual([ + ['order.cancelled', 'expired'], + ]); + }); + + it('cancels it too when the session was never recorded on the order', async () => { + const order = await pendingOrder(); + + const outcome = await deliver(JSON.stringify(sessionExpired(order.id))); + + expect(outcome.kind).toBe('expired'); + expect(await statusOf(order.id)).toBe('cancelled'); + }); + + it('leaves an order alone that is waiting for another session', async () => { + const order = await pendingOrder(); + await recordCheckoutSession(db(), { + orderId: order.id, + sessionId: 'cs_new', + expiresAt: NOW, + now: NOW, + }); + + const outcome = await deliver( + JSON.stringify(sessionExpired(order.id, 'cs_old')), + ); + + expect(outcome.status).toBe(200); + expect(outcome.kind).toBe('ignored'); + expect(await statusOf(order.id)).toBe('pending'); + expect(await outboxRows()).toEqual([]); + }); + + it('leaves an order alone that was paid or cancelled already', async () => { + const paid = await pendingOrder(); + await deliver(JSON.stringify(paymentSucceeded(paid.id))); + const cancelled = await pendingOrder(); + await cancelOrder(db(), { orderId: cancelled.id, now: NOW }); + + const first = await deliver( + JSON.stringify(sessionExpired(paid.id, 'cs_1', 'evt_e1')), + ); + const second = await deliver( + JSON.stringify(sessionExpired(cancelled.id, 'cs_2', 'evt_e2')), + ); + + expect([first.kind, second.kind]).toEqual(['ignored', 'ignored']); + expect(await statusOf(paid.id)).toBe('paid'); + expect(await statusOf(cancelled.id)).toBe('cancelled'); + expect((await outboxRows()).map((row) => row.ref)).toEqual([ + null, + 'seller', + ]); + }); + + it('answers 200 to a lapsed session that names no order, or one it does not have', async () => { + const none = await deliver(JSON.stringify(sessionExpired(null))); + const unknown = await deliver(JSON.stringify(sessionExpired('nope'))); + + expect(none).toMatchObject({ status: 200, kind: 'ignored' }); + expect(unknown).toEqual({ + status: 200, + kind: 'unmatched', + orderId: 'nope', + }); + }); }); From 296f6449bd76d7a0a4e74d35aff52ff99fd7235e Mon Sep 17 00:00:00 2001 From: JasonYv Date: Sat, 31 Oct 2026 22:39:05 +0800 Subject: [PATCH 03/26] feat: ask Stripe for what checkout needs, at a version this code was checked against A Checkout session now carries the order line by line at its own prices and shipping as one option named after its zone, lapses after an hour, offers only methods that settle at once, and has Stripe's own currency conversion switched off, so the buyer pays what the shop's page said. With Stripe calculating tax it is worked out from a customer holding the address the order ships to. A session can be expired before its order is cancelled. Every request names API version 2026-10-28.endive. --- src/plugins/shop/lib/stripe-client.ts | 269 ++++++++++++++++++++++-- test/shop/stripe-client.test.ts | 289 +++++++++++++++++++++++++- 2 files changed, 532 insertions(+), 26 deletions(-) diff --git a/src/plugins/shop/lib/stripe-client.ts b/src/plugins/shop/lib/stripe-client.ts index b223098..2861c41 100644 --- a/src/plugins/shop/lib/stripe-client.ts +++ b/src/plugins/shop/lib/stripe-client.ts @@ -1,15 +1,49 @@ /** - * The two Stripe calls the shop makes, over `fetch`, with no SDK. + * The Stripe calls the shop makes, over `fetch`, with no SDK. * - * Opening a hosted Checkout session and refunding a payment are the whole - * surface. Calling the REST API directly keeps a vendor SDK out of the Worker, + * Opening a hosted Checkout session, expiring one, refunding a payment, and — + * when Stripe calculates tax — creating the customer the tax is worked out + * from. Calling the REST API directly keeps a vendor SDK out of the Worker, * which matters twice over for code other people deploy as their own. + * + * Every request names the API version it was written against, so a Stripe + * account set to a newer default cannot change what a field means under it. */ import type { Currency } from './currency.js'; const API_BASE = 'https://api.stripe.com/v1'; +/** + * The version this file and the webhook were written and checked against + * (2026-10-31). The webhook endpoint a seller creates is to be set to the + * same one, so that the events it sends have the shape the webhook reads. + */ +export const STRIPE_API_VERSION = '2026-10-28.endive'; + +/** How long a Checkout session takes payment: one hour (design §20, D9). */ +export const CHECKOUT_LIFETIME_MS = 60 * 60 * 1000; + +/** + * The most Stripe can charge in one payment by every method checkout offers, + * in minor units: eight digits, the limit for payments that are not by card, + * which is the strictest that applies. + */ +export const MAX_CHARGE_MINOR = 99_999_999; + +/** The least Stripe charges, by currency, in minor units. */ +export const MIN_CHARGE_MINOR: Readonly> = { + USD: 50, + EUR: 50, + GBP: 30, +}; + +/** Checkout's limit on the lines of one session in payment mode. */ +export const MAX_CHECKOUT_LINES = 100; + +/** The languages a Checkout page is offered in that the shop also speaks. */ +const CHECKOUT_LOCALES = new Set(['en', 'de', 'fr', 'es']); + interface StripeErrorBody { readonly error?: { readonly type?: unknown; @@ -46,6 +80,21 @@ function describeFailure(payload: unknown, status: number): string { return `Stripe: ${[...parts, `status ${status}`].join(', ')}`; } +/** A request Stripe answered with an error. */ +export class StripeRequestError extends Error { + /** The HTTP status Stripe answered with; 0 when nothing came back. */ + readonly status: number; + /** Stripe's error code, when it gave one. */ + readonly code: string | null; + + constructor(payload: unknown, status: number) { + super(describeFailure(payload, status)); + this.name = 'StripeRequestError'; + this.status = status; + this.code = identifier((payload as StripeErrorBody | null)?.error?.code); + } +} + async function stripeRequest( secretKey: string, path: string, @@ -58,6 +107,7 @@ async function stripeRequest( headers: { Authorization: `Bearer ${secretKey}`, 'Content-Type': 'application/x-www-form-urlencoded', + 'Stripe-Version': STRIPE_API_VERSION, // What stops a retried request from charging, or refunding, twice. 'Idempotency-Key': idempotencyKey, }, @@ -69,7 +119,7 @@ async function stripeRequest( const payload: unknown = await response.json().catch(() => null); if (!response.ok || payload === null) { - throw new Error(describeFailure(payload, response.status)); + throw new StripeRequestError(payload, response.status); } return payload as T; @@ -81,58 +131,135 @@ export interface CheckoutSession { readonly url: string; } +/** One line of an order, as the buyer will see it on Stripe's page. */ +export interface CheckoutLine { + readonly name: string; + readonly sku: string; + readonly unitPriceMinor: number; + readonly quantity: number; +} + +/** A whole number of minor units Stripe can be asked for, or not. */ +function isAmount(value: number): boolean { + return Number.isInteger(value) && value >= 0; +} + /** * Opens a Stripe-hosted Checkout session for an order. * * The hosted page needs no client-side code, and card numbers never reach * this Worker. The cost is that the buyer leaves the site to pay. * - * The amount is the order's total as the server computed it — one line item, - * so nothing a client sent can take part in what is charged. + * Every amount is the order's, as the server stored it — each line at its + * snapshot price, and shipping as one fixed option named after its zone — + * so nothing a client sent takes part in what is charged, and Stripe's page + * shows what the order holds. Stripe's own currency conversion is switched + * off: the buyer pays what the shop's page said, in the shop's currency. + * + * Only payment methods that settle at once are offered (design §20, D3): + * cards, which take in Apple Pay and Google Pay, and Link. A method that + * settles days later would leave the stock to go meanwhile. * * The order id goes into `payment_intent_data.metadata` as well as the * session's own metadata. The webhook receives `payment_intent.succeeded`, - * and the intent's metadata is the only way it can find the order. + * and the intent's metadata is the only way it can find the order; the + * session's is how `checkout.session.expired` finds it. */ export async function createCheckoutSession( secretKey: string, input: { - readonly amountMinor: number; - readonly currency: Currency; readonly orderId: string; readonly orderNo: string; - readonly productName: string; + readonly currency: Currency; + readonly lines: readonly CheckoutLine[]; + readonly shipping: { readonly label: string; readonly amountMinor: number }; readonly successUrl: string; readonly cancelUrl: string; + /** The language of the page the buyer came from. */ + readonly locale: string; + readonly expiresAt: Date; + /** Prefills the address on Stripe's page. Not sent with a customer. */ readonly customerEmail?: string; + /** + * With Stripe calculating tax: the customer whose shipping address the + * tax is worked out from (`createTaxCustomer`). Absent, no tax. + */ + readonly taxCustomerId?: string; }, fetchImpl: typeof fetch = fetch, ): Promise { + const { lines } = input; + if (lines.length === 0 || lines.length > MAX_CHECKOUT_LINES) { + throw new Error( + `A Checkout session takes 1 to ${MAX_CHECKOUT_LINES} lines`, + ); + } + const goods = lines.reduce( + (sum, line) => sum + line.unitPriceMinor * line.quantity, + 0, + ); // Stripe is never asked to charge nothing. A session for a total of zero // creates no payment intent, so `payment_intent.succeeded` would never - // arrive and the order would wait for ever. An order that costs nothing is - // confirmed without Stripe, by whoever calls this. - if (!Number.isInteger(input.amountMinor) || input.amountMinor <= 0) { + // arrive and the order would wait for ever. + if ( + !lines.every( + (line) => + isAmount(line.unitPriceMinor) && + Number.isInteger(line.quantity) && + line.quantity > 0, + ) || + !isAmount(input.shipping.amountMinor) || + goods + input.shipping.amountMinor <= 0 + ) { throw new Error( 'A Checkout session needs a positive amount in whole minor units', ); } + const currency = input.currency.toLowerCase(); + const taxed = input.taxCustomerId !== undefined; const body: Record = { mode: 'payment', - 'line_items[0][quantity]': '1', - 'line_items[0][price_data][currency]': input.currency.toLowerCase(), - 'line_items[0][price_data][unit_amount]': String(input.amountMinor), - 'line_items[0][price_data][product_data][name]': input.productName, success_url: input.successUrl, cancel_url: input.cancelUrl, + expires_at: String(Math.floor(input.expiresAt.getTime() / 1000)), + locale: CHECKOUT_LOCALES.has(input.locale) ? input.locale : 'auto', + 'adaptive_pricing[enabled]': 'false', + 'allowed_payment_method_types[0]': 'card', + 'allowed_payment_method_types[1]': 'link', + client_reference_id: input.orderNo, 'metadata[order_id]': input.orderId, 'metadata[order_no]': input.orderNo, 'payment_intent_data[metadata][order_id]': input.orderId, 'payment_intent_data[metadata][order_no]': input.orderNo, + 'shipping_options[0][shipping_rate_data][type]': 'fixed_amount', + 'shipping_options[0][shipping_rate_data][display_name]': + input.shipping.label.slice(0, 100), + 'shipping_options[0][shipping_rate_data][fixed_amount][amount]': String( + input.shipping.amountMinor, + ), + 'shipping_options[0][shipping_rate_data][fixed_amount][currency]': currency, }; + lines.forEach((line, index) => { + const at = `line_items[${index}]`; + body[`${at}[quantity]`] = String(line.quantity); + body[`${at}[price_data][currency]`] = currency; + body[`${at}[price_data][unit_amount]`] = String(line.unitPriceMinor); + body[`${at}[price_data][product_data][name]`] = + `${line.name} (${line.sku})`; + if (taxed) { + // The shop's prices are without tax: Stripe adds it on top. + body[`${at}[price_data][tax_behavior]`] = 'exclusive'; + } + }); - if (input.customerEmail !== undefined) { + if (taxed) { + body['automatic_tax[enabled]'] = 'true'; + body.customer = input.taxCustomerId; + body['shipping_options[0][shipping_rate_data][tax_behavior]'] = 'exclusive'; + // Stripe's own code for shipping. + body['shipping_options[0][shipping_rate_data][tax_code]'] = 'txcd_92010001'; + } else if (input.customerEmail !== undefined) { body.customer_email = input.customerEmail; } @@ -146,6 +273,109 @@ export async function createCheckoutSession( ); } +/** Where an order goes, as Stripe's address fields name its parts. */ +export interface StripeAddress { + readonly recipient: string; + readonly line1: string; + readonly line2?: string; + readonly city: string; + readonly region?: string; + readonly postalCode: string; + readonly country: string; +} + +function addressFields( + prefix: string, + address: StripeAddress, +): Record { + const fields: Record = { + [`${prefix}[line1]`]: address.line1, + [`${prefix}[city]`]: address.city, + [`${prefix}[postal_code]`]: address.postalCode, + [`${prefix}[country]`]: address.country, + }; + if (address.line2 !== undefined && address.line2 !== '') { + fields[`${prefix}[line2]`] = address.line2; + } + if (address.region !== undefined && address.region !== '') { + fields[`${prefix}[state]`] = address.region; + } + return fields; +} + +/** + * Creates the Stripe customer an order's tax is calculated from, when the + * shop has Stripe calculate tax. + * + * Checkout works tax out from a customer's shipping address when it collects + * none itself. Giving it the address the buyer already entered here means + * the tax is for where the goods are going, and the buyer types it once. + * One customer per order, keyed on the order: the shop has no buyer + * accounts to attach one to. + */ +export async function createTaxCustomer( + secretKey: string, + input: { + readonly orderId: string; + readonly email: string; + readonly company: string; + readonly address: StripeAddress; + }, + fetchImpl: typeof fetch = fetch, +): Promise<{ readonly id: string }> { + return stripeRequest<{ id: string }>( + secretKey, + '/customers', + { + email: input.email, + name: input.company.slice(0, 256), + 'shipping[name]': input.address.recipient, + ...addressFields('shipping[address]', input.address), + // "Required if calculating taxes." + ...addressFields('address', input.address), + 'metadata[order_id]': input.orderId, + }, + `customer:${input.orderId}`, + fetchImpl, + ); +} + +/** + * Expires an open Checkout session, so that it can no longer be paid: done + * before an order is cancelled, never after. + * + * A session that is no longer open — paid, or expired already — is refused + * by Stripe; that is reported as `not_open` for the caller to look into the + * order, not thrown. + */ +export async function expireCheckoutSession( + secretKey: string, + sessionId: string, + fetchImpl: typeof fetch = fetch, +): Promise<'expired' | 'not_open'> { + try { + await stripeRequest( + secretKey, + `/checkout/sessions/${encodeURIComponent(sessionId)}/expire`, + {}, + `expire:${sessionId}`, + fetchImpl, + ); + return 'expired'; + } catch (error) { + if ( + error instanceof StripeRequestError && + error.status >= 400 && + error.status < 500 && + error.status !== 401 && + error.status !== 429 + ) { + return 'not_open'; + } + throw error; + } +} + export interface Refund { readonly id: string; readonly status: string; @@ -155,7 +385,8 @@ export interface Refund { export type RefundReason = 'duplicate' | 'fraudulent' | 'requested_by_customer'; /** - * Refunds a payment. No amount is sent, so the whole payment is refunded. + * Refunds a payment. No amount is sent, so the whole payment is refunded + * (design §20, D11). * * Keyed on the payment intent: asking twice, because the first answer was * lost on the way back, must not refund twice. diff --git a/test/shop/stripe-client.test.ts b/test/shop/stripe-client.test.ts index 0ecd7fa..f87e63c 100644 --- a/test/shop/stripe-client.test.ts +++ b/test/shop/stripe-client.test.ts @@ -2,6 +2,9 @@ import { describe, expect, it } from 'vitest'; import { createCheckoutSession, createRefund, + createTaxCustomer, + expireCheckoutSession, + STRIPE_API_VERSION, } from '../../src/plugins/shop/lib/stripe-client.js'; interface Captured { @@ -39,18 +42,35 @@ function headersOf(call: Captured): Record { return call.init.headers as Record; } +const EXPIRES = new Date('2026-10-31T09:00:00.000Z'); + const SESSION = { - amountMinor: 99_000, currency: 'USD' as const, orderId: 'order-1', orderNo: 'ND-261005-7K3M9QXA', - productName: 'Order ND-261005-7K3M9QXA', + lines: [ + { + name: 'Hex bolt M8', + sku: 'HB-M8', + unitPriceMinor: 990, + quantity: 100, + }, + { + name: 'Flange nut M8', + sku: 'FN-M8', + unitPriceMinor: 45, + quantity: 17, + }, + ], + shipping: { label: 'Europe', amountMinor: 2500 }, successUrl: 'https://shop.example/ok', cancelUrl: 'https://shop.example/cart', + locale: 'de', + expiresAt: EXPIRES, }; describe('createCheckoutSession', () => { - it('charges the server-computed total as a single line item', async () => { + it('charges each line at the order’s own price, and shipping as one option', async () => { const { impl, calls } = recordingFetch({ id: 'cs_1', url: 'https://checkout.stripe.com/c/pay/cs_1', @@ -63,15 +83,154 @@ describe('createCheckoutSession', () => { expect(call.url).toBe('https://api.stripe.com/v1/checkout/sessions'); expect(call.init.method).toBe('POST'); expect(body.get('mode')).toBe('payment'); - expect(body.get('line_items[0][price_data][unit_amount]')).toBe('99000'); + expect(body.get('line_items[0][price_data][unit_amount]')).toBe('990'); expect(body.get('line_items[0][price_data][currency]')).toBe('usd'); - expect(body.get('line_items[0][quantity]')).toBe('1'); + expect(body.get('line_items[0][price_data][product_data][name]')).toBe( + 'Hex bolt M8 (HB-M8)', + ); + expect(body.get('line_items[0][quantity]')).toBe('100'); + expect(body.get('line_items[1][price_data][unit_amount]')).toBe('45'); + expect(body.get('line_items[1][quantity]')).toBe('17'); + expect(body.has('line_items[2][quantity]')).toBe(false); + expect(body.get('shipping_options[0][shipping_rate_data][type]')).toBe( + 'fixed_amount', + ); + expect( + body.get('shipping_options[0][shipping_rate_data][display_name]'), + ).toBe('Europe'); + expect( + body.get('shipping_options[0][shipping_rate_data][fixed_amount][amount]'), + ).toBe('2500'); + expect( + body.get( + 'shipping_options[0][shipping_rate_data][fixed_amount][currency]', + ), + ).toBe('usd'); expect(session).toEqual({ id: 'cs_1', url: 'https://checkout.stripe.com/c/pay/cs_1', }); }); + it('charges in the shop’s currency, at once, and lapses when the order says', async () => { + const { impl, calls } = recordingFetch({ id: 'cs_1', url: 'https://x' }); + + await createCheckoutSession('sk_test_123', SESSION, impl); + + const body = bodyOf(only(calls)); + // Stripe's conversion would charge the buyer an amount the page never + // showed. + expect(body.get('adaptive_pricing[enabled]')).toBe('false'); + // Methods that settle at once only: a bank debit can take days, and the + // stock is taken when the payment is. + expect(body.getAll('allowed_payment_method_types[0]')).toEqual(['card']); + expect(body.getAll('allowed_payment_method_types[1]')).toEqual(['link']); + expect(body.has('allowed_payment_method_types[2]')).toBe(false); + expect(body.get('expires_at')).toBe( + String(Math.floor(EXPIRES.getTime() / 1000)), + ); + expect(body.get('locale')).toBe('de'); + expect(body.get('client_reference_id')).toBe(SESSION.orderNo); + expect(body.has('automatic_tax[enabled]')).toBe(false); + }); + + it('lets Stripe choose the page’s language for one the shop does not offer it in', async () => { + const { impl, calls } = recordingFetch({ id: 'cs_1', url: 'https://x' }); + + await createCheckoutSession( + 'sk_test_123', + { ...SESSION, locale: 'xx' }, + impl, + ); + + expect(bodyOf(only(calls)).get('locale')).toBe('auto'); + }); + + it('names the API version it was written against on every request', async () => { + const session = recordingFetch({ id: 'cs_1', url: 'https://x' }); + const refund = recordingFetch({ id: 're_1', status: 'succeeded' }); + const customer = recordingFetch({ id: 'cus_1' }); + const expire = recordingFetch({ id: 'cs_1', status: 'expired' }); + + await createCheckoutSession('sk_test_123', SESSION, session.impl); + await createRefund('sk_test_123', { paymentIntentId: 'pi_1' }, refund.impl); + await createTaxCustomer( + 'sk_test_123', + { + orderId: 'order-1', + email: 'buyer@example.com', + company: 'Acme GmbH', + address: { + recipient: 'Jane Buyer', + line1: 'Hafenstraße 1', + city: 'Hamburg', + postalCode: '20457', + country: 'DE', + }, + }, + customer.impl, + ); + await expireCheckoutSession('sk_test_123', 'cs_1', expire.impl); + + for (const calls of [ + session.calls, + refund.calls, + customer.calls, + expire.calls, + ]) { + expect(headersOf(only(calls))['Stripe-Version']).toBe(STRIPE_API_VERSION); + } + expect(STRIPE_API_VERSION).toBe('2026-10-28.endive'); + }); + + it('asks Stripe for tax on top of the prices only when given a customer to work it out from', async () => { + const { impl, calls } = recordingFetch({ id: 'cs_1', url: 'https://x' }); + + await createCheckoutSession( + 'sk_test_123', + { ...SESSION, taxCustomerId: 'cus_1', customerEmail: 'b@example.com' }, + impl, + ); + + const body = bodyOf(only(calls)); + expect(body.get('automatic_tax[enabled]')).toBe('true'); + expect(body.get('customer')).toBe('cus_1'); + // The customer carries the email; sending both is not asked of Stripe. + expect(body.has('customer_email')).toBe(false); + expect(body.get('line_items[0][price_data][tax_behavior]')).toBe( + 'exclusive', + ); + expect(body.get('line_items[1][price_data][tax_behavior]')).toBe( + 'exclusive', + ); + expect( + body.get('shipping_options[0][shipping_rate_data][tax_behavior]'), + ).toBe('exclusive'); + expect(body.get('shipping_options[0][shipping_rate_data][tax_code]')).toBe( + 'txcd_92010001', + ); + }); + + it('refuses more lines than Checkout takes, and none', async () => { + const { impl, calls } = recordingFetch({ id: 'cs_1', url: 'https://x' }); + const line = SESSION.lines[0]; + if (line === undefined) { + throw new Error('fixture'); + } + + await expect( + createCheckoutSession( + 'sk_test_123', + { ...SESSION, lines: Array.from({ length: 101 }, () => line) }, + impl, + ), + ).rejects.toThrow(/1 to 100 lines/); + await expect( + createCheckoutSession('sk_test_123', { ...SESSION, lines: [] }, impl), + ).rejects.toThrow(/1 to 100 lines/); + expect(calls).toHaveLength(0); + }); + it('puts the order id on the payment intent, which is what the webhook reads', async () => { const { impl, calls } = recordingFetch({ id: 'cs_1', url: 'https://x' }); @@ -180,11 +339,47 @@ describe('createCheckoutSession', () => { // that marks an order paid would never arrive. const { impl, calls } = recordingFetch({ id: 'cs_1', url: 'https://x' }); - for (const amountMinor of [0, -100, 99.5, Number.NaN]) { + const free = { + ...SESSION, + lines: [{ name: 'Sample', sku: 'S', unitPriceMinor: 0, quantity: 1 }], + shipping: { label: 'Europe', amountMinor: 0 }, + }; + await expect( + createCheckoutSession('sk_test_123', free, impl), + ).rejects.toThrow(/positive amount/); + for (const unitPriceMinor of [-100, 99.5, Number.NaN]) { + await expect( + createCheckoutSession( + 'sk_test_123', + { + ...SESSION, + lines: [{ name: 'Bolt', sku: 'B', unitPriceMinor, quantity: 1 }], + }, + impl, + ), + ).rejects.toThrow(/positive amount/); + } + for (const amountMinor of [-1, 2.5]) { await expect( - createCheckoutSession('sk_test_123', { ...SESSION, amountMinor }, impl), + createCheckoutSession( + 'sk_test_123', + { ...SESSION, shipping: { label: 'Europe', amountMinor } }, + impl, + ), ).rejects.toThrow(/positive amount/); } + await expect( + createCheckoutSession( + 'sk_test_123', + { + ...SESSION, + lines: [ + { name: 'Bolt', sku: 'B', unitPriceMinor: 10, quantity: 1.5 }, + ], + }, + impl, + ), + ).rejects.toThrow(/positive amount/); expect(calls).toHaveLength(0); }); @@ -232,3 +427,83 @@ describe('createRefund', () => { expect(bodyOf(call).get('reason')).toBe('requested_by_customer'); }); }); + +describe('createTaxCustomer', () => { + it('gives Stripe the address the order ships to, keyed on the order', async () => { + const { impl, calls } = recordingFetch({ id: 'cus_1' }); + + const customer = await createTaxCustomer( + 'sk_test_123', + { + orderId: 'order-7', + email: 'buyer@example.com', + company: 'Acme GmbH', + address: { + recipient: 'Jane Buyer', + line1: 'Hafenstraße 1', + line2: '', + city: 'Hamburg', + region: 'HH', + postalCode: '20457', + country: 'DE', + }, + }, + impl, + ); + + const call = only(calls); + const body = bodyOf(call); + expect(call.url).toBe('https://api.stripe.com/v1/customers'); + expect(headersOf(call)['Idempotency-Key']).toBe('customer:order-7'); + expect(body.get('email')).toBe('buyer@example.com'); + expect(body.get('name')).toBe('Acme GmbH'); + expect(body.get('shipping[name]')).toBe('Jane Buyer'); + expect(body.get('shipping[address][line1]')).toBe('Hafenstraße 1'); + expect(body.has('shipping[address][line2]')).toBe(false); + expect(body.get('shipping[address][state]')).toBe('HH'); + expect(body.get('shipping[address][country]')).toBe('DE'); + expect(body.get('address[postal_code]')).toBe('20457'); + expect(body.get('metadata[order_id]')).toBe('order-7'); + expect(customer).toEqual({ id: 'cus_1' }); + }); +}); + +describe('expireCheckoutSession', () => { + it('expires the session so it can no longer be paid', async () => { + const { impl, calls } = recordingFetch({ id: 'cs_1', status: 'expired' }); + + expect(await expireCheckoutSession('sk_test_123', 'cs_1', impl)).toBe( + 'expired', + ); + const call = only(calls); + expect(call.url).toBe( + 'https://api.stripe.com/v1/checkout/sessions/cs_1/expire', + ); + expect(headersOf(call)['Idempotency-Key']).toBe('expire:cs_1'); + }); + + it('reports a session that is no longer open, rather than throwing', async () => { + const { impl } = recordingFetch( + { + error: { + type: 'invalid_request_error', + code: 'checkout_session_not_open', + }, + }, + 400, + ); + + expect(await expireCheckoutSession('sk_test_123', 'cs_1', impl)).toBe( + 'not_open', + ); + }); + + it('throws for what a later try could change: a bad key, a limit, an outage', async () => { + for (const status of [401, 429, 500, 503]) { + const { impl } = recordingFetch({ error: { type: 'api_error' } }, status); + await expect( + expireCheckoutSession('sk_test_123', 'cs_1', impl), + ).rejects.toThrow(new RegExp(`status ${status}`)); + } + }); +}); From 451e457ddede4ea1ef149ce44fc3a15b4e49f18c Mon Sep 17 00:00:00 2001 From: JasonYv Date: Sat, 31 Oct 2026 22:39:05 +0800 Subject: [PATCH 04/26] feat: write the buyer's four emails and the seller's three notices The buyer is told an order is confirmed, shipped, refunded, or cancelled by the seller, in the order's language, with a link to the order; the seller is told of a new order, of one paid for after its stock had gone, and of a payment that has to be refunded, with the reason. Everything a person typed is escaped on its way into the HTML. --- src/plugins/shop/lib/order-email.ts | 413 +++++++++++++++++++++++++--- test/shop/order-email.test.ts | 152 ++++++++++ 2 files changed, 529 insertions(+), 36 deletions(-) diff --git a/src/plugins/shop/lib/order-email.ts b/src/plugins/shop/lib/order-email.ts index 98078a2..10b1a95 100644 --- a/src/plugins/shop/lib/order-email.ts +++ b/src/plugins/shop/lib/order-email.ts @@ -1,16 +1,25 @@ /** - * The two emails an order sends its buyer: payment confirmed, and shipped. + * The emails an order sends. * - * Each is written in the language the order was placed in, and each carries a - * plain-text part beside the HTML: HTML alone renders blank in some clients - * and raises the spam score. + * The buyer's four (design §20, D17): payment confirmed, shipped, refunded, + * and cancelled by the seller. Each is written in the language the order was + * placed in. The seller's (D16): a new order, an order paid for after its + * stock had gone, and a payment that has to be refunded — in English, as + * the inquiry's is, since they are read in the admin's language. + * + * Each carries a plain-text part beside the HTML: HTML alone renders blank + * in some clients and raises the spam score. Every value that reached the + * shop from a person — a name, an address, a product's name typed in the + * admin — is escaped on its way into the HTML. * * These build the content only. Sending is Mallok's `ctx.sendEmail`. */ import { escapeHtml } from 'mallok/worker'; +import type { Currency } from './currency.js'; import { formatMoney } from './money.js'; -import type { OrderDetail } from './orders.js'; +import type { OrderDetail, OrderLine, ShippingAddress } from './orders.js'; +import { countryName } from './shipping.js'; export interface EmailContent { readonly subject: string; @@ -22,11 +31,22 @@ interface Copy { readonly confirmSubject: (orderNo: string) => string; readonly confirmIntro: string; readonly itemsHeading: string; + readonly subtotalLabel: string; + readonly shippingLabel: string; + readonly taxLabel: string; readonly totalLabel: string; + readonly addressHeading: string; readonly leadTime: (days: number) => string; + readonly viewOrder: string; readonly shipSubject: (orderNo: string) => string; readonly shipIntro: string; readonly trackingLabel: string; + readonly carrierLabel: string; + readonly refundSubject: (orderNo: string) => string; + readonly refundIntro: (amount: string) => string; + readonly refundTiming: string; + readonly cancelSubject: (orderNo: string) => string; + readonly cancelIntro: string; readonly signOff: string; } @@ -34,11 +54,24 @@ const ENGLISH: Copy = { confirmSubject: (orderNo) => `Order ${orderNo} confirmed`, confirmIntro: 'Thank you for your order. We have received your payment.', itemsHeading: 'Items', + subtotalLabel: 'Subtotal', + shippingLabel: 'Shipping', + taxLabel: 'Tax', totalLabel: 'Total', + addressHeading: 'Shipping to', leadTime: (days) => `Expected to ship within ${days} business days.`, + viewOrder: 'See your order', shipSubject: (orderNo) => `Order ${orderNo} has shipped`, shipIntro: 'Your order is on its way.', trackingLabel: 'Tracking number', + carrierLabel: 'Carrier', + refundSubject: (orderNo) => `Order ${orderNo} refunded`, + refundIntro: (amount) => + `We have refunded ${amount} to the payment method you used.`, + refundTiming: + 'Depending on your bank, it can take a few business days to appear.', + cancelSubject: (orderNo) => `Order ${orderNo} cancelled`, + cancelIntro: 'Your order has been cancelled. You have not been charged.', signOff: 'If you have any questions, simply reply to this email.', }; @@ -49,12 +82,26 @@ const COPY: Readonly> = { confirmIntro: 'Vielen Dank für Ihre Bestellung. Ihre Zahlung ist bei uns eingegangen.', itemsHeading: 'Artikel', + subtotalLabel: 'Zwischensumme', + shippingLabel: 'Versand', + taxLabel: 'Steuer', totalLabel: 'Gesamt', + addressHeading: 'Lieferadresse', leadTime: (days) => `Voraussichtlicher Versand innerhalb von ${days} Werktagen.`, + viewOrder: 'Bestellung ansehen', shipSubject: (orderNo) => `Bestellung ${orderNo} wurde versandt`, shipIntro: 'Ihre Bestellung ist unterwegs.', trackingLabel: 'Sendungsnummer', + carrierLabel: 'Versanddienstleister', + refundSubject: (orderNo) => `Bestellung ${orderNo} erstattet`, + refundIntro: (amount) => + `Wir haben ${amount} auf Ihr Zahlungsmittel zurückerstattet.`, + refundTiming: + 'Je nach Bank kann es einige Werktage dauern, bis der Betrag sichtbar ist.', + cancelSubject: (orderNo) => `Bestellung ${orderNo} storniert`, + cancelIntro: + 'Ihre Bestellung wurde storniert. Ihnen wurde nichts berechnet.', signOff: 'Bei Fragen antworten Sie einfach auf diese E-Mail.', }, fr: { @@ -62,22 +109,47 @@ const COPY: Readonly> = { confirmIntro: 'Merci pour votre commande. Nous avons bien reçu votre paiement.', itemsHeading: 'Articles', + subtotalLabel: 'Sous-total', + shippingLabel: 'Livraison', + taxLabel: 'Taxes', totalLabel: 'Total', + addressHeading: 'Adresse de livraison', leadTime: (days) => `Expédition prévue sous ${days} jours ouvrés.`, + viewOrder: 'Voir votre commande', shipSubject: (orderNo) => `Commande ${orderNo} expédiée`, shipIntro: 'Votre commande est en route.', trackingLabel: 'Numéro de suivi', + carrierLabel: 'Transporteur', + refundSubject: (orderNo) => `Commande ${orderNo} remboursée`, + refundIntro: (amount) => + `Nous avons remboursé ${amount} sur le moyen de paiement utilisé.`, + refundTiming: + 'Selon votre banque, le remboursement peut mettre quelques jours ouvrés à apparaître.', + cancelSubject: (orderNo) => `Commande ${orderNo} annulée`, + cancelIntro: 'Votre commande a été annulée. Aucun montant n’a été débité.', signOff: 'Pour toute question, répondez simplement à cet e-mail.', }, es: { confirmSubject: (orderNo) => `Pedido ${orderNo} confirmado`, confirmIntro: 'Gracias por su pedido. Hemos recibido su pago.', itemsHeading: 'Artículos', + subtotalLabel: 'Subtotal', + shippingLabel: 'Envío', + taxLabel: 'Impuestos', totalLabel: 'Total', + addressHeading: 'Dirección de envío', leadTime: (days) => `Envío previsto en ${days} días hábiles.`, + viewOrder: 'Ver su pedido', shipSubject: (orderNo) => `Pedido ${orderNo} enviado`, shipIntro: 'Su pedido está en camino.', trackingLabel: 'Número de seguimiento', + carrierLabel: 'Transportista', + refundSubject: (orderNo) => `Pedido ${orderNo} reembolsado`, + refundIntro: (amount) => + `Hemos reembolsado ${amount} al medio de pago que utilizó.`, + refundTiming: 'Según su banco, puede tardar unos días hábiles en aparecer.', + cancelSubject: (orderNo) => `Pedido ${orderNo} cancelado`, + cancelIntro: 'Su pedido ha sido cancelado. No se le ha cobrado nada.', signOff: 'Si tiene alguna pregunta, responda a este correo.', }, }; @@ -105,17 +177,72 @@ ${bodyHtml} `; } -/** The confirmation sent once, when an order's payment is confirmed. */ +const SIGN_OFF_STYLE = 'color:#525252;font-size:14px;'; + +/** A link to an absolute https address, or nothing. */ +function linkHtml(href: string | undefined, label: string): string { + if (href === undefined || !/^https?:\/\//.test(href)) { + return ''; + } + return `

${escapeHtml(label)}

`; +} + +/** An address, one line a part, the country by name. */ +function addressLines( + address: Partial, + company: string, + language: string, +): string[] { + const cityLine = [address.postalCode, address.city] + .filter((part) => part !== undefined && part !== '') + .join(' '); + return [ + address.recipient, + company, + address.line1, + address.line2, + cityLine, + address.state, + address.country === undefined || address.country === '' + ? undefined + : countryName(address.country, language), + ].filter((line): line is string => line !== undefined && line !== ''); +} + +function lineText(line: OrderLine, money: (minor: number) => string): string { + return `- ${line.name} (${line.sku}) × ${line.quantity} — ${money( + line.unitPriceMinor * line.quantity, + )}`; +} + +function lineHtml(line: OrderLine, money: (minor: number) => string): string { + return `
  • ${escapeHtml(line.name)} (${escapeHtml(line.sku)}) × ${ + line.quantity + } — ${escapeHtml(money(line.unitPriceMinor * line.quantity))}
  • `; +} + +type ConfirmedOrder = Pick< + OrderDetail, + 'orderNo' | 'currency' | 'totalMinor' | 'locale' | 'lines' | 'leadTimeDaysMax' +> & + Partial< + Pick< + OrderDetail, + | 'subtotalMinor' + | 'shippingMinor' + | 'taxMinor' + | 'shippingAddress' + | 'company' + > + >; + +/** + * The confirmation sent once, when an order's payment is confirmed. With the + * order's own link, when there is one, so that the buyer can follow it. + */ export function orderConfirmationEmail( - order: Pick< - OrderDetail, - | 'orderNo' - | 'currency' - | 'totalMinor' - | 'locale' - | 'lines' - | 'leadTimeDaysMax' - >, + order: ConfirmedOrder, + orderUrl?: string, ): EmailContent { const language = languageOf(order.locale); const copy = COPY[language] ?? ENGLISH; @@ -126,45 +253,62 @@ export function orderConfirmationEmail( order.leadTimeDaysMax === null ? null : copy.leadTime(order.leadTimeDaysMax); + // The parts of the total, when the order says what they are. + const breakdown: [string, number][] = + order.subtotalMinor === undefined + ? [] + : [ + [copy.subtotalLabel, order.subtotalMinor], + [copy.shippingLabel, order.shippingMinor ?? 0], + ...((order.taxMinor ?? 0) > 0 + ? ([[copy.taxLabel, order.taxMinor ?? 0]] as [string, number][]) + : []), + ]; + const address = + order.shippingAddress === undefined + ? [] + : addressLines(order.shippingAddress, order.company ?? '', language); const text = [ copy.confirmIntro, '', `${copy.itemsHeading}:`, - ...order.lines.map( - (line) => - `- ${line.name} (${line.sku}) × ${line.quantity} — ${money( - line.unitPriceMinor * line.quantity, - )}`, - ), + ...order.lines.map((line) => lineText(line, money)), '', + ...breakdown.map(([label, minor]) => `${label}: ${money(minor)}`), `${copy.totalLabel}: ${money(order.totalMinor)}`, ...(leadTimeLine === null ? [] : ['', leadTimeLine]), + ...(address.length === 0 + ? [] + : ['', `${copy.addressHeading}:`, ...address]), + ...(orderUrl === undefined ? [] : ['', `${copy.viewOrder}: ${orderUrl}`]), '', copy.signOff, ].join('\n'); - // Names and SKUs are typed by people in the admin and reach a buyer's - // inbox as markup, so every one of them is escaped. - const items = order.lines - .map( - (line) => - `
  • ${escapeHtml(line.name)} (${escapeHtml(line.sku)}) × ${ - line.quantity - } — ${escapeHtml(money(line.unitPriceMinor * line.quantity))}
  • `, - ) - .join(''); - const html = layout( subject, `

    ${escapeHtml(copy.confirmIntro)}

    ${escapeHtml(copy.itemsHeading)}

    -
      ${items}
    +
      ${order.lines.map((line) => lineHtml(line, money)).join('')}
    +${breakdown + .map( + ([label, minor]) => + `

    ${escapeHtml(label)}: ${escapeHtml(money(minor))}

    `, + ) + .join('\n')}

    ${escapeHtml(copy.totalLabel)}: ${escapeHtml( money(order.totalMinor), )}

    ${leadTimeLine === null ? '' : `

    ${escapeHtml(leadTimeLine)}

    `} -

    ${escapeHtml(copy.signOff)}

    `, +${ + address.length === 0 + ? '' + : `

    ${escapeHtml(copy.addressHeading)}

    +

    ${address.map(escapeHtml).join('
    ')}

    ` +} +${linkHtml(orderUrl, copy.viewOrder)} +

    ${escapeHtml(copy.signOff)}

    `, ); return { subject, text, html }; @@ -175,15 +319,30 @@ export function shippingNotificationEmail(input: { readonly orderNo: string; readonly locale: string; readonly trackingNo: string | null; + readonly carrier?: string | null; + readonly orderUrl?: string; }): EmailContent { const copy = COPY[languageOf(input.locale)] ?? ENGLISH; const subject = copy.shipSubject(input.orderNo); + const carrier = + input.carrier === undefined || + input.carrier === null || + input.carrier === '' + ? null + : input.carrier; const text = [ copy.shipIntro, + ...(carrier === null ? [] : ['', `${copy.carrierLabel}: ${carrier}`]), ...(input.trackingNo === null ? [] - : ['', `${copy.trackingLabel}: ${input.trackingNo}`]), + : [ + ...(carrier === null ? [''] : []), + `${copy.trackingLabel}: ${input.trackingNo}`, + ]), + ...(input.orderUrl === undefined + ? [] + : ['', `${copy.viewOrder}: ${input.orderUrl}`]), '', copy.signOff, ].join('\n'); @@ -191,6 +350,13 @@ export function shippingNotificationEmail(input: { const html = layout( subject, `

    ${escapeHtml(copy.shipIntro)}

    +${ + carrier === null + ? '' + : `

    ${escapeHtml(copy.carrierLabel)}: ${escapeHtml( + carrier, + )}

    ` +} ${ input.trackingNo === null ? '' @@ -198,8 +364,183 @@ ${ input.trackingNo, )}

    ` } -

    ${escapeHtml(copy.signOff)}

    `, +${linkHtml(input.orderUrl, copy.viewOrder)} +

    ${escapeHtml(copy.signOff)}

    `, + ); + + return { subject, text, html }; +} + +/** The notice sent once an order's payment has been refunded. */ +export function refundNotificationEmail(input: { + readonly orderNo: string; + readonly locale: string; + readonly currency: Currency; + readonly totalMinor: number; + readonly orderUrl?: string; +}): EmailContent { + const language = languageOf(input.locale); + const copy = COPY[language] ?? ENGLISH; + const subject = copy.refundSubject(input.orderNo); + const intro = copy.refundIntro( + formatMoney(input.totalMinor, input.currency, language), + ); + + const text = [ + intro, + copy.refundTiming, + ...(input.orderUrl === undefined + ? [] + : ['', `${copy.viewOrder}: ${input.orderUrl}`]), + '', + copy.signOff, + ].join('\n'); + const html = layout( + subject, + `

    ${escapeHtml(intro)}

    +

    ${escapeHtml(copy.refundTiming)}

    +${linkHtml(input.orderUrl, copy.viewOrder)} +

    ${escapeHtml(copy.signOff)}

    `, ); + return { subject, text, html }; +} +/** The notice sent when the seller cancels an order that was never paid. */ +export function cancellationEmail(input: { + readonly orderNo: string; + readonly locale: string; +}): EmailContent { + const copy = COPY[languageOf(input.locale)] ?? ENGLISH; + const subject = copy.cancelSubject(input.orderNo); + const text = [copy.cancelIntro, '', copy.signOff].join('\n'); + const html = layout( + subject, + `

    ${escapeHtml(copy.cancelIntro)}

    +

    ${escapeHtml(copy.signOff)}

    `, + ); return { subject, text, html }; } + +type SellerOrder = Pick< + OrderDetail, + | 'orderNo' + | 'currency' + | 'subtotalMinor' + | 'shippingMinor' + | 'taxMinor' + | 'totalMinor' + | 'email' + | 'company' + | 'taxId' + | 'shippingZone' + | 'shippingAddress' + | 'lines' +>; + +/** The order, as the seller's notices print it: lines, sums, buyer, address. */ +function sellerSummary(order: SellerOrder): { text: string[]; html: string } { + const money = (minor: number) => formatMoney(minor, order.currency, 'en'); + const address = addressLines(order.shippingAddress, order.company, 'en'); + const facts: [string, string][] = [ + ['Subtotal', money(order.subtotalMinor)], + ['Shipping', money(order.shippingMinor)], + ...(order.taxMinor > 0 + ? ([['Tax', money(order.taxMinor)]] as [string, string][]) + : []), + ['Total', money(order.totalMinor)], + ['Buyer', order.email], + ...(order.taxId === '' + ? [] + : ([['Tax number', order.taxId]] as [string, string][])), + ...(order.shippingZone === '' + ? [] + : ([['Shipping zone', order.shippingZone]] as [string, string][])), + ]; + return { + text: [ + 'Items:', + ...order.lines.map((line) => lineText(line, money)), + '', + ...facts.map(([label, value]) => `${label}: ${value}`), + ...(address.length === 0 ? [] : ['', 'Ship to:', ...address]), + ], + html: `
      ${order.lines.map((line) => lineHtml(line, money)).join('')}
    +${facts + .map( + ([label, value]) => + `

    ${escapeHtml(label)}: ${escapeHtml(value)}

    `, + ) + .join('\n')} +${ + address.length === 0 + ? '' + : `

    Ship to

    +

    ${address.map(escapeHtml).join('
    ')}

    ` +}`, + }; +} + +/** To the seller, when an order has been paid for. Answered to the buyer. */ +export function sellerNewOrderEmail(order: SellerOrder): EmailContent { + const money = formatMoney(order.totalMinor, order.currency, 'en'); + const subject = `New order ${order.orderNo} — ${money}`; + const summary = sellerSummary(order); + const intro = + 'An order has been paid for. It is in the admin under Shop → Orders.'; + return { + subject, + text: [intro, '', ...summary.text].join('\n'), + html: layout(subject, `

    ${escapeHtml(intro)}

    \n${summary.html}`), + }; +} + +/** To the seller, when an order was paid for after its stock had gone. */ +export function sellerOversoldEmail(order: SellerOrder): EmailContent { + const subject = `Order ${order.orderNo} was paid for, and the stock had gone`; + const intro = + 'The payment went through after the stock for this order had been sold. Nothing has been shipped or taken from stock. In the admin, under Shop → Orders, either refund it, or restock and fulfil it.'; + const summary = sellerSummary(order); + return { + subject, + text: [intro, '', ...summary.text].join('\n'), + html: layout(subject, `

    ${escapeHtml(intro)}

    \n${summary.html}`), + }; +} + +/** Why a payment could not be kept, as the seller is told it. */ +export type RefusedBecause = + /** The order had been cancelled when the payment came in. */ + | 'cancelled' + /** Another payment had settled the order already. */ + | 'already_paid' + /** The payment did not come to the order's total in its currency. */ + | 'amount_mismatch'; + +const REFUSED_REASON: Readonly> = { + cancelled: 'the order had been cancelled when the payment came in', + already_paid: 'another payment had already settled the order', + amount_mismatch: + "the payment did not come to the order's total in its currency", +}; + +/** To the seller, when a payment came in that the shop could not keep. */ +export function sellerRefundOwedEmail(input: { + readonly orderNo: string; + readonly paymentIntentId: string; + readonly because: RefusedBecause; +}): EmailContent { + const subject = `A payment for order ${input.orderNo} has to be refunded`; + const lines = [ + `Stripe took a payment for order ${input.orderNo} that the shop could not keep: ${REFUSED_REASON[input.because]}. Nothing was shipped and no stock was taken.`, + `Payment: ${input.paymentIntentId}`, + 'Refund it in the admin, under Shop → Refused payments, so that the shop records the refund.', + ]; + return { + subject, + text: lines.join('\n\n'), + html: layout( + subject, + lines.map((line) => `

    ${escapeHtml(line)}

    `).join('\n'), + ), + }; +} diff --git a/test/shop/order-email.test.ts b/test/shop/order-email.test.ts index dd3dfab..b29836b 100644 --- a/test/shop/order-email.test.ts +++ b/test/shop/order-email.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from 'vitest'; import { + cancellationEmail, orderConfirmationEmail, + refundNotificationEmail, + sellerNewOrderEmail, + sellerOversoldEmail, + sellerRefundOwedEmail, shippingNotificationEmail, } from '../../src/plugins/shop/lib/order-email.js'; @@ -165,3 +170,150 @@ describe('shippingNotificationEmail', () => { expect(nasty.html).toContain('<b>T1</b>'); }); }); + +describe('the confirmation, with what checkout knows', () => { + const full = orderConfirmationEmail( + { + ...ORDER, + subtotalMinor: 99_000, + shippingMinor: 4900, + taxMinor: 0, + totalMinor: 103_900, + company: 'Engines & ', + shippingAddress: { + recipient: 'Ada Lovelace', + line1: '1 Harbour Road', + city: 'Aberdeen', + postalCode: 'AB11 5RY', + country: 'GB', + }, + }, + 'https://shop.example/_mallok/p/shop/order/ND-261005-7K3M9QXA?k=abc', + ); + + it('states the goods and the shipping as well as the total, and no tax line for none', () => { + expect(full.text).toContain('Subtotal: $990.00'); + expect(full.text).toContain('Shipping: $49.00'); + expect(full.text).toContain('Total: $1,039.00'); + expect(full.text).not.toContain('Tax:'); + }); + + it('says where the order goes, the country by name', () => { + expect(full.text).toContain( + 'Shipping to:\nAda Lovelace\nEngines & \n1 Harbour Road\nAB11 5RY Aberdeen\nUnited Kingdom', + ); + expect(full.html).toContain('Ada <b>Lovelace</b>'); + expect(full.html).toContain('Engines & <Sons>'); + expect(full.html).not.toContain('Lovelace'); + }); + + it('carries the buyer’s link to their order', () => { + expect(full.text).toContain( + 'See your order: https://shop.example/_mallok/p/shop/order/ND-261005-7K3M9QXA?k=abc', + ); + expect(full.html).toContain( + 'See your order', + ); + }); + + it('links nothing that is not a web address', () => { + const odd = orderConfirmationEmail(ORDER, 'javascript:alert(1)'); + expect(odd.html).not.toContain('javascript:'); + }); +}); + +describe('the shipping notice, with a carrier', () => { + it('names the carrier beside the tracking number', () => { + const mail = shippingNotificationEmail({ + orderNo: 'ND-1', + locale: 'fr', + trackingNo: '1Z999', + carrier: 'UPS', + }); + + expect(mail.text).toContain('Transporteur: UPS\nNuméro de suivi: 1Z999'); + }); +}); + +describe('refundNotificationEmail', () => { + it('says how much went back, in the order’s language and money', () => { + const mail = refundNotificationEmail({ + orderNo: 'ND-1', + locale: 'de', + currency: 'EUR', + totalMinor: 94_500, + }); + + expect(mail.subject).toBe('Bestellung ND-1 erstattet'); + expect(mail.text).toContain('Wir haben 945,00'); + }); +}); + +describe('cancellationEmail', () => { + it('says the order was cancelled and nothing was charged', () => { + const mail = cancellationEmail({ orderNo: 'ND-1', locale: 'es' }); + + expect(mail.subject).toBe('Pedido ND-1 cancelado'); + expect(mail.text).toContain('No se le ha cobrado nada.'); + }); +}); + +describe('the seller’s notices', () => { + const ORDER_FOR_SELLER = { + orderNo: 'ND-261031-7K3M9QXA', + currency: 'USD' as const, + subtotalMinor: 99_000, + shippingMinor: 4900, + taxMinor: 0, + totalMinor: 103_900, + email: 'ada@buyer.example', + company: 'Engines & ', + taxId: 'GB123', + shippingZone: 'United Kingdom', + shippingAddress: { + recipient: 'Ada', + line1: '1 Road', + city: 'Aberdeen', + country: 'GB', + }, + lines: ORDER.lines, + }; + + it('names a new order and its total, with what it holds and who bought it', () => { + const mail = sellerNewOrderEmail(ORDER_FOR_SELLER); + + expect(mail.subject).toBe('New order ND-261031-7K3M9QXA — $1,039.00'); + expect(mail.text).toContain('Buyer: ada@buyer.example'); + expect(mail.text).toContain('Tax number: GB123'); + expect(mail.text).toContain('Shipping zone: United Kingdom'); + expect(mail.html).toContain('Engines & <Sons>'); + }); + + it('asks for an oversold order to be refunded or restocked', () => { + const mail = sellerOversoldEmail(ORDER_FOR_SELLER); + + expect(mail.subject).toBe( + 'Order ND-261031-7K3M9QXA was paid for, and the stock had gone', + ); + expect(mail.text).toContain('either refund it, or restock and fulfil it'); + }); + + it.each([ + ['cancelled', 'the order had been cancelled'], + ['already_paid', 'another payment had already settled the order'], + ['amount_mismatch', "did not come to the order's total"], + ] as const)( + 'asks for a payment to be refunded and says why: %s', + (because, words) => { + const mail = sellerRefundOwedEmail({ + orderNo: 'ND-1', + paymentIntentId: 'pi_9', + because, + }); + + expect(mail.subject).toBe('A payment for order ND-1 has to be refunded'); + expect(mail.text).toContain(words); + expect(mail.text).toContain('Payment: pi_9'); + }, + ); +}); From 89d62293ba0c49fb5484779973e982cd623d0907 Mon Sep 17 00:00:00 2001 From: JasonYv Date: Sat, 31 Oct 2026 22:39:06 +0800 Subject: [PATCH 05/26] feat: check a cart out and pay for it with Stripe, and run an order afterwards The checkout page asks where the order goes, shows shipping for that country from the seller's zones and the total, and places a pending order before sending the buyer to Stripe; one cart has one payment open at a time. The order's page opens with a signed link, never by its number alone. Stripe's deliveries pay an order, empty what was ordered from its cart in the same batch, and close an order whose payment page lapsed. What each change still owes is carried out by a job, with the cron behind it: emails and purges, claimed so two runners never send one twice. The admin lists orders and refused payments, and ships, delivers, cancels, refunds, and fulfils an oversold order once restocked, always moving the money at Stripe before the books here. --- src/plugins/shop/index.ts | 38 +- src/plugins/shop/lib/cart-pricing.ts | 12 +- src/plugins/shop/lib/cart-view.ts | 5 + src/plugins/shop/lib/checkout-view.ts | 137 ++++ src/plugins/shop/lib/checkout.ts | 271 +++++++ src/plugins/shop/lib/export.ts | 7 +- src/plugins/shop/lib/inquiries.ts | 3 +- src/plugins/shop/lib/order-access.ts | 120 +++ src/plugins/shop/lib/order-admin.ts | 435 +++++++++++ src/plugins/shop/lib/order-follow-up.ts | 403 ++++++++++ src/plugins/shop/lib/order-fulfilment.ts | 2 + src/plugins/shop/lib/orders.ts | 52 +- src/plugins/shop/lib/paths.ts | 32 + src/plugins/shop/lib/scheduled.ts | 118 ++- src/plugins/shop/lib/state.ts | 7 +- src/plugins/shop/lib/stripe-check.ts | 78 ++ src/plugins/shop/migrations/0004_checkout.sql | 82 ++- src/plugins/shop/plugin.json | 255 ++++++- src/plugins/shop/routes/cart.ts | 14 +- src/plugins/shop/routes/checkout.ts | 409 +++++++++++ src/plugins/shop/routes/order.ts | 122 ++++ src/plugins/shop/routes/stripe-webhook.ts | 87 +++ src/theme/assets/style.css | 135 ++++ src/theme/index.ts | 4 + src/theme/layouts/shop-cart.liquid | 5 +- src/theme/layouts/shop-checkout.liquid | 127 ++++ src/theme/layouts/shop-order.liquid | 64 ++ src/theme/locales/de.json | 61 +- src/theme/locales/en.json | 61 +- src/theme/locales/es.json | 61 +- src/theme/locales/fr.json | 61 +- src/theme/theme.json | 6 +- test/shop/checkout-route.test.ts | 538 ++++++++++++++ test/shop/checkout.test.ts | 437 +++++++++++ test/shop/export.test.ts | 18 +- test/shop/helpers.ts | 154 ++++ test/shop/order-admin.test.ts | 688 ++++++++++++++++++ test/shop/order-follow-up.test.ts | 443 +++++++++++ test/shop/order-page.test.ts | 317 ++++++++ test/shop/orders.test.ts | 83 +++ test/shop/scheduled.test.ts | 156 ++++ test/shop/schema.test.ts | 4 +- test/theme/checkout.test.ts | 292 ++++++++ test/theme/packs.test.ts | 8 + 44 files changed, 6367 insertions(+), 45 deletions(-) create mode 100644 src/plugins/shop/lib/checkout-view.ts create mode 100644 src/plugins/shop/lib/checkout.ts create mode 100644 src/plugins/shop/lib/order-access.ts create mode 100644 src/plugins/shop/lib/order-admin.ts create mode 100644 src/plugins/shop/lib/order-follow-up.ts create mode 100644 src/plugins/shop/lib/stripe-check.ts create mode 100644 src/plugins/shop/routes/checkout.ts create mode 100644 src/plugins/shop/routes/order.ts create mode 100644 src/plugins/shop/routes/stripe-webhook.ts create mode 100644 src/theme/layouts/shop-checkout.liquid create mode 100644 src/theme/layouts/shop-order.liquid create mode 100644 test/shop/checkout-route.test.ts create mode 100644 test/shop/checkout.test.ts create mode 100644 test/shop/order-admin.test.ts create mode 100644 test/shop/order-follow-up.test.ts create mode 100644 test/shop/order-page.test.ts create mode 100644 test/theme/checkout.test.ts diff --git a/src/plugins/shop/index.ts b/src/plugins/shop/index.ts index db6a11a..420f98d 100644 --- a/src/plugins/shop/index.ts +++ b/src/plugins/shop/index.ts @@ -3,8 +3,9 @@ * * Mallok provides the site: content, languages, SEO, the admin, the edge * cache. This plugin adds what makes it a shop: variants, prices in several - * currencies, stock, minimum order quantities, a cart, and the cart sent as - * an inquiry. + * currencies, stock, minimum order quantities, a cart, the cart sent as an + * inquiry, and checkout: shipping zones, the order, payment with Stripe, and + * what a seller does with an order afterwards. * * Everything here is commerce logic. Nothing about pages or rendering belongs * in it — that is the theme's side of the boundary. @@ -22,6 +23,15 @@ import { markInquiries, } from './lib/inquiry-admin.js'; import { INQUIRY_EMAILS_JOB, sendInquiryEmails } from './lib/inquiry-jobs.js'; +import { + cancelOrders, + deliverOrders, + fulfilOrders, + refundOrders, + refundRefusedPayments, + shipOrders, +} from './lib/order-admin.js'; +import { FOLLOW_UP_JOB, followUpJob } from './lib/order-follow-up.js'; import { renderData } from './lib/render-data.js'; import { runScheduledTick } from './lib/scheduled.js'; import { @@ -29,6 +39,10 @@ import { removeShippingZone, saveShippingZone, } from './lib/shipping-records.js'; +import { + checkStripeSecretKey, + checkStripeWebhookSecret, +} from './lib/stripe-check.js'; import { loadVariant, onProductDeleted, @@ -41,7 +55,10 @@ import inquiriesSql from './migrations/0003_inquiries.sql'; import checkoutSql from './migrations/0004_checkout.sql'; import manifest from './plugin.json'; import { cartPage, cartUpdate } from './routes/cart.js'; +import { checkoutPage, checkoutPlace } from './routes/checkout.js'; import { cartInquiry } from './routes/inquiry.js'; +import { orderPage } from './routes/order.js'; +import { stripeWebhook } from './routes/stripe-webhook.js'; async function scheduled(ctx: PluginContext): Promise { const outcome = await runScheduledTick(ctx); @@ -89,9 +106,19 @@ export const shop = definePlugin({ cart: cartPage, 'cart/update': cartUpdate, 'cart/inquiry': cartInquiry, + checkout: checkoutPage, + 'checkout/place': checkoutPlace, + 'order/:orderNo': orderPage, + 'stripe/webhook': stripeWebhook, }, jobs: { [INQUIRY_EMAILS_JOB]: (payload, ctx) => sendInquiryEmails(payload, ctx), + [FOLLOW_UP_JOB]: (payload, ctx) => followUpJob(payload, ctx), + }, + checkSecrets: { + stripe_secret_key: (ctx: PluginContext) => checkStripeSecretKey(ctx), + stripe_webhook_secret: (ctx: PluginContext) => + checkStripeWebhookSecret(ctx), }, actions: { inquiry_mark_answered: (ids, ctx) => markInquiries(ids, ctx, 'answered'), @@ -99,5 +126,12 @@ export const shop = definePlugin({ inquiry_mark_spam: (ids, ctx) => markInquiries(ids, ctx, 'spam'), inquiry_export_csv: (ids, ctx) => exportInquiries(ids, ctx), inquiry_delete: (ids, ctx, params) => deleteInquiries(ids, ctx, params), + order_ship: (ids, ctx, params) => shipOrders(ids, ctx, params), + order_deliver: (ids, ctx) => deliverOrders(ids, ctx), + order_fulfil: (ids, ctx, params) => fulfilOrders(ids, ctx, params), + order_refund: (ids, ctx, params) => refundOrders(ids, ctx, params), + order_cancel: (ids, ctx, params) => cancelOrders(ids, ctx, params), + payment_refund: (ids, ctx, params) => + refundRefusedPayments(ids, ctx, params), }, }); diff --git a/src/plugins/shop/lib/cart-pricing.ts b/src/plugins/shop/lib/cart-pricing.ts index ca69e71..2d8a687 100644 --- a/src/plugins/shop/lib/cart-pricing.ts +++ b/src/plugins/shop/lib/cart-pricing.ts @@ -286,8 +286,18 @@ export async function priceCart( if (input.lines.length === 0) { return { ok: false, issues: [{ kind: 'empty' }] }; } - const facts = await readCartFacts(db, input); + return pricedCartOf(await readCartFacts(db, input)); +} +/** + * A cart's reading as an order's lines, or its list of problems. Checkout + * reads the cart once and turns that same reading into the order, so the + * order cannot be priced from anything the page did not show. + */ +export function pricedCartOf(facts: CartFacts): PricedCart { + if (facts.lines.length === 0) { + return { ok: false, issues: [{ kind: 'empty' }] }; + } const issues = facts.lines.flatMap((line) => line.issue === null ? [] : [line.issue], ); diff --git a/src/plugins/shop/lib/cart-view.ts b/src/plugins/shop/lib/cart-view.ts index 7bb6df5..b31073e 100644 --- a/src/plugins/shop/lib/cart-view.ts +++ b/src/plugins/shop/lib/cart-view.ts @@ -33,6 +33,11 @@ * `phone`, `message`, or ''), `empty`, `cart_problem`, * `too_many` * + * And for paying for it: + * + * checkout_path the checkout page + * can_check_out every line can be ordered and the shop takes payments + * * The form's fields are `name`, `email`, `company`, `phone` and `message`, * of which the first two are required, and `website`, which a person must * not see: whatever fills it in is not one. `lib/inquiries.ts` has the diff --git a/src/plugins/shop/lib/checkout-view.ts b/src/plugins/shop/lib/checkout-view.ts new file mode 100644 index 0000000..5f16766 --- /dev/null +++ b/src/plugins/shop/lib/checkout-view.ts @@ -0,0 +1,137 @@ +/** + * The checkout page as a theme draws it: what the layout `shop/checkout` + * receives as `plugin_page`. As with the cart's view, every value is ready to + * print and the words around it are the theme's. + * + * currency the currency every amount is in + * lines[] sku, name, path, quantity, unit_price, line_total + * goods what the lines come to + * countries[] code, name, selected: where the cart can be shipped in its + * currency, by name in the page's language + * country the country chosen, or '' + * zone the shipping zone's name; '' until a country is chosen + * shipping what shipping costs, or ''; `shipping_free` when it is + * nothing because the goods passed `free_over` + * free_over what the goods must come to to ship free, or '' + * total goods and shipping; '' until a country is chosen + * tax_mode `none`: prices are without tax and none is charged. + * `stripe`: tax is added at payment, where it applies + * problem '' or why the cart cannot be checked out as it stands: + * `empty`, `cart_problem`, `no_shipping`, `too_small`, + * `too_large` + * payments whether the shop can take a payment at all: false until + * its Stripe keys are set + * can_place the form can be sent: payments, a country, no problem + * refused null, or `kind` and `field`: why the form that was sent + * placed no order — `invalid` (with the field), `empty`, + * `cart_problem`, `no_shipping`, `too_small`, `too_large`, + * `payments_unavailable` + * terms_path a page the buyer must accept to order, or '' + * country_action where the form that chooses a country is sent, by GET + * action where the order form posts + * cart_path the cart page + * limits the most each field may hold: `email`, `company`, + * `recipient`, `phone`, `line1`, `line2`, `postal_code`, + * `city`, `state`, `tax_id` + * email_pattern, name_pattern the patterns the server holds the address + * and every required line to, as a field's `pattern` + * + * The order form's fields are those of `limits`, then `country` (the one + * chosen, as a hidden field), `terms` (a box sending `yes`, when there is a + * `terms_path`) and `website`, which a person must not see. `email`, + * `company`, `recipient`, `line1` and `city` are required. + * + * A form the server refuses comes back empty — Mallok lists a page under the + * address that rendered it, so the refusal is a redirect to this page, and + * what was typed does not travel in an address. The fields carry the + * server's rules so that a browser refuses first. + */ + +import { CHECKOUT_LIMITS, type CheckoutReading } from './checkout.js'; +import { EMAIL_PATTERN_SOURCE, NAME_PATTERN_SOURCE } from './inquiries.js'; +import { formatMoney } from './money.js'; +import type { TaxMode } from './orders.js'; + +/** Why a sent form placed no order. A theme has words for each. */ +export const CHECKOUT_REFUSALS = [ + 'invalid', + 'empty', + 'cart_problem', + 'no_shipping', + 'too_small', + 'too_large', + 'payments_unavailable', +] as const; + +export type CheckoutRefusal = (typeof CHECKOUT_REFUSALS)[number]; + +export function checkoutView( + reading: CheckoutReading, + input: { + readonly locale: string; + readonly taxMode: TaxMode; + readonly payments: boolean; + readonly termsPath: string; + readonly refused: { kind: CheckoutRefusal; field: string } | null; + readonly paths: { + readonly checkout: string; + readonly place: string; + readonly cart: string; + }; + }, +): Readonly> { + const { facts, quote, rate } = reading; + const money = (minor: number) => + formatMoney(minor, facts.currency, input.locale); + const goodsMinor = + quote?.goodsMinor ?? + facts.lines.reduce( + (sum, line) => sum + (line.unitPriceMinor ?? 0) * line.quantity, + 0, + ); + const priced = + reading.problem !== 'empty' && reading.problem !== 'cart_problem'; + return { + currency: facts.currency, + lines: facts.lines.map((line) => ({ + sku: line.sku, + name: line.name ?? '', + path: line.path ?? '', + quantity: line.quantity, + unit_price: + line.unitPriceMinor === null ? '' : money(line.unitPriceMinor), + line_total: + line.unitPriceMinor === null + ? '' + : money(line.unitPriceMinor * line.quantity), + })), + goods: priced ? money(goodsMinor) : '', + countries: reading.countries.map((entry) => ({ + code: entry.code, + name: entry.name, + selected: entry.code === reading.country, + })), + country: reading.country ?? '', + zone: rate?.zoneName ?? '', + shipping: quote === null ? '' : money(quote.shippingMinor), + shipping_free: quote !== null && quote.shippingMinor === 0, + free_over: + rate === null || rate.freeOverMinor === null + ? '' + : money(rate.freeOverMinor), + total: quote === null ? '' : money(quote.totalMinor), + tax_mode: input.taxMode, + problem: reading.problem ?? '', + payments: input.payments, + can_place: + input.payments && reading.problem === null && reading.country !== null, + refused: input.refused, + terms_path: input.termsPath, + country_action: input.paths.checkout, + action: input.paths.place, + cart_path: input.paths.cart, + limits: CHECKOUT_LIMITS, + email_pattern: EMAIL_PATTERN_SOURCE, + name_pattern: NAME_PATTERN_SOURCE, + }; +} diff --git a/src/plugins/shop/lib/checkout.ts b/src/plugins/shop/lib/checkout.ts new file mode 100644 index 0000000..2f73003 --- /dev/null +++ b/src/plugins/shop/lib/checkout.ts @@ -0,0 +1,271 @@ +/** + * Checkout: what a cart comes to once it is going somewhere, and the form a + * buyer fills in to send it. + * + * The checkout page and the order it places read the cart the same way — + * `readCartFacts`, the cart page's own reading — and add one thing to it: + * where the goods go, and so what shipping costs. `readCheckout` is that one + * reading and `quoteOf` the one sum, so that the page cannot show a figure + * the order would not charge. + * + * The shop sells to businesses (design §20, D1): a company is required. A + * tax number is optional and recorded (D7). Only a country in a shipping + * zone with a rate in the cart's currency can be shipped to (D5). + */ + +import { z } from 'zod'; +import type { CartLine } from './cart.js'; +import { type CartFacts, readCartFacts } from './cart-pricing.js'; +import type { Currency } from './currency.js'; +import { EMAIL_PATTERN, INQUIRY_LIMITS, oneLine } from './inquiries.js'; +import { sumMinor } from './money.js'; +import type { TaxMode } from './orders.js'; +import { + countryName, + isCountryCode, + rateOf, + type ShippingCountry, + type ShippingRate, + shippingCostMinor, + shippingCountriesOf, + shippingCountriesStatement, +} from './shipping.js'; +import { MAX_CHARGE_MINOR, MIN_CHARGE_MINOR } from './stripe-client.js'; + +/** The length each field may have. The form carries the same in `maxlength`. */ +export const CHECKOUT_LIMITS = { + email: INQUIRY_LIMITS.email, + company: 200, + recipient: 200, + phone: 60, + line1: 200, + line2: 200, + city: 100, + state: 100, + postal_code: 20, + tax_id: 40, +} as const; + +/** The fields a buyer fills in, in the order a page shows them. */ +export const CHECKOUT_FIELDS = [ + 'email', + 'company', + 'recipient', + 'phone', + 'line1', + 'line2', + 'postal_code', + 'city', + 'state', + 'country', + 'tax_id', + 'terms', +] as const; + +export type CheckoutField = (typeof CHECKOUT_FIELDS)[number]; + +/** What a box that is ticked sends. */ +export const TERMS_ACCEPTED = 'yes'; + +export const checkoutFormSchema = z.object({ + email: z + .string() + .default('') + .transform((value) => value.trim()) + .pipe(z.string().min(3).max(CHECKOUT_LIMITS.email).regex(EMAIL_PATTERN)), + company: oneLine(CHECKOUT_LIMITS.company, 1), + recipient: oneLine(CHECKOUT_LIMITS.recipient, 1), + phone: oneLine(CHECKOUT_LIMITS.phone), + line1: oneLine(CHECKOUT_LIMITS.line1, 1), + line2: oneLine(CHECKOUT_LIMITS.line2), + // Not every country has postal codes. + postal_code: oneLine(CHECKOUT_LIMITS.postal_code), + city: oneLine(CHECKOUT_LIMITS.city, 1), + state: oneLine(CHECKOUT_LIMITS.state), + country: z + .string() + .default('') + .refine((value) => isCountryCode(value)), + tax_id: oneLine(CHECKOUT_LIMITS.tax_id), + terms: z.string().max(10).default(''), + /** A field no person sees. Whatever fills it in is not one. */ + website: z.string().max(500).default(''), +}); + +export type CheckoutForm = z.infer; + +/** The first field, in the page's order, that was refused. */ +export function firstInvalidCheckoutField( + error: z.ZodError, +): CheckoutField | null { + const named = new Set(error.issues.map((issue) => issue.path[0])); + return CHECKOUT_FIELDS.find((field) => named.has(field)) ?? null; +} + +/** Why a cart cannot be checked out as it stands. A theme has words for each. */ +export type CheckoutProblem = + /** Nothing in it. */ + | 'empty' + /** A line cannot be ordered: the cart page says which. */ + | 'cart_problem' + /** No country chosen yet, or one the shop does not ship to in this currency. */ + | 'no_shipping' + /** Less than Stripe charges: a total of nothing included (D14). */ + | 'too_small' + /** More than one payment can carry. */ + | 'too_large'; + +export interface CheckoutQuote { + readonly goodsMinor: number; + readonly shippingMinor: number; + readonly totalMinor: number; +} + +/** + * What a cart comes to, shipped at a rate, or why it cannot be checked out. + * The one sum both the page and the order use. + */ +export function quoteOf( + facts: CartFacts, + rate: ShippingRate | null, +): { quote: CheckoutQuote | null; problem: CheckoutProblem | null } { + if (facts.lines.length === 0) { + return { quote: null, problem: 'empty' }; + } + if (facts.lines.some((line) => line.issue !== null)) { + return { quote: null, problem: 'cart_problem' }; + } + const goodsMinor = sumMinor( + facts.lines.map((line) => (line.unitPriceMinor ?? 0) * line.quantity), + ); + if (rate === null || rate.currency !== facts.currency) { + return { quote: null, problem: 'no_shipping' }; + } + const shippingMinor = shippingCostMinor(rate, goodsMinor); + const quote = { + goodsMinor, + shippingMinor, + totalMinor: sumMinor([goodsMinor, shippingMinor]), + }; + if (quote.totalMinor < MIN_CHARGE_MINOR[facts.currency]) { + return { quote, problem: 'too_small' }; + } + if (quote.totalMinor > MAX_CHARGE_MINOR) { + return { quote, problem: 'too_large' }; + } + return { quote, problem: null }; +} + +export interface CheckoutReading { + readonly facts: CartFacts; + /** The countries the cart can be shipped to in its currency, by name. */ + readonly countries: readonly { code: string; name: string }[]; + /** The country it is going to: one of `countries`, or null. */ + readonly country: string | null; + readonly rate: ShippingRate | null; + readonly quote: CheckoutQuote | null; + readonly problem: CheckoutProblem | null; +} + +/** Every rate a country has, whatever the currency: one zone's, or none. */ +function countryRatesStatement( + db: D1Database, + country: string, +): D1PreparedStatement { + return db + .prepare( + `SELECT z.id AS zone_id, z.name AS zone_name, r.currency AS currency, + r.amount_minor AS amount_minor, + r.free_over_minor AS free_over_minor + FROM p_shop_shipping_country AS c + JOIN p_shop_shipping_zone AS z ON z.id = c.zone_id + JOIN p_shop_shipping_rate AS r ON r.zone_id = z.id + WHERE c.country = ?`, + ) + .bind(country); +} + +/** + * Reads a cart for checking out to a country: the cart's own reading, then + * where it can go and what that costs, in one more round trip. + * + * `country` is what the buyer asked for; it counts only when the cart can be + * shipped there in its currency, and the reading says so by naming it. + */ +export async function readCheckout( + db: D1Database, + input: { + readonly lines: readonly CartLine[]; + readonly locale: string; + readonly defaultLocale: string; + readonly currency: Currency; + readonly country: string | null; + readonly now?: Date; + }, +): Promise { + const facts = await readCartFacts(db, input); + const asked = + input.country !== null && isCountryCode(input.country) ? input.country : ''; + const [countryResult, rateResult] = await db.batch>([ + shippingCountriesStatement(db), + countryRatesStatement(db, asked), + ]); + const shippable: ShippingCountry[] = shippingCountriesOf( + countryResult?.results ?? [], + ).filter((entry) => entry.currencies.includes(facts.currency)); + const countries = shippable + .map((entry) => ({ + code: entry.code, + name: countryName(entry.code, input.locale), + })) + .sort((a, b) => a.name.localeCompare(b.name, input.locale)); + + const rate = + (rateResult?.results ?? []) + .map(rateOf) + .find((candidate) => candidate?.currency === facts.currency) ?? null; + const country = + rate !== null && countries.some((entry) => entry.code === asked) + ? asked + : null; + const { quote, problem } = quoteOf(facts, country === null ? null : rate); + return { + facts, + countries, + country, + rate: country === null ? null : rate, + quote, + problem, + }; +} + +/** What the shop needs of Stripe to take a payment: both keys. */ +export function stripeKeys( + secrets: Readonly>, +): { secretKey: string; webhookSecret: string } | null { + const secretKey = secrets.stripe_secret_key ?? ''; + const webhookSecret = secrets.stripe_webhook_secret ?? ''; + // Without the signing secret no payment could ever be confirmed: an order + // would be paid for and wait for ever. + return secretKey === '' || webhookSecret === '' + ? null + : { secretKey, webhookSecret }; +} + +export function taxModeOf( + settings: Readonly>, +): TaxMode { + return settings.tax_mode === 'stripe' ? 'stripe' : 'none'; +} + +/** + * The page a buyer must accept, from the settings: a path on this site, or + * nothing. Anything else is not printed as a link. + */ +export function termsPathOf( + settings: Readonly>, +): string { + const value = + typeof settings.terms_path === 'string' ? settings.terms_path.trim() : ''; + return /^\/(?![/\\])[^\s\\]{0,200}$/.test(value) ? value : ''; +} diff --git a/src/plugins/shop/lib/export.ts b/src/plugins/shop/lib/export.ts index b30f0e3..5ae3864 100644 --- a/src/plugins/shop/lib/export.ts +++ b/src/plugins/shop/lib/export.ts @@ -128,9 +128,8 @@ const TABLES: readonly ExportedTable[] = [ name: 'orders', table: 'p_shop_order', sql: 'SELECT * FROM p_shop_order ORDER BY created_at, id LIMIT ?', - // The cart an order came from and the digest of the buyer's link: the - // one was a credential, the other is a credential's fingerprint. - without: ['cart_id', 'access_hash'], + // The cart an order came from: its id was a visitor's credential. + without: ['cart_id'], }, { name: 'order-lines', @@ -146,6 +145,8 @@ const TABLES: readonly ExportedTable[] = [ name: 'outbox', table: 'p_shop_outbox', sql: 'SELECT * FROM p_shop_outbox ORDER BY seq LIMIT ?', + // Whose runner had a row in hand, a moment ago: nothing to carry. + without: ['claimed_at'], }, { name: 'inquiries', diff --git a/src/plugins/shop/lib/inquiries.ts b/src/plugins/shop/lib/inquiries.ts index 9901dc1..c2000f6 100644 --- a/src/plugins/shop/lib/inquiries.ts +++ b/src/plugins/shop/lib/inquiries.ts @@ -104,8 +104,9 @@ export type InquiryField = (typeof INQUIRY_FIELDS)[number]; * becomes one space, rather than being refused: a browser lets a person type * or paste it, and a form the server refuses comes back empty. What is * stored is one line either way, which is what an email's subject needs. + * Checkout's fields follow the same rule. */ -function oneLine(max: number, min = 0) { +export function oneLine(max: number, min = 0) { return z .string() .default('') diff --git a/src/plugins/shop/lib/order-access.ts b/src/plugins/shop/lib/order-access.ts new file mode 100644 index 0000000..7f3516b --- /dev/null +++ b/src/plugins/shop/lib/order-access.ts @@ -0,0 +1,120 @@ +/** + * The secret in a buyer's link to their order. + * + * The shop has no buyer accounts (design §20, D2): what lets a buyer see + * their order is a link — Stripe's return to the shop, and the one in every + * email — whose secret is an HMAC of the order's id. The order number alone + * is not enough: it is printed on a parcel and read out on the phone, and + * says nothing a stranger could not guess from a date. + * + * An HMAC rather than a random token stored with the order, because the + * emails are sent by a job, later, with no request in hand: the job has to + * be able to write the link again, and a stored token would have to be kept + * readable for that. The key is made once, at random, and kept in the shop's + * state — which a site export leaves behind — so an export opens no order's + * page, and a site restored from one gives its old links up. + */ + +import { STATE_KEYS } from './state.js'; + +function base64url(bytes: Uint8Array): string { + let binary = ''; + for (const byte of bytes) { + binary += String.fromCharCode(byte); + } + return btoa(binary) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/, ''); +} + +/** + * The key every order's link is signed with: made the first time it is + * needed, and the same ever after. Two requests that both find none both + * offer one, and both read back whichever was stored first. + */ +export async function orderLinkKey( + db: D1Database, + now: Date, +): Promise { + const offered = base64url(crypto.getRandomValues(new Uint8Array(32))); + const [, stored] = await db.batch<{ value: string }>([ + db + .prepare( + `INSERT INTO p_shop_state (key, value, updated_at) VALUES (?, ?, ?) + ON CONFLICT (key) DO NOTHING`, + ) + .bind(STATE_KEYS.orderLinkKey, offered, now.toISOString()), + db + .prepare('SELECT value FROM p_shop_state WHERE key = ?') + .bind(STATE_KEYS.orderLinkKey), + ]); + const value = (stored?.results ?? [])[0]?.value; + if (value === undefined) { + throw new Error('The order link key could not be stored'); + } + return importKey(value); +} + +/** + * The key, if one has been made, for a page that only reads: a site with + * no key has placed no order, so no link can open anything yet. + */ +export async function existingOrderLinkKey( + db: D1Database, +): Promise { + const row = await db + .prepare('SELECT value FROM p_shop_state WHERE key = ?') + .bind(STATE_KEYS.orderLinkKey) + .first<{ value: string }>(); + return row === null ? null : importKey(row.value); +} + +function importKey(value: string): Promise { + return crypto.subtle.importKey( + 'raw', + new TextEncoder().encode(value), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign', 'verify'], + ); +} + +/** The secret in one order's link: 43 characters of base64url. */ +export async function orderToken( + key: CryptoKey, + orderId: string, +): Promise { + const signature = await crypto.subtle.sign( + 'HMAC', + key, + new TextEncoder().encode(`order:${orderId}`), + ); + return base64url(new Uint8Array(signature)); +} + +/** What a token looks like, before anything is computed for it. */ +export function isOrderToken(value: string): boolean { + return /^[A-Za-z0-9_-]{43}$/.test(value); +} + +/** + * Whether a token opens an order. Compared in time that does not depend on + * where the two first differ, so that a visitor learns nothing from how long + * a wrong guess took. + */ +export async function tokenOpens( + key: CryptoKey, + orderId: string, + token: string, +): Promise { + if (!isOrderToken(token)) { + return false; + } + const expected = await orderToken(key, orderId); + let difference = expected.length ^ token.length; + for (let index = 0; index < expected.length; index += 1) { + difference |= expected.charCodeAt(index) ^ token.charCodeAt(index); + } + return difference === 0; +} diff --git a/src/plugins/shop/lib/order-admin.ts b/src/plugins/shop/lib/order-admin.ts new file mode 100644 index 0000000..4910f1b --- /dev/null +++ b/src/plugins/shop/lib/order-admin.ts @@ -0,0 +1,435 @@ +/** + * What the admin does with orders, and with payments the shop could not + * keep. Mallok lists both from the manifest's panels; these are the panels' + * actions, each given the ids of the rows that were ticked. + * + * Money moves at Stripe before the books move here, never after: a refund is + * asked of Stripe and then recorded, so an order never reads "refunded" + * while the buyer waits for the money; a session is expired at Stripe and + * then its order cancelled, so a cancelled order cannot still be paid. Both + * Stripe calls are keyed, so pressing the button again after a failure + * halfway repeats nothing at Stripe and finishes the bookkeeping. + * + * A refusal answers 422 with a message the admin shows. What a change owes + * the buyer — an email — is queued as the order's follow-up job. + */ + +import type { PluginContext } from 'mallok/worker'; +import { FOLLOW_UP_JOB } from './order-follow-up.js'; +import { + cancelOrder, + fulfilOversold, + markDelivered, + refundOrder, + shipOrder, +} from './order-fulfilment.js'; +import type { OrderStatus } from './order-state.js'; +import { + createRefund, + expireCheckoutSession, + StripeRequestError, +} from './stripe-client.js'; + +/** + * A refund asked of Stripe, or the word that the payment had been refunded + * already — in Stripe's dashboard, say — which is as good for the books. + */ +async function refundAtStripe( + secretKey: string, + paymentIntentId: string, + reason?: 'requested_by_customer', +): Promise<{ id: string }> { + try { + return await createRefund(secretKey, { + paymentIntentId, + ...(reason === undefined ? {} : { reason }), + }); + } catch (error) { + if ( + error instanceof StripeRequestError && + error.code === 'charge_already_refunded' + ) { + return { id: REFUNDED_OUTSIDE }; + } + throw error; + } +} + +/** What a refund made outside the shop is recorded as: Stripe gave no id. */ +export const REFUNDED_OUTSIDE = 'refunded_outside_shop'; + +/** The most orders one action changes. */ +const ACTION_LIMIT = 20; + +/** The carriers offered by name (design §20, D18); `Other` asks for one. */ +export const CARRIERS = ['DHL', 'FedEx', 'UPS', 'Other'] as const; + +function refused(error: string, errors?: Record): Response { + return Response.json( + { error, ...(errors === undefined ? {} : { errors }) }, + { status: 422 }, + ); +} + +interface OrderRow { + id: string; + order_no: string; + status: OrderStatus; + stripe_payment_intent_id: string | null; + stripe_session_id: string | null; +} + +async function readOrders( + db: D1Database, + ids: readonly string[], +): Promise { + const { results } = await db + .prepare( + `SELECT id, order_no, status, stripe_payment_intent_id, stripe_session_id + FROM p_shop_order WHERE id IN (SELECT value FROM json_each(?)) + ORDER BY created_at`, + ) + .bind(JSON.stringify(ids.slice(0, ACTION_LIMIT))) + .all(); + return results; +} + +/** Queues what a change owes; the cron takes it up if this cannot. */ +async function owe(ctx: PluginContext, orderId: string): Promise { + try { + await ctx.enqueue(FOLLOW_UP_JOB, { orderId }); + } catch { + console.log( + JSON.stringify({ event: 'shop_follow_up_not_queued', orderId }), + ); + } +} + +/** What went wrong with each order that was not changed, for the admin. */ +function summary( + problems: readonly string[], + done: number, +): Response | undefined { + if (problems.length === 0) { + return undefined; + } + return refused( + `${done === 0 ? 'Nothing was changed' : `${done} changed`}. ${problems.join(' ')}`, + ); +} + +function why(order: OrderRow, needed: string): string { + return `${order.order_no} is ${order.status}: ${needed}.`; +} + +/** Ships one order: a tracking number and a carrier are required (D18). */ +export async function shipOrders( + ids: readonly string[], + ctx: PluginContext, + params: Readonly>, + now: Date = new Date(), +): Promise { + if (ids.length !== 1) { + return refused( + 'Ship one order at a time: each has its own tracking number.', + ); + } + const trackingNo = + typeof params.tracking_no === 'string' ? params.tracking_no.trim() : ''; + const chosen = typeof params.carrier === 'string' ? params.carrier : ''; + const other = + typeof params.carrier_other === 'string' ? params.carrier_other.trim() : ''; + if (trackingNo === '' || trackingNo.length > 100) { + return refused('A tracking number is required.', { + tracking_no: 'Enter the tracking number, at most 100 characters.', + }); + } + if (!(CARRIERS as readonly string[]).includes(chosen)) { + return refused('Choose a carrier.', { carrier: 'Choose a carrier.' }); + } + if (chosen === 'Other' && (other === '' || other.length > 100)) { + return refused('Name the carrier.', { + carrier_other: 'Name the carrier, at most 100 characters.', + }); + } + const [order] = await readOrders(ctx.db, ids); + if (order === undefined) { + return refused('That order no longer exists.'); + } + if (order.status !== 'paid') { + return refused(why(order, 'only a paid order can be shipped')); + } + try { + await shipOrder(ctx.db, { + orderId: order.id, + trackingNo, + carrier: chosen === 'Other' ? other : chosen, + now, + }); + } catch { + return refused(`${order.order_no} changed meanwhile. Nothing was changed.`); + } + await owe(ctx, order.id); + return undefined; +} + +export async function deliverOrders( + ids: readonly string[], + ctx: PluginContext, + now: Date = new Date(), +): Promise { + const problems: string[] = []; + let done = 0; + for (const order of await readOrders(ctx.db, ids)) { + if (order.status !== 'shipped') { + problems.push(why(order, 'only a shipped order can be marked delivered')); + continue; + } + try { + await markDelivered(ctx.db, { orderId: order.id, now }); + done += 1; + } catch { + problems.push(`${order.order_no} changed meanwhile.`); + } + } + return summary(problems, done); +} + +/** + * Cancels orders still waiting for their payment. Each one's Checkout + * session is expired at Stripe first, so it cannot be paid once cancelled; + * one that Stripe says is no longer open is looked at again — it may have + * just been paid — before anything is written. + */ +export async function cancelOrders( + ids: readonly string[], + ctx: PluginContext, + params: Readonly>, + now: Date = new Date(), +): Promise { + if (params.confirm !== true) { + return refused('Tick the box to confirm.', { + confirm: 'Tick the box to cancel these orders.', + }); + } + const secretKey = ctx.secrets.stripe_secret_key ?? ''; + const problems: string[] = []; + let done = 0; + for (const order of await readOrders(ctx.db, ids)) { + if (order.status !== 'pending') { + problems.push( + why( + order, + order.status === 'oversold' + ? 'refund it, or restock and fulfil it' + : 'only an order waiting for payment can be cancelled; refund a paid one', + ), + ); + continue; + } + if (order.stripe_session_id !== null) { + if (secretKey === '') { + problems.push( + `${order.order_no}: set the Stripe secret key first, so that its payment page can be closed.`, + ); + continue; + } + try { + const closed = await expireCheckoutSession( + secretKey, + order.stripe_session_id, + ); + if (closed === 'not_open') { + const [now2] = await readOrders(ctx.db, [order.id]); + if (now2 === undefined || now2.status !== 'pending') { + problems.push(`${order.order_no} was paid meanwhile.`); + continue; + } + } + } catch (error) { + problems.push( + `${order.order_no}: Stripe could not be reached (${error instanceof Error ? error.message : 'unknown'}). Try again.`, + ); + continue; + } + } + try { + await cancelOrder(ctx.db, { orderId: order.id, reason: 'seller', now }); + done += 1; + await owe(ctx, order.id); + } catch { + problems.push(`${order.order_no} changed meanwhile.`); + } + } + return summary(problems, done); +} + +/** Which way the stock goes when an order is refunded (D11). */ +export const RESTOCK_CHOICES = [ + 'Back to stock unless it has shipped', + 'Back to stock', + 'Leave the stock as it is', +] as const; + +function restockFor(choice: unknown, status: OrderStatus): boolean { + if (choice === RESTOCK_CHOICES[1]) { + return true; + } + if (choice === RESTOCK_CHOICES[2]) { + return false; + } + return status === 'paid' || status === 'oversold'; +} + +/** + * Refunds orders in full (D11): the money at Stripe first, then the order + * and, as chosen, its stock. + */ +export async function refundOrders( + ids: readonly string[], + ctx: PluginContext, + params: Readonly>, + now: Date = new Date(), +): Promise { + if (params.confirm !== true) { + return refused('Tick the box to confirm.', { + confirm: 'Tick the box to refund these orders in full.', + }); + } + const secretKey = ctx.secrets.stripe_secret_key ?? ''; + if (secretKey === '') { + return refused( + 'Set the Stripe secret key first: the refund is made at Stripe.', + ); + } + const problems: string[] = []; + let done = 0; + for (const order of await readOrders(ctx.db, ids)) { + if ( + !['paid', 'shipped', 'delivered', 'oversold'].includes(order.status) || + order.stripe_payment_intent_id === null + ) { + problems.push(why(order, 'only an order that was paid can be refunded')); + continue; + } + try { + await refundAtStripe( + secretKey, + order.stripe_payment_intent_id, + 'requested_by_customer', + ); + } catch (error) { + problems.push( + `${order.order_no}: Stripe did not refund it (${error instanceof Error ? error.message : 'unknown'}).`, + ); + continue; + } + try { + await refundOrder(ctx.db, { + orderId: order.id, + restock: restockFor(params.restock, order.status), + now, + }); + done += 1; + await owe(ctx, order.id); + } catch { + // The money has gone back; the order says so once this is pressed + // again, which asks Stripe for nothing new. + problems.push( + `${order.order_no} was refunded at Stripe but changed here meanwhile: refund it again to record it.`, + ); + } + } + return summary(problems, done); +} + +/** Fulfils oversold orders once their stock is back (D12). */ +export async function fulfilOrders( + ids: readonly string[], + ctx: PluginContext, + params: Readonly>, + now: Date = new Date(), +): Promise { + if (params.confirm !== true) { + return refused('Tick the box to confirm.', { + confirm: 'Tick the box once the stock is back.', + }); + } + const problems: string[] = []; + let done = 0; + for (const order of await readOrders(ctx.db, ids)) { + if (order.status !== 'oversold') { + problems.push(why(order, 'only an oversold order is fulfilled this way')); + continue; + } + try { + await fulfilOversold(ctx.db, { orderId: order.id, now }); + done += 1; + await owe(ctx, order.id); + } catch { + problems.push( + `${order.order_no}: there is not enough stock yet for every line. Restock it first.`, + ); + } + } + return summary(problems, done); +} + +/** + * Refunds payments the shop took and could not keep, and records each + * refund on its event. Keyed on the payment, as every refund is. + */ +export async function refundRefusedPayments( + ids: readonly string[], + ctx: PluginContext, + params: Readonly>, +): Promise { + if (params.confirm !== true) { + return refused('Tick the box to confirm.', { + confirm: 'Tick the box to refund these payments in full.', + }); + } + const secretKey = ctx.secrets.stripe_secret_key ?? ''; + if (secretKey === '') { + return refused( + 'Set the Stripe secret key first: the refund is made at Stripe.', + ); + } + const { results } = await ctx.db + .prepare( + `SELECT event_id, payment_intent_id, refund_id FROM p_shop_stripe_event + WHERE outcome = 'refused' + AND event_id IN (SELECT value FROM json_each(?))`, + ) + .bind(JSON.stringify(ids.slice(0, ACTION_LIMIT))) + .all<{ + event_id: string; + payment_intent_id: string; + refund_id: string | null; + }>(); + const problems: string[] = []; + let done = 0; + for (const row of results) { + if (row.refund_id !== null) { + continue; + } + try { + // No reason: the payment was neither a duplicate nor the buyer's + // request, and Stripe offers nothing else. + const refund = await refundAtStripe(secretKey, row.payment_intent_id); + await ctx.db + .prepare( + `UPDATE p_shop_stripe_event SET refund_id = ? + WHERE event_id = ? AND refund_id IS NULL`, + ) + .bind(refund.id, row.event_id) + .run(); + done += 1; + } catch (error) { + problems.push( + `${row.payment_intent_id}: not refunded (${error instanceof Error ? error.message : 'unknown'}).`, + ); + } + } + return summary(problems, done); +} diff --git a/src/plugins/shop/lib/order-follow-up.ts b/src/plugins/shop/lib/order-follow-up.ts new file mode 100644 index 0000000..c4e7252 --- /dev/null +++ b/src/plugins/shop/lib/order-follow-up.ts @@ -0,0 +1,403 @@ +/** + * Carrying out what the outbox says a change of an order still owes. + * + * Every change of an order writes its outbox row in its own batch + * (`outbox.ts`). This is what reads the rows back and does the rest: the + * buyer's email, the seller's, the purge of the product pages whose stock + * moved. It runs from a job the change queues (`FOLLOW_UP_JOB`), and the + * minute's cron takes up whatever a job left behind — a job that failed five + * times, or one that was never queued because the request stopped after its + * batch (design §20: Mallok's jobs, with the cron behind them). + * + * A row is claimed before its follow-up runs, so that a job and the cron + * that meet over it do not both send its email; a claim older than ten + * minutes is taken to belong to a runner that stopped. A row whose follow-up + * fails is let go and stops the rest of its order's rows: "shipped" must not + * reach the buyer before "confirmed". A row is marked handled once + * everything it owed has been handed over — to Mallok's email queue, which + * retries delivery itself — so it can be handled twice only if the marking + * is what fails, and then one email arrives twice; it is never lost. + * + * What each topic owes: + * + * order.paid buyer: confirmed. Seller: a new order, unless it was + * oversold first and the seller restocked it. Purge. + * order.oversold seller: refund it, or restock and fulfil it. + * payment.refused seller: this payment has to be refunded. + * order.shipped buyer: shipped, with the carrier and tracking number. + * order.refunded buyer: refunded. Purge, for the stock that came back. + * order.cancelled buyer: cancelled — only when the seller cancelled it, + * not when its payment page lapsed or gave way to + * another: the address was never proven to be theirs. + * order.delivered nothing. + */ + +import type { EmailMessage } from 'mallok/worker'; +import { orderLinkKey, orderToken } from './order-access.js'; +import { + cancellationEmail, + type EmailContent, + orderConfirmationEmail, + type RefusedBecause, + refundNotificationEmail, + sellerNewOrderEmail, + sellerOversoldEmail, + sellerRefundOwedEmail, + shippingNotificationEmail, +} from './order-email.js'; +import { getOrder, type OrderDetail } from './orders.js'; +import { markOutboxHandled, type OutboxTopic } from './outbox.js'; +import { orderLink } from './paths.js'; +import { productCacheTag, purgeOutcome } from './render-data.js'; + +/** The job a change of an order queues for what it owes. */ +export const FOLLOW_UP_JOB = 'order_follow_up'; + +/** How long a claim holds before it is taken to belong to a runner that stopped. */ +const CLAIM_HOLD_MS = 10 * 60 * 1000; + +/** What the runner needs of Mallok's context. */ +export interface FollowUpContext { + readonly db: D1Database; + readonly settings: Readonly>; + readonly site: { readonly defaultLocale: string }; + readonly sendEmail: (message: EmailMessage) => Promise; + readonly purgeTags?: (tags: readonly string[]) => Promise; +} + +interface Row { + id: string; + topic: OutboxTopic; + order_id: string; + ref: string | null; +} + +/** Where the seller is told; null when the shop has nowhere to tell them. */ +function sellerAddress( + settings: Readonly>, +): string | null { + const value = settings.inquiry_recipient; + return typeof value === 'string' && value.trim() !== '' ? value.trim() : null; +} + +function message( + to: string, + content: EmailContent, + replyTo?: string, +): EmailMessage { + return { + to, + subject: content.subject, + text: content.text, + html: content.html, + ...(replyTo === undefined ? {} : { replyTo }), + }; +} + +async function linkOf( + ctx: FollowUpContext, + order: OrderDetail, + now: Date, +): Promise { + if (order.siteOrigin === '') { + return undefined; + } + const token = await orderToken(await orderLinkKey(ctx.db, now), order.id); + return orderLink({ + origin: order.siteOrigin, + orderNo: order.orderNo, + token, + locale: order.locale, + defaultLocale: ctx.site.defaultLocale, + }); +} + +/** + * Purges the pages of every product on the order. Which of them changed is + * known only to the call that made the change; purging all of them is + * always safe. A purge that does not happen leaves the pages to expire, and + * is not a failure of the row. + */ +async function purgeOrderProducts( + ctx: FollowUpContext, + orderId: string, +): Promise { + if (ctx.purgeTags === undefined) { + return; + } + const { results } = await ctx.db + .prepare( + `SELECT DISTINCT v.product_group AS product_group + FROM p_shop_order_line AS l + JOIN p_shop_variant AS v ON v.id = l.variant_id + WHERE l.order_id = ?`, + ) + .bind(orderId) + .all<{ product_group: string }>(); + if (results.length === 0) { + return; + } + try { + const answer = await ctx.purgeTags( + results.map((row) => productCacheTag(row.product_group)), + ); + if (purgeOutcome(answer) === 'refused') { + console.log( + JSON.stringify({ event: 'shop_purge_failed', reason: 'refused' }), + ); + } + } catch { + console.log( + JSON.stringify({ event: 'shop_purge_failed', reason: 'threw' }), + ); + } +} + +/** Why a refused payment could not be kept, read from the order as it is. */ +function refusedBecause( + order: OrderDetail, + paymentIntentId: string, +): RefusedBecause { + if ( + order.stripePaymentIntentId !== null && + order.stripePaymentIntentId !== paymentIntentId + ) { + return 'already_paid'; + } + if (order.status === 'cancelled') { + return 'cancelled'; + } + return 'amount_mismatch'; +} + +/** Whether the order was oversold before it was paid: the seller restocked it. */ +async function wasOversold( + ctx: FollowUpContext, + orderId: string, +): Promise { + const row = await ctx.db + .prepare( + `SELECT 1 AS hit FROM p_shop_stripe_event + WHERE order_id = ? AND outcome = 'oversold' LIMIT 1`, + ) + .bind(orderId) + .first<{ hit: number }>(); + return row !== null; +} + +/** Does what one row owes. Throws when something it owes could not be handed over. */ +async function perform( + ctx: FollowUpContext, + row: Row, + now: Date, +): Promise { + const order = await getOrder(ctx.db, { id: row.order_id }); + if (order === null) { + // Nothing is left to tell anyone about. + return; + } + const seller = sellerAddress(ctx.settings); + + switch (row.topic) { + case 'order.paid': { + const link = await linkOf(ctx, order, now); + await ctx.sendEmail( + message(order.email, orderConfirmationEmail(order, link)), + ); + if (seller !== null && !(await wasOversold(ctx, order.id))) { + await ctx.sendEmail( + message(seller, sellerNewOrderEmail(order), order.email), + ); + } + await purgeOrderProducts(ctx, order.id); + return; + } + case 'order.oversold': + if (seller !== null) { + await ctx.sendEmail( + message(seller, sellerOversoldEmail(order), order.email), + ); + } + return; + case 'payment.refused': + if (seller !== null && row.ref !== null) { + await ctx.sendEmail( + message( + seller, + sellerRefundOwedEmail({ + orderNo: order.orderNo, + paymentIntentId: row.ref, + because: refusedBecause(order, row.ref), + }), + ), + ); + } + return; + case 'order.shipped': { + const link = await linkOf(ctx, order, now); + await ctx.sendEmail( + message( + order.email, + shippingNotificationEmail({ + orderNo: order.orderNo, + locale: order.locale, + trackingNo: order.trackingNo, + carrier: order.carrier, + ...(link === undefined ? {} : { orderUrl: link }), + }), + ), + ); + return; + } + case 'order.refunded': { + const link = await linkOf(ctx, order, now); + await ctx.sendEmail( + message( + order.email, + refundNotificationEmail({ + orderNo: order.orderNo, + locale: order.locale, + currency: order.currency, + totalMinor: order.totalMinor, + ...(link === undefined ? {} : { orderUrl: link }), + }), + ), + ); + await purgeOrderProducts(ctx, order.id); + return; + } + case 'order.cancelled': + if (row.ref === 'seller') { + await ctx.sendEmail( + message( + order.email, + cancellationEmail({ orderNo: order.orderNo, locale: order.locale }), + ), + ); + } + return; + case 'order.delivered': + return; + } +} + +/** + * Takes up a row for this runner. False when another has it, or it was + * handled meanwhile. + */ +async function claim(db: D1Database, id: string, now: Date): Promise { + const row = await db + .prepare( + `UPDATE p_shop_outbox SET claimed_at = ? + WHERE id = ? AND handled_at IS NULL + AND (claimed_at IS NULL OR claimed_at <= ?) + RETURNING id`, + ) + .bind( + now.toISOString(), + id, + new Date(now.getTime() - CLAIM_HOLD_MS).toISOString(), + ) + .first<{ id: string }>(); + return row !== null; +} + +export interface FollowUpOutcome { + readonly handled: number; + readonly failed: number; +} + +/** + * Carries out the rows still owed — one order's, or any — oldest first. + * + * `committedBefore` leaves out rows newer than it: the cron passes it so as + * not to race the job a change has just queued for its own rows. + */ +export async function runFollowUps( + ctx: FollowUpContext, + input: { + readonly now: Date; + readonly limit: number; + readonly orderId?: string; + readonly committedBefore?: Date; + }, +): Promise { + const { now } = input; + const { results } = await ctx.db + .prepare( + `SELECT id, topic, order_id, ref FROM p_shop_outbox + WHERE handled_at IS NULL + AND (claimed_at IS NULL OR claimed_at <= ?) + AND (? IS NULL OR order_id = ?) + AND (? IS NULL OR created_at <= ?) + ORDER BY seq LIMIT ?`, + ) + .bind( + new Date(now.getTime() - CLAIM_HOLD_MS).toISOString(), + input.orderId ?? null, + input.orderId ?? null, + input.committedBefore?.toISOString() ?? null, + input.committedBefore?.toISOString() ?? null, + input.limit, + ) + .all(); + + let handled = 0; + let failed = 0; + // An order one of whose rows could not be carried out: its later rows wait. + const held = new Set(); + for (const row of results) { + if (held.has(row.order_id)) { + continue; + } + if (!(await claim(ctx.db, row.id, now))) { + held.add(row.order_id); + continue; + } + try { + await perform(ctx, row, now); + } catch (error) { + held.add(row.order_id); + failed += 1; + await ctx.db + .prepare('UPDATE p_shop_outbox SET claimed_at = NULL WHERE id = ?') + .bind(row.id) + .run(); + // The topic and the order's id, which name nobody. + console.log( + JSON.stringify({ + event: 'shop_follow_up_failed', + topic: row.topic, + orderId: row.order_id, + reason: error instanceof Error ? error.name : 'unknown', + }), + ); + continue; + } + await markOutboxHandled(ctx.db, [row.id], now); + handled += 1; + } + return { handled, failed }; +} + +/** The job: one order's rows. Throws when one failed, so Mallok tries again. */ +export async function followUpJob( + payload: unknown, + ctx: FollowUpContext, + now: Date = new Date(), +): Promise { + const orderId = + payload !== null && + typeof payload === 'object' && + typeof (payload as { orderId?: unknown }).orderId === 'string' + ? (payload as { orderId: string }).orderId + : null; + if (orderId === null) { + // Not a payload this plugin queues: nothing to retry it for. + return; + } + const outcome = await runFollowUps(ctx, { now, limit: 20, orderId }); + if (outcome.failed > 0) { + throw new Error(`${outcome.failed} follow-up(s) of an order failed`); + } +} diff --git a/src/plugins/shop/lib/order-fulfilment.ts b/src/plugins/shop/lib/order-fulfilment.ts index 8584434..a841bab 100644 --- a/src/plugins/shop/lib/order-fulfilment.ts +++ b/src/plugins/shop/lib/order-fulfilment.ts @@ -139,6 +139,8 @@ export type CancelReason = | 'expired' /** Stripe would not open a Checkout session for it. */ | 'failed' + /** The buyer checked the same cart out again, and this one gave way. */ + | 'replaced' /** The seller cancelled it. */ | 'seller'; diff --git a/src/plugins/shop/lib/orders.ts b/src/plugins/shop/lib/orders.ts index 39e3685..f6a7ce2 100644 --- a/src/plugins/shop/lib/orders.ts +++ b/src/plugins/shop/lib/orders.ts @@ -110,8 +110,8 @@ export async function createPendingOrder( readonly taxId?: string; readonly shippingZone?: string; readonly taxMode?: TaxMode; - /** The digest of the secret in the buyer's link to their order. */ - readonly accessHash?: string | null; + /** The site's address as the buyer checked out on it. */ + readonly siteOrigin?: string; readonly orderNoPrefix?: string; }, ): Promise<{ id: string; orderNo: string; totalMinor: number }> { @@ -156,7 +156,7 @@ export async function createPendingOrder( `INSERT INTO p_shop_order (id, order_no, status, currency, subtotal_minor, shipping_minor, tax_minor, total_minor, email, shipping_address, locale, - cart_id, company, tax_id, shipping_zone, tax_mode, access_hash, + cart_id, company, tax_id, shipping_zone, tax_mode, site_origin, created_at, updated_at) VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) @@ -176,7 +176,7 @@ export async function createPendingOrder( input.taxId ?? '', input.shippingZone ?? '', input.taxMode ?? 'none', - input.accessHash ?? null, + input.siteOrigin ?? '', nowIso, nowIso, ), @@ -240,6 +240,8 @@ export interface OrderDetail { readonly cartId: string | null; readonly stripePaymentIntentId: string | null; readonly stripeSessionId: string | null; + /** The site's address as the buyer checked out on it; '' when unknown. */ + readonly siteOrigin: string; readonly createdAt: string; readonly updatedAt: string; readonly lines: readonly OrderLine[]; @@ -271,6 +273,7 @@ interface OrderRow { cart_id: string | null; stripe_payment_intent_id: string | null; stripe_session_id: string | null; + site_origin: string; created_at: string; updated_at: string; } @@ -320,7 +323,7 @@ export async function getOrder( tax_minor, total_minor, email, shipping_address, locale, tracking_no, carrier, company, tax_id, shipping_zone, tax_mode, cart_id, stripe_payment_intent_id, - stripe_session_id, created_at, updated_at + stripe_session_id, site_origin, created_at, updated_at FROM p_shop_order WHERE ${column} = ?`, ) .bind(key), @@ -377,6 +380,7 @@ export async function getOrder( cartId: row.cart_id, stripePaymentIntentId: row.stripe_payment_intent_id, stripeSessionId: row.stripe_session_id, + siteOrigin: row.site_origin, createdAt: row.created_at, updatedAt: row.updated_at, lines: ((lineResult?.results ?? []) as LineRow[]).map((line) => ({ @@ -601,6 +605,30 @@ function variantsOfOrder(db: D1Database, orderId: string): D1PreparedStatement { .bind(orderId); } +/** + * Takes what was ordered out of the cart the order came from, once the + * payment is in (design §20, D10): not before, so that a payment that fails + * does not cost the buyer their cart, and not after, so that a buyer who + * comes back from paying does not find the same lines waiting to be bought + * again. Only the order's own variants: what was added since stays. + */ +function emptyOrderedCart( + db: D1Database, + orderId: string, + condition: SqlCondition, +): D1PreparedStatement { + return db + .prepare( + `DELETE FROM p_shop_cart_line + WHERE cart_id = (SELECT cart_id FROM p_shop_order WHERE id = ?) + AND variant_id IN ( + SELECT variant_id FROM p_shop_order_line WHERE order_id = ? + ) + AND ${condition.sql}`, + ) + .bind(orderId, orderId, ...condition.binds); +} + /** The record that a payment was acted on, and how. */ function recordEvent( db: D1Database, @@ -627,7 +655,7 @@ function recordEvent( } /** - * The payment itself: five writes between two readings of the stock. + * The payment itself: six writes between two readings of the stock. * * Returns null when the order had already left `from` by the time the batch * ran — a delivery racing this one got there first — in which case nothing @@ -687,6 +715,7 @@ async function writePaid( .bind(nowIso, orderId, orderId, from), // What is owed because of this payment, committed with it. orderChangedOutbox(db, { orderId, from, to: 'paid', now: input.now }), + emptyOrderedCart(db, orderId, stillInStatus), // Last: every statement above tests the status this one changes. db .prepare( @@ -702,7 +731,7 @@ async function writePaid( variantsOfOrder(db, orderId), ]); - if ((results[5]?.results ?? []).length === 0) { + if ((results[6]?.results ?? []).length === 0) { return null; } return { @@ -710,7 +739,7 @@ async function writePaid( status: 'paid', availabilityChanged: changedProductGroups( (results[0]?.results ?? []) as unknown as StockRow[], - (results[6]?.results ?? []) as unknown as StockRow[], + (results[7]?.results ?? []) as unknown as StockRow[], ), }; } @@ -750,6 +779,11 @@ async function writeOversold( now: input.now, andIf: stillShort, }), + // Paid for, so it is out of the cart as a paid order's would be. + emptyOrderedCart(db, orderId, { + sql: `${ORDER_STILL_IN_STATUS} AND ${ORDER_SHORT_OF_STOCK}`, + binds: [orderId, from, orderId], + }), db .prepare( `UPDATE p_shop_order @@ -765,7 +799,7 @@ async function writeOversold( orderId, ), ]); - return (results[2]?.results ?? []).length > 0; + return (results[3]?.results ?? []).length > 0; } /** diff --git a/src/plugins/shop/lib/paths.ts b/src/plugins/shop/lib/paths.ts index 5dd7ee6..c44140d 100644 --- a/src/plugins/shop/lib/paths.ts +++ b/src/plugins/shop/lib/paths.ts @@ -18,6 +18,18 @@ export const CART_UPDATE_ROUTE = 'cart/update'; /** Where the cart page's form posts to send the cart as an inquiry. */ export const CART_INQUIRY_ROUTE = 'cart/inquiry'; +/** The checkout page: where the goods go, and the button that pays. */ +export const CHECKOUT_ROUTE = 'checkout'; + +/** Where the checkout page's form posts to place the order. */ +export const CHECKOUT_PLACE_ROUTE = 'checkout/place'; + +/** An order's own page, at `order/`. */ +export const ORDER_ROUTE = 'order'; + +/** Where Stripe delivers its events. Not a page: no language segment. */ +export const STRIPE_WEBHOOK_ROUTE = 'stripe/webhook'; + export function shopPath( route: string, locale: string, @@ -27,3 +39,23 @@ export function shopPath( ? `${CART_COOKIE_PATH}/${route}` : `${CART_COOKIE_PATH}/${locale}/${route}`; } + +/** + * The buyer's link to their order, whole: the site's address, the order's + * page in the language it was placed in, and the secret that opens it. + * An order number is letters, digits and hyphens, so it needs no escaping. + */ +export function orderLink(input: { + readonly origin: string; + readonly orderNo: string; + readonly token: string; + readonly locale: string; + readonly defaultLocale: string; +}): string { + const path = shopPath( + `${ORDER_ROUTE}/${encodeURIComponent(input.orderNo)}`, + input.locale, + input.defaultLocale, + ); + return `${input.origin}${path}?k=${encodeURIComponent(input.token)}`; +} diff --git a/src/plugins/shop/lib/scheduled.ts b/src/plugins/shop/lib/scheduled.ts index a120aa2..8a460a4 100644 --- a/src/plugins/shop/lib/scheduled.ts +++ b/src/plugins/shop/lib/scheduled.ts @@ -3,14 +3,18 @@ * * Mallok runs one cron for the whole site, and every plugin's `scheduled` * hook shares that invocation's CPU budget (10 ms on the Workers Free plan). - * So a tick does **one** small piece of work and returns: a repricing run in - * progress goes first, then a rate refresh if one is due, then clearing - * expired carts. Whatever is left waits for the next minute. + * So a tick does **one** small piece of work and returns: what an order's + * change still owes and its job left behind goes first, then closing orders + * whose payment page lapsed with no word from Stripe, then a repricing run + * in progress, then a rate refresh if one is due, then clearing expired + * carts. Whatever is left waits for the next minute. */ import { deleteExpiredCarts } from './cart.js'; import { BASE_CURRENCY, CURRENCIES } from './currency.js'; import { fetchEcbRates, ratesFromBase } from './ecb.js'; +import { type FollowUpContext, runFollowUps } from './order-follow-up.js'; +import { cancelOrder } from './order-fulfilment.js'; import { pricingRulesFromSettings } from './pricing.js'; import { readRates, repriceChunk, storeRatesStatements } from './rates.js'; import { productCacheTag, purgeOutcome } from './render-data.js'; @@ -36,6 +40,28 @@ const REPRICE_CHUNK = 50; /** Expired carts deleted per cleanup. */ const CART_CLEANUP_LIMIT = 50; +/** + * How old an outbox row is before the cron takes it up: its own job runs + * within a minute or two, and the cron is for what that job left behind. + */ +const FOLLOW_UP_GRACE_MS = 5 * 60 * 1000; + +/** Outbox rows carried out per tick. Each is a read and an email or two. */ +const FOLLOW_UP_LIMIT = 5; + +const ORDER_SWEEP_INTERVAL_MS = 10 * 60 * 1000; + +/** + * How long after its payment page lapsed an order is closed by the cron. + * Stripe's own word — `checkout.session.expired` — closes it sooner; this is + * for a word that never came, and leaves time for a payment made in the last + * moment whose word is late. + */ +const LAPSED_GRACE_MS = 60 * 60 * 1000; + +/** Orders closed per sweep. */ +const ORDER_SWEEP_LIMIT = 10; + export type TickOutcome = | { readonly kind: 'repriced'; @@ -56,6 +82,12 @@ export type TickOutcome = } | { readonly kind: 'rates_failed'; readonly reason: string } | { readonly kind: 'carts_cleaned'; readonly deleted: number } + | { + readonly kind: 'follow_ups'; + readonly handled: number; + readonly failed: number; + } + | { readonly kind: 'orders_lapsed'; readonly cancelled: number } | { readonly kind: 'idle' }; function elapsed(since: string | undefined, now: Date): number { @@ -66,12 +98,48 @@ function elapsed(since: string | undefined, now: Date): number { return Number.isNaN(then) ? Number.POSITIVE_INFINITY : now.getTime() - then; } +/** + * Orders still waiting for a payment that can no longer come: their page + * lapsed an hour ago, or none was recorded for them and they are two hours + * old — a page lives one. + */ +async function closeLapsedOrders(db: D1Database, now: Date): Promise { + const { results } = await db + .prepare( + `SELECT id FROM p_shop_order + WHERE status = 'pending' + AND ((stripe_session_expires_at IS NOT NULL + AND stripe_session_expires_at <= ?) + OR (stripe_session_expires_at IS NULL AND created_at <= ?)) + ORDER BY created_at LIMIT ?`, + ) + .bind( + new Date(now.getTime() - LAPSED_GRACE_MS).toISOString(), + new Date(now.getTime() - 2 * LAPSED_GRACE_MS).toISOString(), + ORDER_SWEEP_LIMIT, + ) + .all<{ id: string }>(); + let cancelled = 0; + for (const row of results) { + try { + await cancelOrder(db, { orderId: row.id, reason: 'expired', now }); + cancelled += 1; + } catch { + // Paid meanwhile: it is no longer waiting. + } + } + return cancelled; +} + export async function runScheduledTick( ctx: { readonly db: D1Database; readonly settings: Readonly>; /** Purges the shop's own cache tags; absent where there is no cache. */ readonly purgeTags?: (tags: readonly string[]) => Promise; + /** Sends an email; absent where a tick is run for its pricing only. */ + readonly sendEmail?: FollowUpContext['sendEmail']; + readonly site?: FollowUpContext['site']; }, deps: { readonly fetch?: typeof fetch; @@ -80,9 +148,47 @@ export async function runScheduledTick( ): Promise { const { db } = ctx; const now = (deps.now ?? (() => new Date()))(); + + // 1. What changes of orders still owe, that their own jobs left behind. + if (ctx.sendEmail !== undefined && ctx.site !== undefined) { + const outcome = await runFollowUps( + { + db, + settings: ctx.settings, + site: ctx.site, + sendEmail: ctx.sendEmail, + ...(ctx.purgeTags === undefined ? {} : { purgeTags: ctx.purgeTags }), + }, + { + now, + limit: FOLLOW_UP_LIMIT, + committedBefore: new Date(now.getTime() - FOLLOW_UP_GRACE_MS), + }, + ); + if (outcome.handled + outcome.failed > 0) { + return { kind: 'follow_ups', ...outcome }; + } + } + const state = await readState(db); - // 1. A repricing run in progress: do the next chunk and nothing else. + // 2. Orders whose payment page lapsed with no word from Stripe. + if ( + elapsed(state.get(STATE_KEYS.ordersSweptAt), now) >= ORDER_SWEEP_INTERVAL_MS + ) { + await setStateStatement( + db, + STATE_KEYS.ordersSweptAt, + now.toISOString(), + now, + ).run(); + const cancelled = await closeLapsedOrders(db, now); + if (cancelled > 0) { + return { kind: 'orders_lapsed', cancelled }; + } + } + + // 3. A repricing run in progress: do the next chunk and nothing else. const cursor = state.get(STATE_KEYS.repriceCursor); if (cursor !== undefined) { const result = await repriceChunk(db, { @@ -125,7 +231,7 @@ export async function runScheduledTick( }; } - // 2. A rate refresh, when one is due. + // 4. A rate refresh, when one is due. if ( elapsed(state.get(STATE_KEYS.ratesAttemptedAt), now) >= RATES_INTERVAL_MS ) { @@ -172,7 +278,7 @@ export async function runScheduledTick( } } - // 3. Housekeeping. + // 5. Housekeeping. if ( elapsed(state.get(STATE_KEYS.cartsCleanedAt), now) >= CART_CLEANUP_INTERVAL_MS diff --git a/src/plugins/shop/lib/state.ts b/src/plugins/shop/lib/state.ts index ab8a71d..658e5ba 100644 --- a/src/plugins/shop/lib/state.ts +++ b/src/plugins/shop/lib/state.ts @@ -3,7 +3,8 @@ * * It exists for the scheduled work, which runs once a minute and has to * remember across ticks when rates were last tried and where a chunked - * repricing run has got to. + * repricing run has got to — and to keep the key buyers' order links are + * signed with, which a site export leaves behind with the rest of it. */ export const STATE_KEYS = { @@ -13,6 +14,10 @@ export const STATE_KEYS = { repriceCursor: 'reprice_cursor', /** ISO time expired carts were last cleared. */ cartsCleanedAt: 'carts_cleaned_at', + /** The key buyers' order links are signed with (`order-access.ts`). */ + orderLinkKey: 'order_link_key', + /** ISO time orders whose payment page lapsed were last looked for. */ + ordersSweptAt: 'orders_swept_at', } as const; export async function readState( diff --git a/src/plugins/shop/lib/stripe-check.ts b/src/plugins/shop/lib/stripe-check.ts new file mode 100644 index 0000000..974e95c --- /dev/null +++ b/src/plugins/shop/lib/stripe-check.ts @@ -0,0 +1,78 @@ +/** + * The admin's "Test" buttons beside the two Stripe secrets. + * + * Read-only, as Mallok asks of a check: the secret key is tried on a read of + * the account's balance, and the signing secret, which only Stripe's own + * deliveries can prove, is checked for its shape. Only the verdict leaves + * the Worker, never the secret. + */ + +import type { PluginContext, PluginSecretVerdict } from 'mallok/worker'; +import { STRIPE_API_VERSION } from './stripe-client.js'; + +export async function checkStripeSecretKey( + ctx: Pick, + fetchImpl: typeof fetch = fetch, +): Promise { + const key = ctx.secrets.stripe_secret_key ?? ''; + if (key === '') { + return { ok: false, message: 'Not set.' }; + } + const shape = /^(sk|rk)_(test|live)_[A-Za-z0-9]+$/.exec(key); + if (shape === null) { + return { + ok: false, + message: + 'This is not a secret key: one begins sk_test_, sk_live_, rk_test_ or rk_live_. A publishable key (pk_) cannot take payments.', + }; + } + const mode = shape[2] === 'live' ? 'live mode' : 'test mode'; + let status = 0; + try { + const response = await fetchImpl('https://api.stripe.com/v1/balance', { + headers: { + Authorization: `Bearer ${key}`, + 'Stripe-Version': STRIPE_API_VERSION, + }, + }); + status = response.status; + } catch { + return { ok: false, message: 'Stripe could not be reached. Try again.' }; + } + if (status === 200) { + return { ok: true, message: `Stripe accepts this key (${mode}).` }; + } + if (status === 401) { + return { ok: false, message: 'Stripe does not accept this key.' }; + } + if (status === 403) { + return { + ok: true, + message: `Stripe accepts this restricted key (${mode}) but it may not read the balance. Make sure it may write Checkout Sessions, Customers and Refunds.`, + }; + } + return { + ok: false, + message: `Stripe could not be asked (status ${status}). Try again.`, + }; +} + +export async function checkStripeWebhookSecret( + ctx: Pick, +): Promise { + const secret = ctx.secrets.stripe_webhook_secret ?? ''; + if (secret === '') { + return { ok: false, message: 'Not set.' }; + } + return /^whsec_[A-Za-z0-9]+$/.test(secret) + ? { + ok: true, + message: + 'This is shaped like a signing secret. Only a delivery from Stripe proves it: send a test event from the webhook endpoint in Stripe.', + } + : { + ok: false, + message: + 'A signing secret begins whsec_. It is shown on the webhook endpoint in Stripe, not with the API keys.', + }; +} diff --git a/src/plugins/shop/migrations/0004_checkout.sql b/src/plugins/shop/migrations/0004_checkout.sql index bdb9974..1010cd4 100644 --- a/src/plugins/shop/migrations/0004_checkout.sql +++ b/src/plugins/shop/migrations/0004_checkout.sql @@ -10,9 +10,10 @@ -- before: a payment that fails must not cost the buyer their cart ALTER TABLE p_shop_order ADD COLUMN cart_id TEXT; --- A digest of the secret in the link the buyer is sent to follow their --- order. The secret itself is in the link and nowhere in the database -ALTER TABLE p_shop_order ADD COLUMN access_hash TEXT; +-- The site's address as the buyer checked out on it, which is where the +-- links in their emails point: an email is sent by a job, which has no +-- request to take an address from +ALTER TABLE p_shop_order ADD COLUMN site_origin TEXT NOT NULL DEFAULT ''; -- Who is buying: the shop sells to businesses ALTER TABLE p_shop_order ADD COLUMN company TEXT NOT NULL DEFAULT ''; @@ -70,3 +71,78 @@ CREATE TABLE IF NOT EXISTS p_shop_shipping_rate ( OR (typeof(free_over_minor) = 'integer' AND free_over_minor > 0)), PRIMARY KEY (zone_id, currency) ); + +-- When a runner took up an outbox row. Two at once — the request that made +-- the change and the minute's tick — must not both send its emails, so a +-- row is claimed before its follow-up runs, and a claim is let go after ten +-- minutes in case its runner stopped +ALTER TABLE p_shop_outbox ADD COLUMN claimed_at TEXT; + +-- The orders as the admin lists them. A table panel shows a column as it is +-- stored, so the amounts are spelled out here, in whole minor units divided +-- without a float, and the address is read out of its JSON +CREATE VIEW IF NOT EXISTS p_shop_order_admin AS +SELECT + o.id, + o.order_no, + o.status, + o.created_at, + o.updated_at, + o.email, + o.company, + COALESCE(json_extract(o.shipping_address, '$.recipient'), '') AS recipient, + COALESCE(json_extract(o.shipping_address, '$.country'), '') AS country, + COALESCE(json_extract(o.shipping_address, '$.phone'), '') AS phone, + trim( + COALESCE(json_extract(o.shipping_address, '$.line1'), '') || ', ' || + COALESCE(NULLIF(json_extract(o.shipping_address, '$.line2'), '') || ', ', '') || + COALESCE(json_extract(o.shipping_address, '$.postalCode'), '') || ' ' || + COALESCE(json_extract(o.shipping_address, '$.city'), '') || + COALESCE(', ' || NULLIF(json_extract(o.shipping_address, '$.state'), ''), '') || ', ' || + COALESCE(json_extract(o.shipping_address, '$.country'), '') + ) AS address, + o.currency, + o.currency || ' ' || (o.subtotal_minor / 100) || '.' || substr('0' || (o.subtotal_minor % 100), -2) AS subtotal, + o.currency || ' ' || (o.shipping_minor / 100) || '.' || substr('0' || (o.shipping_minor % 100), -2) AS shipping, + o.currency || ' ' || (o.tax_minor / 100) || '.' || substr('0' || (o.tax_minor % 100), -2) AS tax, + o.currency || ' ' || (o.total_minor / 100) || '.' || substr('0' || (o.total_minor % 100), -2) AS total, + o.shipping_zone, + o.tax_id, + o.tax_mode, + o.tracking_no, + o.carrier, + o.locale, + o.stripe_payment_intent_id, + (SELECT COUNT(*) FROM p_shop_stripe_event AS e + WHERE e.order_id = o.id AND e.outcome = 'refused' AND e.refund_id IS NULL) AS refunds_owed +FROM p_shop_order AS o; + +-- The order's lines as the admin lists them, amounts spelled out the same way +CREATE VIEW IF NOT EXISTS p_shop_order_line_admin AS +SELECT + l.id, + l.order_id, + l.sku_snapshot AS sku, + l.name_snapshot AS name, + l.quantity, + o.currency || ' ' || (l.unit_price_minor / 100) || '.' || substr('0' || (l.unit_price_minor % 100), -2) AS unit_price, + o.currency || ' ' || ((l.unit_price_minor * l.quantity) / 100) || '.' || substr('0' || ((l.unit_price_minor * l.quantity) % 100), -2) AS line_total +FROM p_shop_order_line AS l +JOIN p_shop_order AS o ON o.id = l.order_id; + +-- Payments the shop took and could not keep: for a cancelled order, one paid +-- twice, one that did not come to its total. Each has to be refunded by a +-- person, and the refund is recorded on the event +CREATE VIEW IF NOT EXISTS p_shop_refused_payment AS +SELECT + e.event_id AS id, + e.order_id, + COALESCE(o.order_no, '') AS order_no, + COALESCE(o.status, '') AS order_status, + e.payment_intent_id, + e.processed_at, + e.refund_id, + CASE WHEN e.refund_id IS NULL THEN 'to_refund' ELSE 'refunded' END AS state +FROM p_shop_stripe_event AS e +LEFT JOIN p_shop_order AS o ON o.id = e.order_id +WHERE e.outcome = 'refused'; diff --git a/src/plugins/shop/plugin.json b/src/plugins/shop/plugin.json index 9a1337c..41e48a5 100644 --- a/src/plugins/shop/plugin.json +++ b/src/plugins/shop/plugin.json @@ -2,7 +2,7 @@ "id": "shop", "name": "Shop", "version": "0.1.0", - "description": "Variants, prices in several currencies, stock, minimum order quantities, a cart and the cart sent as an inquiry, for a Mallok site.", + "description": "Variants, prices in several currencies, stock, minimum order quantities, a cart, the cart sent as an inquiry, and checkout with Stripe, for a Mallok site.", "pluginApi": 2, "hooks": ["scheduled", "renderData", "onContentDelete"], "routes": [ @@ -22,6 +22,30 @@ "path": "cart/inquiry", "method": "POST", "rateLimit": "strict" + }, + { + "path": "checkout", + "method": "GET", + "render": "page", + "layout": "shop/checkout", + "rateLimit": "relaxed" + }, + { + "path": "checkout/place", + "method": "POST", + "rateLimit": "strict" + }, + { + "path": "order/:orderNo", + "method": "GET", + "render": "page", + "layout": "shop/order", + "rateLimit": "relaxed" + }, + { + "path": "stripe/webhook", + "method": "POST", + "body": "raw" } ], "settings": { @@ -78,6 +102,12 @@ "choices": ["none", "stripe"], "default": "none", "group": "Orders" + }, + "terms_path": { + "type": "string", + "label": "Terms page", + "help": "A page on this site, such as /terms. When set, a buyer ticks that they accept it before paying, and the box links to it.", + "group": "Orders" } }, "panels": [ @@ -394,6 +424,229 @@ "help": "Lower first in the list a buyer chooses a country from." } } + }, + { + "id": "orders", + "label": "Orders", + "type": "table", + "table": "p_shop_order_admin", + "columns": [ + { + "field": "order_no", + "label": "Number", + "sortable": true + }, + { + "field": "created_at", + "label": "Placed", + "type": "datetime", + "sortable": true + }, + { + "field": "company", + "label": "Company", + "sortable": true + }, + { + "field": "email", + "label": "Email", + "type": "email" + }, + { + "field": "country", + "label": "Country" + }, + { + "field": "total", + "label": "Total" + }, + { + "field": "status", + "label": "Status", + "type": "badge" + }, + { + "field": "refunds_owed", + "label": "Refunds owed" + } + ], + "filters": ["status"], + "search": ["order_no", "company", "email", "recipient"], + "detail": [ + "recipient", + "phone", + "address", + "tax_id", + "subtotal", + "shipping", + "tax", + "shipping_zone", + "tax_mode", + "carrier", + "tracking_no", + "locale", + "stripe_payment_intent_id", + "updated_at" + ], + "orderBy": "created_at", + "related": [ + { + "id": "lines", + "label": "Lines", + "table": "p_shop_order_line_admin", + "foreignKey": "order_id", + "orderBy": "sku", + "columns": [ + { + "field": "sku", + "label": "SKU" + }, + { + "field": "name", + "label": "Product" + }, + { + "field": "quantity", + "label": "Quantity" + }, + { + "field": "unit_price", + "label": "Unit price" + }, + { + "field": "line_total", + "label": "Total" + } + ] + } + ], + "actions": [ + { + "id": "order_ship", + "label": "Mark shipped", + "params": { + "tracking_no": { + "type": "string", + "label": "Tracking number", + "required": true + }, + "carrier": { + "type": "select", + "label": "Carrier", + "choices": ["DHL", "FedEx", "UPS", "Other"], + "required": true + }, + "carrier_other": { + "type": "string", + "label": "Carrier, if Other", + "help": "The carrier's name, when it is not one of the list." + } + } + }, + { + "id": "order_deliver", + "label": "Mark delivered" + }, + { + "id": "order_fulfil", + "label": "Fulfil an oversold order", + "params": { + "confirm": { + "type": "boolean", + "label": "The stock is back. Take it for these orders now and make them paid, ready to ship.", + "required": true + } + } + }, + { + "id": "order_refund", + "label": "Refund in full", + "params": { + "restock": { + "type": "select", + "label": "Stock", + "choices": [ + "Back to stock unless it has shipped", + "Back to stock", + "Leave the stock as it is" + ], + "default": "Back to stock unless it has shipped", + "required": true, + "help": "What the order took from stock. Goods that have shipped are usually still with the buyer." + }, + "confirm": { + "type": "boolean", + "label": "Refund these orders in full at Stripe. This cannot be undone.", + "required": true + } + } + }, + { + "id": "order_cancel", + "label": "Cancel unpaid", + "params": { + "confirm": { + "type": "boolean", + "label": "Cancel these unpaid orders. Their payment pages are closed first, and each buyer is told by email.", + "required": true + } + } + } + ] + }, + { + "id": "refused-payments", + "label": "Refused payments", + "type": "table", + "table": "p_shop_refused_payment", + "columns": [ + { + "field": "order_no", + "label": "Order", + "sortable": true + }, + { + "field": "processed_at", + "label": "Received", + "type": "datetime", + "sortable": true + }, + { + "field": "order_status", + "label": "Order status", + "type": "badge" + }, + { + "field": "payment_intent_id", + "label": "Payment" + }, + { + "field": "state", + "label": "State", + "type": "badge" + }, + { + "field": "refund_id", + "label": "Refund" + } + ], + "filters": ["state"], + "search": ["order_no", "payment_intent_id"], + "detail": [], + "orderBy": "processed_at", + "actions": [ + { + "id": "payment_refund", + "label": "Refund", + "params": { + "confirm": { + "type": "boolean", + "label": "Refund these payments in full at Stripe. This cannot be undone.", + "required": true + } + } + } + ] } ], "secrets": { diff --git a/src/plugins/shop/routes/cart.ts b/src/plugins/shop/routes/cart.ts index af7ce1e..58874ed 100644 --- a/src/plugins/shop/routes/cart.ts +++ b/src/plugins/shop/routes/cart.ts @@ -48,6 +48,7 @@ import { type VariantRow, } from '../lib/cart-pricing.js'; import { cartView } from '../lib/cart-view.js'; +import { stripeKeys } from '../lib/checkout.js'; import { cartCookieHeader, readCartCookie } from '../lib/cookie.js'; import { type Currency, @@ -64,8 +65,10 @@ import { CART_INQUIRY_ROUTE, CART_ROUTE, CART_UPDATE_ROUTE, + CHECKOUT_ROUTE, shopPath, } from '../lib/paths.js'; + import { INQUIRY_FIELD_PARAM, INQUIRY_PARAM, @@ -149,12 +152,14 @@ function paths(ctx: PluginRequestContext): { cart: string; update: string; inquiry: string; + checkout: string; } { const { defaultLocale } = ctx.site; return { cart: shopPath(CART_ROUTE, ctx.locale, defaultLocale), update: shopPath(CART_UPDATE_ROUTE, ctx.locale, defaultLocale), inquiry: shopPath(CART_INQUIRY_ROUTE, ctx.locale, defaultLocale), + checkout: shopPath(CHECKOUT_ROUTE, ctx.locale, defaultLocale), }; } @@ -282,13 +287,18 @@ export async function cartPage( currency, now, }); - const { cart, update, inquiry } = paths(ctx); + const { cart, update, inquiry, checkout } = paths(ctx); + const view = cartView(facts, ctx.locale); return { view: { - ...cartView(facts, ctx.locale), + ...view, action: update, cart_path: cart, inquiry_action: inquiry, + checkout_path: checkout, + // Offered when every line can be ordered and the shop can take a + // payment at all; where it ships is the checkout page's question. + can_check_out: view.orderable && stripeKeys(ctx.secrets) !== null, // A cart with a part that has no price can be asked about though it // cannot be ordered; one with any other problem has to be put right. can_inquire: inquiryLinesOf(facts) !== null, diff --git a/src/plugins/shop/routes/checkout.ts b/src/plugins/shop/routes/checkout.ts new file mode 100644 index 0000000..bd0d434 --- /dev/null +++ b/src/plugins/shop/routes/checkout.ts @@ -0,0 +1,409 @@ +/** + * Checkout's two routes. + * + * `GET /_mallok/p/shop/checkout` is the checkout page: the cart as it will + * be ordered, where it can be shipped, what that costs, and the form that + * places the order. A country is chosen first, by a form sent with GET — the + * page has no script — and the page then shows shipping and the total for + * it, and the order form, which carries that country. + * + * `POST /_mallok/p/shop/checkout/place` places the order and sends the buyer + * to Stripe to pay. It never renders: every answer is a 303, to Stripe's + * page or back to the checkout page with the kind of reason no order was + * placed (`?checkout=invalid&field=email`). Nothing a person typed travels + * in an address. + * + * What is ordered is the cart as it is read at the POST, priced then, by the + * reading the page itself is drawn from; shipping is the rate of the zone the + * posted country is in. The order is written before Stripe is asked for + * anything, so that a payment always has an order to land on, and it waits + * as `pending` until Stripe says it was paid — its stock is taken then, not + * now (design §11). + * + * One open payment per cart: placing the order again — a second tab, a + * buyer who came back from Stripe's page and changed the cart — first + * closes the session of any order from the same cart still waiting, so the + * same goods cannot be paid for twice. + */ + +import type { + PluginPageResult, + PluginRequestContext, + RouteInput, +} from 'mallok/worker'; +import { readCartCurrencyStatement, readCartStatement } from '../lib/cart.js'; +import { pricedCartOf } from '../lib/cart-pricing.js'; +import { + type CheckoutForm, + checkoutFormSchema, + firstInvalidCheckoutField, + readCheckout, + stripeKeys, + TERMS_ACCEPTED, + taxModeOf, + termsPathOf, +} from '../lib/checkout.js'; +import { + CHECKOUT_REFUSALS, + type CheckoutRefusal, + checkoutView, +} from '../lib/checkout-view.js'; +import { readCartCookie } from '../lib/cookie.js'; +import { + type Currency, + defaultCurrencyForLocale, + isCurrency, +} from '../lib/currency.js'; +import { orderLinkKey, orderToken } from '../lib/order-access.js'; +import { cancelOrder } from '../lib/order-fulfilment.js'; +import { + createPendingOrder, + orderNoPrefixOf, + recordCheckoutSession, +} from '../lib/orders.js'; +import { + CART_ROUTE, + CHECKOUT_PLACE_ROUTE, + CHECKOUT_ROUTE, + orderLink, + shopPath, +} from '../lib/paths.js'; +import { isCountryCode } from '../lib/shipping.js'; +import { + CHECKOUT_LIFETIME_MS, + createCheckoutSession, + createTaxCustomer, + expireCheckoutSession, + StripeRequestError, +} from '../lib/stripe-client.js'; + +/** The checkout page's address carries a refusal as these parameters. */ +export const CHECKOUT_PARAM = 'checkout'; +export const CHECKOUT_FIELD_PARAM = 'field'; +/** And the country chosen, from its own form. */ +export const COUNTRY_PARAM = 'country'; + +function paths(ctx: PluginRequestContext): { + checkout: string; + place: string; + cart: string; +} { + const { defaultLocale } = ctx.site; + return { + checkout: shopPath(CHECKOUT_ROUTE, ctx.locale, defaultLocale), + place: shopPath(CHECKOUT_PLACE_ROUTE, ctx.locale, defaultLocale), + cart: shopPath(CART_ROUTE, ctx.locale, defaultLocale), + }; +} + +/** The cart this browser holds: its lines and its currency, in one round trip. */ +async function readHeldCart( + ctx: PluginRequestContext, + now: Date, +): Promise<{ + cartId: string | null; + lines: { variantId: string; quantity: number }[]; + currency: Currency; +}> { + const cartId = readCartCookie(ctx.request); + const [linesResult, currencyResult] = await ctx.db.batch< + { variant_id: string; quantity: number } | { currency: string | null } + >([ + readCartStatement(ctx.db, cartId ?? '', now), + readCartCurrencyStatement(ctx.db, cartId ?? '', now), + ]); + const chosen = ( + (currencyResult?.results ?? []) as { currency: string | null }[] + )[0]?.currency; + return { + cartId, + lines: ( + (linesResult?.results ?? []) as { variant_id: string; quantity: number }[] + ).map((row) => ({ variantId: row.variant_id, quantity: row.quantity })), + currency: + typeof chosen === 'string' && isCurrency(chosen) + ? chosen + : defaultCurrencyForLocale(ctx.locale), + }; +} + +/** `GET checkout`: the checkout page. It reads and never writes. */ +export async function checkoutPage( + _input: RouteInput, + ctx: PluginRequestContext, +): Promise { + const now = new Date(); + const cart = await readHeldCart(ctx, now); + // The country asked for, else the one the request came from — a guess the + // buyer can change, never a decision taken for them. + const asked = (ctx.url.searchParams.get(COUNTRY_PARAM) ?? '').toUpperCase(); + const country = isCountryCode(asked) ? asked : (ctx.country ?? null); + const reading = await readCheckout(ctx.db, { + lines: cart.lines, + locale: ctx.locale, + defaultLocale: ctx.site.defaultLocale, + currency: cart.currency, + country, + now, + }); + + const refusedAsked = ctx.url.searchParams.get(CHECKOUT_PARAM); + const refusedKind = CHECKOUT_REFUSALS.find((kind) => kind === refusedAsked); + const fieldAsked = ctx.url.searchParams.get(CHECKOUT_FIELD_PARAM) ?? ''; + return { + view: checkoutView(reading, { + locale: ctx.locale, + taxMode: taxModeOf(ctx.settings), + payments: stripeKeys(ctx.secrets) !== null, + termsPath: termsPathOf(ctx.settings), + refused: + refusedKind === undefined + ? null + : { + kind: refusedKind, + // Only a field the form has: nothing else from the address + // reaches the page. + field: + refusedKind === 'invalid' && + /^[a-z_0-9]{1,20}$/.test(fieldAsked) && + fieldAsked !== 'website' + ? fieldAsked + : '', + }, + paths: paths(ctx), + }), + }; +} + +/** + * Closes every order from this cart still waiting for its payment, so that + * the order about to be placed is the only one that can be paid. Stripe is + * asked to expire a session before its order is cancelled, never after. + * + * Throws when Stripe could not be asked: an order whose session cannot be + * closed must not be left open beside a new one. + */ +async function closeEarlierOrders( + ctx: PluginRequestContext, + cartId: string, + secretKey: string, + now: Date, +): Promise { + const { results } = await ctx.db + .prepare( + `SELECT id, stripe_session_id FROM p_shop_order + WHERE cart_id = ? AND status = 'pending' + ORDER BY created_at LIMIT 10`, + ) + .bind(cartId) + .all<{ id: string; stripe_session_id: string | null }>(); + for (const row of results) { + if (row.stripe_session_id !== null) { + await expireCheckoutSession(secretKey, row.stripe_session_id); + } + try { + await cancelOrder(ctx.db, { orderId: row.id, reason: 'replaced', now }); + } catch { + // Paid, or closed, meanwhile: either way no longer waiting. + } + } +} + +function addressOf(form: CheckoutForm) { + return { + recipient: form.recipient, + line1: form.line1, + ...(form.line2 === '' ? {} : { line2: form.line2 }), + city: form.city, + ...(form.state === '' ? {} : { state: form.state }), + postalCode: form.postal_code, + country: form.country, + ...(form.phone === '' ? {} : { phone: form.phone }), + }; +} + +/** `POST checkout/place`: place the order, and send the buyer to pay. */ +export async function checkoutPlace( + input: RouteInput, + ctx: PluginRequestContext, +): Promise { + const now = new Date(); + const routes = paths(ctx); + const back = (query: Record): Response => { + const search = new URLSearchParams(query).toString(); + return new Response(null, { + status: 303, + headers: { + location: + search === '' ? routes.checkout : `${routes.checkout}?${search}`, + }, + }); + }; + const refuse = ( + kind: CheckoutRefusal, + extra: Record = {}, + ): Response => back({ [CHECKOUT_PARAM]: kind, ...extra }); + + const parsed = checkoutFormSchema.safeParse(input.fields); + if (!parsed.success) { + const field = firstInvalidCheckoutField(parsed.error); + return refuse( + 'invalid', + field === null ? {} : { [CHECKOUT_FIELD_PARAM]: field }, + ); + } + const form = parsed.data; + const withCountry = { [COUNTRY_PARAM]: form.country }; + + // Whatever filled in the field no person sees is answered as if all were + // well, and nothing is placed: it learns nothing to try differently. + if (form.website !== '') { + return back(withCountry); + } + if (termsPathOf(ctx.settings) !== '' && form.terms !== TERMS_ACCEPTED) { + return refuse('invalid', { + [CHECKOUT_FIELD_PARAM]: 'terms', + ...withCountry, + }); + } + const keys = stripeKeys(ctx.secrets); + if (keys === null) { + return refuse('payments_unavailable', withCountry); + } + + const cart = await readHeldCart(ctx, now); + if (cart.cartId === null || cart.lines.length === 0) { + return refuse('empty'); + } + const reading = await readCheckout(ctx.db, { + lines: cart.lines, + locale: ctx.locale, + defaultLocale: ctx.site.defaultLocale, + currency: cart.currency, + country: form.country, + now, + }); + const priced = pricedCartOf(reading.facts); + if ( + reading.problem !== null || + reading.quote === null || + reading.rate === null || + !priced.ok + ) { + return refuse(reading.problem ?? 'cart_problem', withCountry); + } + + try { + await closeEarlierOrders(ctx, cart.cartId, keys.secretKey, now); + } catch (error) { + logFailure('close_earlier', error); + return refuse('payments_unavailable', withCountry); + } + + const taxMode = taxModeOf(ctx.settings); + const order = await createPendingOrder(ctx.db, { + cart: priced, + locale: ctx.locale, + email: form.email, + shippingAddress: addressOf(form), + shippingMinor: reading.quote.shippingMinor, + taxMinor: 0, + now, + cartId: cart.cartId, + company: form.company, + taxId: form.tax_id, + shippingZone: reading.rate.zoneName, + taxMode, + siteOrigin: ctx.url.origin, + orderNoPrefix: orderNoPrefixOf(ctx.settings.order_no_prefix), + }); + + try { + const token = await orderToken(await orderLinkKey(ctx.db, now), order.id); + const expiresAt = new Date(now.getTime() + CHECKOUT_LIFETIME_MS); + const taxCustomer = + taxMode === 'stripe' + ? await createTaxCustomer(keys.secretKey, { + orderId: order.id, + email: form.email, + company: form.company, + address: { ...addressOf(form), region: form.state }, + }) + : null; + const session = await createCheckoutSession(keys.secretKey, { + orderId: order.id, + orderNo: order.orderNo, + currency: priced.currency, + lines: priced.lines.map((line) => ({ + name: line.name, + sku: line.sku, + unitPriceMinor: line.unitPriceMinor, + quantity: line.quantity, + })), + shipping: { + label: reading.rate.zoneName, + amountMinor: reading.quote.shippingMinor, + }, + successUrl: orderLink({ + origin: ctx.url.origin, + orderNo: order.orderNo, + token, + locale: ctx.locale, + defaultLocale: ctx.site.defaultLocale, + }), + cancelUrl: `${ctx.url.origin}${routes.checkout}?${new URLSearchParams(withCountry).toString()}`, + locale: ctx.locale, + expiresAt, + ...(taxCustomer === null + ? { customerEmail: form.email } + : { taxCustomerId: taxCustomer.id }), + }); + if (!session.url.startsWith('https://')) { + throw new Error('Stripe answered with no page to pay on'); + } + await recordCheckoutSession(ctx.db, { + orderId: order.id, + sessionId: session.id, + expiresAt, + now, + }); + console.log( + JSON.stringify({ event: 'shop_checkout', orderId: order.id, taxMode }), + ); + return new Response(null, { + status: 303, + headers: { location: session.url }, + }); + } catch (error) { + logFailure('session', error, order.id); + // Nothing was paid: the order is closed, quietly, and the buyer told + // that payments are not available now. + await cancelOrder(ctx.db, { + orderId: order.id, + reason: 'failed', + now, + }).catch(() => undefined); + return refuse('payments_unavailable', withCountry); + } +} + +/** + * One line for the logs. Stripe's failure is described by its identifiers + * (`stripe-client.ts`); any other by its kind alone, since nothing rules out + * a message repeating a value that was bound. + */ +function logFailure(stage: string, error: unknown, orderId?: string): void { + console.log( + JSON.stringify({ + event: 'shop_checkout_failed', + stage, + ...(orderId === undefined ? {} : { orderId }), + reason: + error instanceof StripeRequestError + ? error.message + : error instanceof Error + ? error.name + : 'unknown', + }), + ); +} diff --git a/src/plugins/shop/routes/order.ts b/src/plugins/shop/routes/order.ts new file mode 100644 index 0000000..b20056a --- /dev/null +++ b/src/plugins/shop/routes/order.ts @@ -0,0 +1,122 @@ +/** + * `GET /_mallok/p/shop/order/:orderNo?k=…`: one order's page, for its buyer. + * + * Where Stripe sends the buyer back after paying, and where every email + * points. It opens only with the secret the link carries (`order-access.ts`); + * a wrong one, a missing one and an order that does not exist all answer the + * same 404, so a guess learns nothing. It reads and never writes. + * + * What the layout `shop/order` receives as `plugin_page`: + * + * found false: there is no such order, or the link is not its own. + * Nothing else is set + * order_no the order's number + * status `pending`, `paid`, `shipped`, `delivered`, `cancelled`, + * `refunded`, `oversold`. A theme words each: a pending order + * is one whose payment is still being confirmed, and an + * oversold one is being looked into + * placed_on the date it was placed, in the page's language + * lines[] sku, name, quantity, unit_price, line_total + * subtotal, shipping, tax, total formatted; `tax` is '' when none was + * charged + * tax_mode as at checkout: `none` or `stripe` + * zone the shipping zone's name + * address[] the address it ships to, a line each + * company, email, tax_id + * carrier, tracking_no '' until it ships + * lead_time_days the business days within which it leaves, or null + * cart_path the cart page + */ + +import type { + PluginPageResult, + PluginRequestContext, + RouteInput, +} from 'mallok/worker'; +import { formatMoney } from '../lib/money.js'; +import { existingOrderLinkKey, tokenOpens } from '../lib/order-access.js'; +import { getOrder } from '../lib/orders.js'; +import { CART_ROUTE, shopPath } from '../lib/paths.js'; +import { countryName } from '../lib/shipping.js'; + +/** What an order number looks like: a prefix, a date, eight characters. */ +const ORDER_NO_SHAPE = /^[A-Z0-9]{1,6}-\d{6}-[0-9A-Z]{8}$/; + +export async function orderPage( + input: RouteInput, + ctx: PluginRequestContext, +): Promise { + const notFound: PluginPageResult = { status: 404, view: { found: false } }; + const orderNo = input.params.orderNo ?? ''; + const token = ctx.url.searchParams.get('k') ?? ''; + if (!ORDER_NO_SHAPE.test(orderNo) || token === '') { + return notFound; + } + const [order, key] = await Promise.all([ + getOrder(ctx.db, { orderNo }), + existingOrderLinkKey(ctx.db), + ]); + if ( + order === null || + key === null || + !(await tokenOpens(key, order.id, token)) + ) { + return notFound; + } + + const money = (minor: number) => + formatMoney(minor, order.currency, ctx.locale); + const address = order.shippingAddress; + const cityLine = [address.postalCode, address.city] + .filter((part) => part !== undefined && part !== '') + .join(' '); + let placedOn = order.createdAt.slice(0, 10); + try { + placedOn = new Intl.DateTimeFormat(ctx.locale, { + dateStyle: 'long', + timeZone: 'UTC', + }).format(new Date(order.createdAt)); + } catch { + // A locale the runtime cannot format in keeps the ISO date. + } + + return { + title: order.orderNo, + view: { + found: true, + order_no: order.orderNo, + status: order.status, + placed_on: placedOn, + lines: order.lines.map((line) => ({ + sku: line.sku, + name: line.name, + quantity: line.quantity, + unit_price: money(line.unitPriceMinor), + line_total: money(line.unitPriceMinor * line.quantity), + })), + subtotal: money(order.subtotalMinor), + shipping: money(order.shippingMinor), + tax: order.taxMinor > 0 ? money(order.taxMinor) : '', + total: money(order.totalMinor), + tax_mode: order.taxMode, + zone: order.shippingZone, + address: [ + address.recipient, + address.line1, + address.line2, + cityLine, + address.state, + address.country === undefined || address.country === '' + ? undefined + : countryName(address.country, ctx.locale), + ].filter((line): line is string => line !== undefined && line !== ''), + company: order.company, + email: order.email, + tax_id: order.taxId, + carrier: order.carrier ?? '', + tracking_no: order.trackingNo ?? '', + lead_time_days: order.leadTimeDaysMax, + cart_path: shopPath(CART_ROUTE, ctx.locale, ctx.site.defaultLocale), + }, + }; +} diff --git a/src/plugins/shop/routes/stripe-webhook.ts b/src/plugins/shop/routes/stripe-webhook.ts new file mode 100644 index 0000000..6f53328 --- /dev/null +++ b/src/plugins/shop/routes/stripe-webhook.ts @@ -0,0 +1,87 @@ +/** + * `POST /_mallok/p/shop/stripe/webhook`: where Stripe delivers its events. + * + * A raw-body route: Mallok hands over the bytes as they arrived, because the + * signature is over them, and passes this route's status back to Stripe + * unchanged — which is how Stripe decides whether to deliver again. The + * signature is the only authentication there is, so nothing is read before + * it has been checked (`handleStripeWebhook`). + * + * Until the signing secret is set, every delivery is answered 503: Stripe + * keeps it and delivers again for three days, so a payment taken in the + * minutes before a seller finished setting up is not lost. + * + * What a delivery owes beyond its own batch — emails, purges — is handed to + * the order's follow-up job (`order-follow-up.ts`); a job that cannot be + * queued is taken up by the minute's cron. + */ + +import type { PluginRequestContext, RouteInput } from 'mallok/worker'; +import { FOLLOW_UP_JOB } from '../lib/order-follow-up.js'; +import { handleStripeWebhook } from '../lib/stripe-webhook.js'; + +export async function stripeWebhook( + _input: RouteInput, + ctx: PluginRequestContext, +): Promise { + const secret = ctx.secrets.stripe_webhook_secret ?? ''; + if (secret === '') { + console.log( + JSON.stringify({ event: 'shop_stripe_webhook', kind: 'no_secret' }), + ); + return new Response('The webhook signing secret is not set', { + status: 503, + }); + } + + const outcome = await handleStripeWebhook(ctx.db, { + rawBody: await ctx.request.text(), + signatureHeader: ctx.request.headers.get('stripe-signature') ?? '', + secret, + now: new Date(), + }); + + // The kind, the status and the order's id: nothing of the buyer. + console.log( + JSON.stringify({ + event: 'shop_stripe_webhook', + kind: outcome.kind, + status: outcome.status, + ...('orderId' in outcome ? { orderId: outcome.orderId } : {}), + ...('reason' in outcome ? { reason: outcome.reason } : {}), + }), + ); + + // Every outcome that names an order of this shop may have left something + // owed — a duplicate too: it is what a redelivery looks like after a first + // attempt that paid the order and stopped. + if ( + outcome.kind === 'paid' || + outcome.kind === 'oversold' || + outcome.kind === 'refused' || + outcome.kind === 'duplicate' || + outcome.kind === 'expired' + ) { + try { + await ctx.enqueue(FOLLOW_UP_JOB, { orderId: outcome.orderId }); + } catch { + console.log( + JSON.stringify({ + event: 'shop_follow_up_not_queued', + orderId: outcome.orderId, + }), + ); + } + } + + return new Response( + outcome.status === 200 ? '{"received":true}' : outcome.kind, + { + status: outcome.status, + headers: { + 'content-type': + outcome.status === 200 ? 'application/json' : 'text/plain', + }, + }, + ); +} diff --git a/src/theme/assets/style.css b/src/theme/assets/style.css index 8e96a74..c7360a2 100644 --- a/src/theme/assets/style.css +++ b/src/theme/assets/style.css @@ -2351,6 +2351,141 @@ p { text-align: right; } +/* ---------------------------------------------- checkout and an order page */ + +.checkout-intro { + margin: 0 0 1.5rem; + color: var(--slate-600); +} + +/* What is ordered, a line each: name and SKU, quantity, line total. */ +.checkout-line { + display: grid; + grid-template-columns: minmax(0, 1fr) auto auto; + align-items: baseline; + gap: 0.5rem 1rem; + padding: 0.75rem 1rem; + border-top: 1px solid var(--slate-100); +} + +.checkout-line:first-child { + border-top: 0; +} + +.checkout-line .cart-what { + display: grid; + gap: 0.125rem; +} + +.checkout-line .offer-sku { + font-family: var(--font-mono); + font-size: 0.75rem; +} + +.checkout-qty { + color: var(--slate-600); + font-size: 0.875rem; + white-space: nowrap; +} + +.checkout-country { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 0.75rem; + margin: 1.5rem 0 0; +} + +.checkout-country label, +.checkout-form .checkout-terms { + color: var(--slate-700); + font-size: 0.6875rem; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.checkout-country select { + display: block; + min-width: 16rem; + max-width: 100%; + margin-top: 0.375rem; + padding: 0.625rem 0.75rem; + border: 1px solid var(--slate-500); + border-radius: var(--radius-lg); + background: var(--white); + color: var(--slate-900); + font: inherit; + font-size: 0.875rem; + font-weight: 400; + letter-spacing: 0; + text-transform: none; +} + +.checkout-sums { + margin: 1.5rem 0 0.75rem auto; + max-width: 24rem; +} + +.checkout-total dt, +.checkout-total dd { + color: var(--slate-900); + font-weight: 700; +} + +.checkout-total .price { + font-size: 1.25rem; +} + +.checkout .cart-note, +.order .cart-note { + margin-top: 0.5rem; +} + +.checkout-unavailable { + margin-top: 1.5rem; +} + +/* A box and its words on one line, not a field under a label. */ +.checkout-form .checkout-terms { + display: flex; + align-items: center; + gap: 0.5rem; + letter-spacing: 0; + text-transform: none; + font-size: 0.875rem; + font-weight: 400; +} + +.checkout-form .checkout-terms input[type="checkbox"] { + display: inline-block; + width: 1.125rem; + height: 1.125rem; + margin: 0; + padding: 0; + accent-color: var(--accent); +} + +.checkout-form .checkout-terms a { + color: var(--accent-strong); +} + +.order-facts { + margin-bottom: 1rem; +} + +.order-address { + margin-top: 2rem; +} + +.order-address p { + margin: 0.5rem 0 0; +} + +.order-questions { + margin-top: 2rem; +} + .spec-card { padding: 1.25rem; border: 1px solid var(--slate-200); diff --git a/src/theme/index.ts b/src/theme/index.ts index f66870c..47c3f69 100644 --- a/src/theme/index.ts +++ b/src/theme/index.ts @@ -23,6 +23,8 @@ import pageLiquid from './layouts/page.liquid'; import productLiquid from './layouts/product.liquid'; import productsLiquid from './layouts/products.liquid'; import shopCartLiquid from './layouts/shop-cart.liquid'; +import shopCheckoutLiquid from './layouts/shop-checkout.liquid'; +import shopOrderLiquid from './layouts/shop-order.liquid'; import toolLiquid from './layouts/tool.liquid'; import deJson from './locales/de.json'; import enJson from './locales/en.json'; @@ -55,6 +57,8 @@ export const nundarTheme = defineTheme(manifest, { 'layouts/tool.liquid': toolLiquid, 'layouts/list.liquid': listLiquid, 'layouts/shop-cart.liquid': shopCartLiquid, + 'layouts/shop-checkout.liquid': shopCheckoutLiquid, + 'layouts/shop-order.liquid': shopOrderLiquid, 'partials/header.liquid': headerLiquid, 'partials/footer.liquid': footerLiquid, 'partials/card.liquid': cardLiquid, diff --git a/src/theme/layouts/shop-cart.liquid b/src/theme/layouts/shop-cart.liquid index 8766a6a..0f56b00 100644 --- a/src/theme/layouts/shop-cart.liquid +++ b/src/theme/layouts/shop-cart.liquid @@ -109,9 +109,10 @@ {% endif %} {% if cart.subtotal != blank %}

    {{ t.subtotal }} {{ cart.subtotal }}

    {% endif %}

    {{ t.cart_note }}

    - {% if site.kinds.product %} + {% if site.kinds.product or cart.can_check_out %}
    - {{ t.back_to_catalogue }} + {% if site.kinds.product %}{{ t.back_to_catalogue }}{% endif %} + {% if cart.can_check_out %}{{ t.checkout }}{% endif %}
    {% endif %} diff --git a/src/theme/layouts/shop-checkout.liquid b/src/theme/layouts/shop-checkout.liquid new file mode 100644 index 0000000..cf9cf77 --- /dev/null +++ b/src/theme/layouts/shop-checkout.liquid @@ -0,0 +1,127 @@ +{% layout "layouts/base" %} +{%- comment -%} + The checkout page. What is ordered, where it can go and what that costs + are the shop plugin's (`plugin_page`, described in the plugin's + `lib/checkout-view.ts`); how it looks, and every word on it, are this + theme's. + + Two plain forms and no script. The first chooses the country, by GET, and + the page comes back with shipping and the total for it; the second, shown + once a country is chosen, carries that country and places the order. Each + field carries the server's own rule — `required`, the length the plugin + allows, the pattern an address or a name is held to — so that a browser + refuses what the server would: a refused form comes back empty. +{%- endcomment -%} +{% block title %}{{ t.checkout_title }} — {{ site.name }}{% endblock %} +{% block content %} +{% assign co = plugin_page %} +
    +
    +

    {{ t.checkout_title }}

    +
    + + {%- comment -%} + Why the form that was sent placed no order: a kind, and for a field that + was wrong, its name. Nothing a person typed comes back. + {%- endcomment -%} + {% if co.refused %} + {% assign reason = "checkout_problem_" | append: co.refused.kind %} + + {% endif %} + + {% if co.problem == "empty" %} +

    {{ t.cart_empty }}

    +

    {{ t.checkout_back_to_cart }}

    + {% elsif co.problem == "cart_problem" %} +

    {{ t.checkout_problem_cart_problem }}

    +

    {{ t.checkout_back_to_cart }}

    + {% else %} +

    {{ t.checkout_intro }}

    + +
      + {% for line in co.lines %} +
    • + + {{ line.name }} + {{ line.sku }} + + × {{ line.quantity }} + {{ line.line_total }} +
    • + {% endfor %} +
    + + {% if co.countries.size == 0 %} +

    {{ t.checkout_no_countries }}

    + {% else %} +
    + + +
    + {% endif %} + +
    +
    {{ t.checkout_goods }}
    {{ co.goods }}
    + {% if co.shipping != blank %} +
    {{ t.checkout_shipping }}{% if co.zone != blank %} · {{ co.zone }}{% endif %}
    {% if co.shipping_free %}{{ t.checkout_shipping_free }}{% else %}{{ co.shipping }}{% endif %}
    + {% endif %} + {% if co.total != blank %} +
    {{ t.checkout_total }}
    {{ co.total }}
    + {% endif %} +
    + {% if co.free_over != blank %}{% unless co.shipping_free %}

    {{ t.checkout_free_over }} {{ co.free_over }}

    {% endunless %}{% endif %} +

    {% if co.tax_mode == "stripe" %}{{ t.checkout_tax_stripe }}{% else %}{{ t.checkout_tax_none }}{% endif %}

    + + {% if co.payments == false %} +

    {{ t.checkout_unavailable }}

    + {% elsif co.problem == "too_small" or co.problem == "too_large" %} + {% assign reason = "checkout_problem_" | append: co.problem %} +

    {{ t[reason] }}

    + {% elsif co.can_place %} + {%- comment -%} + The order form. The country is the one chosen above, carried as it is; + the last field is one no person sees or reaches, and whatever fills it + in places no order. + {%- endcomment -%} +
    +

    {{ t.checkout_details }}

    +
    + + +
    +
    + + +
    + + +
    + + +
    +
    + + +
    + + {% if co.terms_path != blank %} + + {% endif %} + + +

    {{ t.checkout_pay_note }}

    +
    + {% endif %} + +

    {{ t.checkout_back_to_cart }}

    + {% endif %} +
    +{% endblock %} diff --git a/src/theme/layouts/shop-order.liquid b/src/theme/layouts/shop-order.liquid new file mode 100644 index 0000000..cfe4ebe --- /dev/null +++ b/src/theme/layouts/shop-order.liquid @@ -0,0 +1,64 @@ +{% layout "layouts/base" %} +{%- comment -%} + One order's page, for its buyer: where Stripe sends them back after + paying, and where every email points. What the order holds is the shop + plugin's (`plugin_page`, described in the plugin's `routes/order.ts`); + how it looks, and every word on it, are this theme's. A link that does + not open the order finds nothing, and says only that. +{%- endcomment -%} +{% block title %}{{ t.order_title }}{% if plugin_page.found %} {{ plugin_page.order_no }}{% endif %} — {{ site.name }}{% endblock %} +{% block content %} +{% assign order = plugin_page %} +
    + {% if order.found %} +
    +

    {{ t.order_title }} {{ order.order_no }}

    +
    + + {% assign status_key = "order_status_" | append: order.status %} +
    +
    {{ t.order_placed_on }}
    {{ order.placed_on }}
    +
    {{ t.order_status }}
    {{ t[status_key] }}
    + {% if order.carrier != blank %}
    {{ t.order_carrier }}
    {{ order.carrier }}
    {% endif %} + {% if order.tracking_no != blank %}
    {{ t.order_tracking }}
    {{ order.tracking_no }}
    {% endif %} +
    + {% if order.status == "pending" %}

    {{ t.order_pending_note }}

    {% endif %} + {% if order.status == "paid" and order.lead_time_days %}

    {{ t.order_ships_within }} {{ order.lead_time_days }} {{ t.business_days }}

    {% endif %} + +
      + {% for line in order.lines %} +
    • + + {{ line.name }} + {{ line.sku }} + + × {{ line.quantity }} + {{ line.line_total }} +
    • + {% endfor %} +
    + +
    +
    {{ t.subtotal }}
    {{ order.subtotal }}
    +
    {{ t.checkout_shipping }}{% if order.zone != blank %} · {{ order.zone }}{% endif %}
    {{ order.shipping }}
    + {% if order.tax != blank %}
    {{ t.order_tax }}
    {{ order.tax }}
    {% endif %} +
    {{ t.checkout_total }}
    {{ order.total }}
    +
    + + {% if order.company != blank or order.address.size > 0 %} +
    +

    {{ t.order_ship_to }}

    +

    {% if order.company != blank %}{{ order.company }}{% if order.address.size > 0 %}
    {% endif %}{% endif %}{% for line in order.address %}{{ line }}{% unless forloop.last %}
    {% endunless %}{% endfor %}

    + {% if order.tax_id != blank %}

    {{ t.order_tax_id }}: {{ order.tax_id }}

    {% endif %} +
    + {% endif %} + +

    {{ t.order_questions }}

    + {% else %} +
    +

    {{ t.order_title }}

    +
    +

    {{ t.order_not_found }}

    + {% endif %} +
    +{% endblock %} diff --git a/src/theme/locales/de.json b/src/theme/locales/de.json index e150f44..b0a4deb 100644 --- a/src/theme/locales/de.json +++ b/src/theme/locales/de.json @@ -180,5 +180,64 @@ "inquiry_message": "Ihre Nachricht", "inquiry_submit": "Anfrage senden", "not_found_title": "Seite nicht gefunden", - "not_found_body": "Die angeforderte Seite gibt es hier nicht. Sie wurde möglicherweise verschoben, oder der Link ist fehlerhaft." + "not_found_body": "Die angeforderte Seite gibt es hier nicht. Sie wurde möglicherweise verschoben, oder der Link ist fehlerhaft.", + "checkout": "Zur Kasse", + "checkout_title": "Kasse", + "checkout_intro": "Wählen Sie, wohin die Bestellung geht: Der Versand wird für dieses Land berechnet. Anschließend bezahlen Sie auf der sicheren Seite von Stripe.", + "checkout_country": "Lieferung nach", + "checkout_country_none": "Land wählen", + "checkout_country_show": "Versand anzeigen", + "checkout_no_countries": "Dieser Warenkorb kann in dieser Währung noch nicht versandt werden. Bitte senden Sie ihn als Angebotsanfrage.", + "checkout_goods": "Waren", + "checkout_shipping": "Versand", + "checkout_shipping_free": "Kostenlos", + "checkout_free_over": "Kostenloser Versand bei Waren ab", + "checkout_total": "Gesamt", + "checkout_tax_none": "Preise ohne Steuer. Einfuhrabgaben und Steuern trägt der Käufer.", + "checkout_tax_stripe": "Steuern werden, wo sie anfallen, auf der Zahlungsseite hinzugefügt.", + "checkout_details": "Ihre Angaben", + "checkout_email": "E-Mail", + "checkout_company": "Firma", + "checkout_recipient": "Name", + "checkout_phone": "Telefon", + "checkout_line1": "Adresse", + "checkout_line2": "Adresszusatz", + "checkout_postal_code": "Postleitzahl", + "checkout_city": "Ort", + "checkout_state": "Bundesland oder Region", + "checkout_tax_id": "USt-IdNr. oder Steuernummer", + "checkout_terms": "Ich akzeptiere die", + "checkout_terms_link": "Verkaufsbedingungen", + "checkout_change": "Ändern", + "checkout_pay": "Weiter zur Zahlung", + "checkout_pay_note": "Sie werden zur sicheren Zahlungsseite von Stripe weitergeleitet. Sobald die Zahlung eingegangen ist, bestätigen wir Ihre Bestellung per E-Mail.", + "checkout_unavailable": "Online-Zahlung ist derzeit nicht verfügbar. Sie können Ihren Warenkorb als Angebotsanfrage senden.", + "checkout_refused": "Ihre Bestellung wurde nicht aufgegeben.", + "checkout_problem_invalid": "Bitte prüfen Sie dieses Feld:", + "checkout_problem_empty": "Der Warenkorb ist leer.", + "checkout_problem_cart_problem": "Einige Positionen im Warenkorb können so nicht bestellt werden. Bitte korrigieren Sie sie zuerst im Warenkorb.", + "checkout_problem_no_shipping": "Bitte wählen Sie ein Land, in das dieser Warenkorb versandt werden kann.", + "checkout_problem_too_small": "Der Bestellwert liegt unter dem, was online bezahlt werden kann. Bitte ergänzen Sie die Bestellung oder senden Sie sie als Angebotsanfrage.", + "checkout_problem_too_large": "Der Bestellwert übersteigt, was eine Online-Zahlung tragen kann. Bitte senden Sie die Bestellung als Angebotsanfrage.", + "checkout_problem_payments_unavailable": "Die Zahlung konnte nicht gestartet werden. Bitte versuchen Sie es gleich noch einmal oder senden Sie Ihren Warenkorb als Angebotsanfrage.", + "checkout_back_to_cart": "Zurück zum Warenkorb", + "order_title": "Bestellung", + "order_placed_on": "Aufgegeben am", + "order_status": "Status", + "order_status_pending": "Zahlungsbestätigung ausstehend", + "order_status_paid": "Bezahlt — in Vorbereitung", + "order_status_shipped": "Versandt", + "order_status_delivered": "Zugestellt", + "order_status_cancelled": "Storniert", + "order_status_refunded": "Erstattet", + "order_status_oversold": "Bezahlt — wir prüfen den Bestand und melden uns", + "order_pending_note": "Wenn Sie gerade bezahlt haben, kann die Bestätigung einen Moment dauern. Laden Sie die Seite gleich neu oder warten Sie auf unsere E-Mail.", + "order_ship_to": "Lieferadresse", + "order_tax": "Steuer", + "order_tax_id": "Steuernummer", + "order_carrier": "Versanddienstleister", + "order_tracking": "Sendungsnummer", + "order_ships_within": "Voraussichtlicher Versand innerhalb von", + "order_not_found": "Diese Bestellung kann nicht angezeigt werden. Der Link ist möglicherweise unvollständig: Bitte verwenden Sie den Link aus Ihrer E-Mail.", + "order_questions": "Fragen zu dieser Bestellung? Antworten Sie einfach auf eine unserer E-Mails dazu." } diff --git a/src/theme/locales/en.json b/src/theme/locales/en.json index 2172d9c..e0f7169 100644 --- a/src/theme/locales/en.json +++ b/src/theme/locales/en.json @@ -174,5 +174,64 @@ "prev": "Previous", "next": "Next", "not_found_title": "Page not found", - "not_found_body": "The page you asked for is not here. It may have moved, or the link may be wrong." + "not_found_body": "The page you asked for is not here. It may have moved, or the link may be wrong.", + "checkout": "Check out", + "checkout_title": "Checkout", + "checkout_intro": "Choose where the order goes: shipping is worked out for that country. You then pay on Stripe’s secure page.", + "checkout_country": "Ship to", + "checkout_country_none": "Choose a country", + "checkout_country_show": "Show shipping", + "checkout_no_countries": "This cart cannot be shipped in this currency yet. Please send it as a request for a quote.", + "checkout_goods": "Goods", + "checkout_shipping": "Shipping", + "checkout_shipping_free": "Free", + "checkout_free_over": "Free shipping on goods from", + "checkout_total": "Total", + "checkout_tax_none": "Prices are without tax. Any import duty and tax are the buyer’s to settle.", + "checkout_tax_stripe": "Tax, where it applies, is added on the payment page.", + "checkout_details": "Your details", + "checkout_email": "Email", + "checkout_company": "Company", + "checkout_recipient": "Name", + "checkout_phone": "Phone", + "checkout_line1": "Address", + "checkout_line2": "Address, second line", + "checkout_postal_code": "Postal code", + "checkout_city": "City", + "checkout_state": "State or region", + "checkout_tax_id": "VAT or tax number", + "checkout_terms": "I accept the", + "checkout_terms_link": "terms of sale", + "checkout_change": "Change", + "checkout_pay": "Continue to payment", + "checkout_pay_note": "You will be taken to Stripe’s secure page to pay. We confirm your order by email once the payment is through.", + "checkout_unavailable": "Online payment is not available at the moment. You can send your cart as a request for a quote.", + "checkout_refused": "Your order was not placed.", + "checkout_problem_invalid": "Please check this field:", + "checkout_problem_empty": "There is nothing in the cart.", + "checkout_problem_cart_problem": "Some lines in the cart cannot be ordered as they are. Please put them right in the cart first.", + "checkout_problem_no_shipping": "Please choose a country this cart can be shipped to.", + "checkout_problem_too_small": "The order comes to less than can be paid online. Please add to it, or send it as a request for a quote.", + "checkout_problem_too_large": "The order comes to more than one online payment can carry. Please send it as a request for a quote.", + "checkout_problem_payments_unavailable": "Payment could not be started. Please try again in a moment, or send your cart as a request for a quote.", + "checkout_back_to_cart": "Back to the cart", + "order_title": "Order", + "order_placed_on": "Placed on", + "order_status": "Status", + "order_status_pending": "Waiting for the payment to be confirmed", + "order_status_paid": "Paid — being prepared", + "order_status_shipped": "Shipped", + "order_status_delivered": "Delivered", + "order_status_cancelled": "Cancelled", + "order_status_refunded": "Refunded", + "order_status_oversold": "Paid — we are checking stock and will write to you", + "order_pending_note": "If you have just paid, confirming it can take a moment. Reload this page shortly, or wait for our email.", + "order_ship_to": "Shipping to", + "order_tax": "Tax", + "order_tax_id": "Tax number", + "order_carrier": "Carrier", + "order_tracking": "Tracking number", + "order_ships_within": "Expected to ship within", + "order_not_found": "This order cannot be shown. The link may be incomplete: please use the one in your email.", + "order_questions": "Questions about this order? Reply to any of our emails about it." } diff --git a/src/theme/locales/es.json b/src/theme/locales/es.json index 82e1871..0f42f9f 100644 --- a/src/theme/locales/es.json +++ b/src/theme/locales/es.json @@ -180,5 +180,64 @@ "inquiry_message": "Su mensaje", "inquiry_submit": "Enviar consulta", "not_found_title": "Página no encontrada", - "not_found_body": "La página solicitada no está aquí. Puede que se haya movido o que el enlace sea incorrecto." + "not_found_body": "La página solicitada no está aquí. Puede que se haya movido o que el enlace sea incorrecto.", + "checkout": "Finalizar pedido", + "checkout_title": "Pedido", + "checkout_intro": "Elija adónde va el pedido: el envío se calcula para ese país. Después paga en la página segura de Stripe.", + "checkout_country": "Enviar a", + "checkout_country_none": "Elija un país", + "checkout_country_show": "Ver el envío", + "checkout_no_countries": "Este carrito aún no se puede enviar en esta moneda. Envíelo como solicitud de presupuesto.", + "checkout_goods": "Mercancía", + "checkout_shipping": "Envío", + "checkout_shipping_free": "Gratis", + "checkout_free_over": "Envío gratis a partir de", + "checkout_total": "Total", + "checkout_tax_none": "Precios sin impuestos. Los aranceles e impuestos de importación corren por cuenta del comprador.", + "checkout_tax_stripe": "Los impuestos aplicables se añaden en la página de pago.", + "checkout_details": "Sus datos", + "checkout_email": "Correo electrónico", + "checkout_company": "Empresa", + "checkout_recipient": "Nombre", + "checkout_phone": "Teléfono", + "checkout_line1": "Dirección", + "checkout_line2": "Dirección, segunda línea", + "checkout_postal_code": "Código postal", + "checkout_city": "Ciudad", + "checkout_state": "Estado o región", + "checkout_tax_id": "NIF o número de IVA", + "checkout_terms": "Acepto las", + "checkout_terms_link": "condiciones de venta", + "checkout_change": "Cambiar", + "checkout_pay": "Continuar al pago", + "checkout_pay_note": "Le llevaremos a la página de pago segura de Stripe. Confirmamos su pedido por correo en cuanto se reciba el pago.", + "checkout_unavailable": "El pago en línea no está disponible en este momento. Puede enviar su carrito como solicitud de presupuesto.", + "checkout_refused": "Su pedido no se ha realizado.", + "checkout_problem_invalid": "Revise este campo:", + "checkout_problem_empty": "El carrito está vacío.", + "checkout_problem_cart_problem": "Algunas líneas del carrito no se pueden pedir así. Corríjalas primero en el carrito.", + "checkout_problem_no_shipping": "Elija un país al que se pueda enviar este carrito.", + "checkout_problem_too_small": "El importe es inferior al mínimo que se puede pagar en línea. Añada más artículos o envíelo como solicitud de presupuesto.", + "checkout_problem_too_large": "El importe supera lo que admite un pago en línea. Envíe el pedido como solicitud de presupuesto.", + "checkout_problem_payments_unavailable": "No se pudo iniciar el pago. Inténtelo de nuevo en un momento o envíe su carrito como solicitud de presupuesto.", + "checkout_back_to_cart": "Volver al carrito", + "order_title": "Pedido", + "order_placed_on": "Realizado el", + "order_status": "Estado", + "order_status_pending": "Pendiente de confirmar el pago", + "order_status_paid": "Pagado — en preparación", + "order_status_shipped": "Enviado", + "order_status_delivered": "Entregado", + "order_status_cancelled": "Cancelado", + "order_status_refunded": "Reembolsado", + "order_status_oversold": "Pagado — estamos comprobando el stock y le escribiremos", + "order_pending_note": "Si acaba de pagar, la confirmación puede tardar un momento. Vuelva a cargar esta página en breve o espere nuestro correo.", + "order_ship_to": "Dirección de envío", + "order_tax": "Impuestos", + "order_tax_id": "Número fiscal", + "order_carrier": "Transportista", + "order_tracking": "Número de seguimiento", + "order_ships_within": "Envío previsto en", + "order_not_found": "No se puede mostrar este pedido. Puede que el enlace esté incompleto: use el de su correo.", + "order_questions": "¿Preguntas sobre este pedido? Responda a cualquiera de nuestros correos sobre él." } diff --git a/src/theme/locales/fr.json b/src/theme/locales/fr.json index b2496b0..a20cee5 100644 --- a/src/theme/locales/fr.json +++ b/src/theme/locales/fr.json @@ -180,5 +180,64 @@ "inquiry_message": "Votre message", "inquiry_submit": "Envoyer la demande", "not_found_title": "Page introuvable", - "not_found_body": "La page demandée n’est pas ici. Elle a peut-être été déplacée, ou le lien est erroné." + "not_found_body": "La page demandée n’est pas ici. Elle a peut-être été déplacée, ou le lien est erroné.", + "checkout": "Commander", + "checkout_title": "Commande", + "checkout_intro": "Choisissez où envoyer la commande : la livraison est calculée pour ce pays. Vous payez ensuite sur la page sécurisée de Stripe.", + "checkout_country": "Livrer en", + "checkout_country_none": "Choisir un pays", + "checkout_country_show": "Voir la livraison", + "checkout_no_countries": "Ce panier ne peut pas encore être livré dans cette devise. Envoyez-le plutôt comme demande de devis.", + "checkout_goods": "Marchandises", + "checkout_shipping": "Livraison", + "checkout_shipping_free": "Offerte", + "checkout_free_over": "Livraison offerte dès", + "checkout_total": "Total", + "checkout_tax_none": "Prix hors taxes. Les droits et taxes à l’importation sont à la charge de l’acheteur.", + "checkout_tax_stripe": "Les taxes applicables sont ajoutées sur la page de paiement.", + "checkout_details": "Vos coordonnées", + "checkout_email": "E-mail", + "checkout_company": "Société", + "checkout_recipient": "Nom", + "checkout_phone": "Téléphone", + "checkout_line1": "Adresse", + "checkout_line2": "Complément d’adresse", + "checkout_postal_code": "Code postal", + "checkout_city": "Ville", + "checkout_state": "État ou région", + "checkout_tax_id": "Numéro de TVA ou fiscal", + "checkout_terms": "J’accepte les", + "checkout_terms_link": "conditions de vente", + "checkout_change": "Modifier", + "checkout_pay": "Passer au paiement", + "checkout_pay_note": "Vous serez redirigé vers la page de paiement sécurisée de Stripe. Nous confirmons votre commande par e-mail dès réception du paiement.", + "checkout_unavailable": "Le paiement en ligne n’est pas disponible pour le moment. Vous pouvez envoyer votre panier comme demande de devis.", + "checkout_refused": "Votre commande n’a pas été passée.", + "checkout_problem_invalid": "Veuillez vérifier ce champ :", + "checkout_problem_empty": "Le panier est vide.", + "checkout_problem_cart_problem": "Certaines lignes du panier ne peuvent pas être commandées en l’état. Corrigez-les d’abord dans le panier.", + "checkout_problem_no_shipping": "Choisissez un pays où ce panier peut être livré.", + "checkout_problem_too_small": "Le montant est inférieur au minimum payable en ligne. Complétez la commande ou envoyez-la comme demande de devis.", + "checkout_problem_too_large": "Le montant dépasse ce qu’un paiement en ligne peut couvrir. Envoyez la commande comme demande de devis.", + "checkout_problem_payments_unavailable": "Le paiement n’a pas pu démarrer. Réessayez dans un instant, ou envoyez votre panier comme demande de devis.", + "checkout_back_to_cart": "Retour au panier", + "order_title": "Commande", + "order_placed_on": "Passée le", + "order_status": "Statut", + "order_status_pending": "En attente de la confirmation du paiement", + "order_status_paid": "Payée — en préparation", + "order_status_shipped": "Expédiée", + "order_status_delivered": "Livrée", + "order_status_cancelled": "Annulée", + "order_status_refunded": "Remboursée", + "order_status_oversold": "Payée — nous vérifions le stock et vous écrivons", + "order_pending_note": "Si vous venez de payer, la confirmation peut prendre un instant. Rechargez cette page dans un moment ou attendez notre e-mail.", + "order_ship_to": "Adresse de livraison", + "order_tax": "Taxes", + "order_tax_id": "Numéro fiscal", + "order_carrier": "Transporteur", + "order_tracking": "Numéro de suivi", + "order_ships_within": "Expédition prévue sous", + "order_not_found": "Cette commande ne peut pas être affichée. Le lien est peut-être incomplet : utilisez celui de votre e-mail.", + "order_questions": "Une question sur cette commande ? Répondez à l’un de nos e-mails à son sujet." } diff --git a/src/theme/theme.json b/src/theme/theme.json index 96ac802..fdff4c8 100644 --- a/src/theme/theme.json +++ b/src/theme/theme.json @@ -2,7 +2,7 @@ "id": "nundar", "name": "Nundar", "description": "A commerce theme for a technical catalogue: a specification finder, product pages built around a size table, landing pages for the applications a part is used in, collections by type, case studies and reference pages. With the shop plugin, each size carries its price, minimum order and availability, and the cart is a page of the site. HTML first: every page is complete without a script, and the three it declares only add to what is already there — filters for a table, a switch between the currencies a page has prices in, calculators beside the tables of an engineering reference.", - "version": "0.11.0", + "version": "0.12.0", "themeApi": 1, "home": "layouts/home.liquid", "kinds": { @@ -297,7 +297,9 @@ "defaultLocale": "en", "imageWidths": [480, 960, 1440], "pluginLayouts": { - "shop/cart": "layouts/shop-cart.liquid" + "shop/cart": "layouts/shop-cart.liquid", + "shop/checkout": "layouts/shop-checkout.liquid", + "shop/order": "layouts/shop-order.liquid" }, "clientScripts": [ { diff --git a/test/shop/checkout-route.test.ts b/test/shop/checkout-route.test.ts new file mode 100644 index 0000000..38174d6 --- /dev/null +++ b/test/shop/checkout-route.test.ts @@ -0,0 +1,538 @@ +import { SELF } from 'cloudflare:test'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { + existingOrderLinkKey, + tokenOpens, +} from '../../src/plugins/shop/lib/order-access.js'; +import { + clearShopTables, + createProduct, + createShippingZone, + createVariant, + db, + ensureSite, + ORIGIN, + outboxRows, + type StripeCall, + setPrice, + setShopSecrets, + setShopSettings, + stockOf, + stubStripe, + type TestProduct, +} from './helpers.js'; + +const SHOP = '/_mallok/p/shop'; +const KEYS = { + stripe_secret_key: 'sk_test_checkout', + stripe_webhook_secret: 'whsec_checkout', +}; + +let bolt: TestProduct; +let stripe: { calls: StripeCall[]; restore: () => void } | null = null; + +function post( + path: string, + fields: Record, + cookie?: string, +): Promise { + return SELF.fetch(`${ORIGIN}${SHOP}${path}`, { + method: 'POST', + headers: { + 'content-type': 'application/x-www-form-urlencoded', + ...(cookie === undefined ? {} : { cookie }), + }, + body: new URLSearchParams(fields).toString(), + redirect: 'manual', + }); +} + +function page(path: string, cookie?: string): Promise { + return SELF.fetch(`${ORIGIN}${SHOP}${path}`, { + headers: cookie === undefined ? {} : { cookie }, + redirect: 'manual', + }); +} + +/** A cart holding `quantity` of the bolt; answers with its cookie. */ +async function cartWith(quantity: number, locale = ''): Promise { + const response = await post(`${locale}/cart/update`, { + variant: 'hb-m8', + quantity: String(quantity), + }); + return response.headers.get('set-cookie')?.split(';')[0] ?? 'no cookie'; +} + +const BUYER = { + email: 'ada@buyer.example', + company: 'Analytical Engines Ltd', + recipient: 'Ada Lovelace', + phone: '+49 40 000000', + line1: 'Hafenstraße 1', + line2: '', + postal_code: '20457', + city: 'Hamburg', + state: '', + tax_id: 'DE123456789', + country: 'DE', +}; + +function place( + cookie: string | undefined, + fields: Record = BUYER, + locale = '', +): Promise { + return post(`${locale}/checkout/place`, fields, cookie); +} + +/** Where a response sends the buyer, taken apart. */ +function landing(response: Response): URL { + return new URL(response.headers.get('location') ?? '/', ORIGIN); +} + +interface OrderRow { + id: string; + order_no: string; + status: string; + currency: string; + subtotal_minor: number; + shipping_minor: number; + total_minor: number; + email: string; + company: string; + tax_id: string; + shipping_zone: string; + tax_mode: string; + site_origin: string; + cart_id: string | null; + locale: string; + stripe_session_id: string | null; + stripe_session_expires_at: string | null; + shipping_address: string; +} + +async function orders(): Promise { + const { results } = await db() + .prepare('SELECT * FROM p_shop_order ORDER BY created_at, id') + .all(); + return results; +} + +function sessionCalls(): StripeCall[] { + return (stripe?.calls ?? []).filter( + (call) => call.path === '/v1/checkout/sessions', + ); +} + +beforeAll(async () => { + await ensureSite(); + bolt = await createProduct({ + title: 'Hex bolt M8', + slug: 'checkout-hex-bolt', + }); +}); + +beforeEach(async () => { + await clearShopTables(); + await setShopSecrets(KEYS); + await setShopSettings({ tax_mode: 'none', terms_path: '' }); + await createVariant({ + id: 'hb-m8', + productGroup: bolt.translationGroup, + sku: 'HB-M8', + moq: 10, + stock: 1000, + }); + for (const [currency, amountMinor] of [ + ['USD', 990], + ['EUR', 900], + ] as const) { + await setPrice({ + variantId: 'hb-m8', + currency, + amountMinor, + source: 'base', + }); + } + await createShippingZone({ + name: 'Europe', + countries: ['DE', 'FR'], + rates: [ + { currency: 'USD', amountMinor: 4900, freeOverMinor: 500_000 }, + { currency: 'EUR', amountMinor: 4500 }, + ], + }); + stripe = stubStripe(); +}); + +afterEach(() => { + stripe?.restore(); + stripe = null; +}); + +describe('the checkout page', () => { + it('shows the cart, the countries it can go to, and no form until one is chosen', async () => { + const cookie = await cartWith(100); + + const html = await (await page('/checkout', cookie)).text(); + + expect(html).toContain('HB-M8'); + expect(html).toContain('