Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

test(print): cover the checkout endpoints and the Materialize quote client

nirholas93f09dd24871
diff --git a/tests/api/print-checkout-endpoints.test.js b/tests/api/print-checkout-endpoints.test.js
new file mode 100644
index 000000000..984f975da
--- /dev/null
+++ b/tests/api/print-checkout-endpoints.test.js
@@ -0,0 +1,339 @@
+/**
+ * Materialize checkout over HTTP: the human lane (api/print/orders.js and its
+ * detail route) and the agent lane (api/x402/print-order.js).
+ *
+ * What these pin, in the order a buyer meets them:
+ *
+ * • nobody orders anonymously, and nobody orders without CSRF;
+ * • the price is the SIGNED price. A forged token, a token whose payload was
+ * edited by one byte, and an expired token all fail identically and none of
+ * them reaches the database;
+ * • the address a parcel goes to must be the country the shipping was priced
+ * for, or we quietly eat the difference on every order;
+ * • an order is only ever visible to the account that placed it;
+ * • on the agent lane, EVERY refusal happens before the 402 is issued, so a
+ * malformed order can never charge. That is the property the whole x402
+ * print rail rests on.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { makeReq, makeRes } from '../_helpers/monetization.js';
+
+process.env.JWT_SECRET = 'print-checkout-test-secret-0123456789';
+process.env.APP_ORIGIN = 'https://three.ws';
+process.env.X402_PAY_TO_SOLANA = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
+process.env.X402_ASSET_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+process.env.X402_FEE_PAYER_SOLANA = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
+
+const USER = { id: '00000000-0000-4000-8000-0000000000aa' };
+const OTHER_USER = { id: '00000000-0000-4000-8000-0000000000bb' };
+
+let sessionUser = USER;
+let csrfOk = true;
+const store = { orders: new Map(), created: [], transitions: [] };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+vi.mock('../../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async (_req, res) => {
+ if (csrfOk) return true;
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'csrf' }));
+ return false;
+ }),
+}));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ printOrderIp: vi.fn(async () => ({ success: true })),
+ authedReadIp: vi.fn(async () => ({ success: true })),
+ // The shared paid-endpoint rail caps anonymous discovery probes before it
+ // builds a challenge, so the x402 lane needs this bucket too.
+ x402ProbeIp: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+// The store is exercised for real in tests/print-checkout-store.test.js; here it
+// is a double so a handler test asserts HTTP behaviour rather than SQL.
+vi.mock('../../api/_lib/print-store.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ createOrder: vi.fn(async (input) => {
+ store.created.push(input);
+ const row = {
+ id: '11111111-2222-4333-8444-555555555555',
+ status: 'created',
+ user_id: input.userId ?? null,
+ payer_wallet: input.payerWallet ?? null,
+ material_id: input.quote.materialId,
+ target_height_mm: input.quote.targetHeightMm,
+ quantity: input.quote.quantity,
+ price_usdc: input.quote.total,
+ quote: input.itemization,
+ shipping: input.shipping,
+ payment_reference: input.paymentReference ?? null,
+ payment_chain: input.paymentChain ?? null,
+ quote_expires_at: new Date(input.quote.expiresAt).toISOString(),
+ events: [],
+ };
+ store.orders.set(row.id, row);
+ return row;
+ }),
+ transition: vi.fn(async ({ orderId, to }) => {
+ store.transitions.push({ orderId, to });
+ const row = store.orders.get(orderId);
+ if (row) row.status = to;
+ return { order: row, event: {}, certificate: null };
+ }),
+ getOrderWithEvents: vi.fn(async (id) => store.orders.get(id) ?? null),
+ listOrdersForUser: vi.fn(async () => []),
+ };
+});
+
+const { signQuote } = await import('../../api/_lib/print/quote.js');
+const ordersHandler = (await import('../../api/print/orders.js')).default;
+const orderDetailHandler = (await import('../../api/print/orders/[id].js')).default;
+const printOrderX402 = (await import('../../api/x402/print-order.js')).default;
+const { floorPriceAtomics } = await import('../../api/x402/print-order.js');
+
+const SHIPPING = {
+ name: 'Ada Lovelace',
+ line1: '12 Analytical Way',
+ city: 'London',
+ postal_code: 'EC1A 1AA',
+ country: 'GB',
+};
+
+/** A quotePrint-shaped result, the only input signQuote accepts. */
+function quoteShape(overrides = {}) {
+ return {
+ material: { id: 'resin-standard', name: 'Standard resin', class: 'resin' },
+ finish: { id: 'as-printed', name: 'As printed' },
+ targetHeightMm: 140,
+ quantity: 1,
+ hollow: false,
+ country: 'GB',
+ total: 48.2,
+ geometry: { volumeCm3: 38.4 },
+ leadTimeDays: 14,
+ ...overrides,
+ };
+}
+
+function tokenFor(overrides = {}, context = {}) {
+ return signQuote(quoteShape(overrides), {
+ reportHash: 'abc123',
+ sourceUrl: 'https://cdn.example.test/model.glb',
+ creationId: null,
+ ...context,
+ });
+}
+
+async function postOrder(body, headers = {}) {
+ const req = makeReq({ method: 'POST', url: '/api/print/orders', body, headers });
+ const res = makeRes();
+ await ordersHandler(req, res);
+ return res;
+}
+
+function parse(res) {
+ return res.body ? JSON.parse(res.body) : null;
+}
+
+beforeEach(() => {
+ sessionUser = USER;
+ csrfOk = true;
+ store.orders.clear();
+ store.created.length = 0;
+ store.transitions.length = 0;
+ vi.clearAllMocks();
+});
+
+describe('POST /api/print/orders', () => {
+ it('refuses an anonymous order', async () => {
+ sessionUser = null;
+ const res = await postOrder({ token: tokenFor(), shipping: SHIPPING });
+ expect(res.statusCode).toBe(401);
+ expect(store.created).toHaveLength(0);
+ });
+
+ it('refuses an order without CSRF', async () => {
+ csrfOk = false;
+ const res = await postOrder({ token: tokenFor(), shipping: SHIPPING });
+ expect(res.statusCode).toBe(403);
+ expect(store.created).toHaveLength(0);
+ });
+
+ it('opens the order and quotes a Solana Pay intent for the signed total', async () => {
+ const res = await postOrder({ token: tokenFor(), shipping: SHIPPING });
+ expect(res.statusCode).toBe(201);
+ const body = parse(res);
+ expect(body.order.status).toBe('quoted');
+ expect(body.order.price_usdc).toBe(48.2);
+ expect(body.payment.chain).toBe('solana');
+ expect(body.payment.recipient).toBe(process.env.X402_PAY_TO_SOLANA);
+ expect(body.payment.mint).toBe(process.env.X402_ASSET_MINT_SOLANA);
+ expect(body.payment.amount).toBe('48.20');
+ // 6-decimal USDC, derived from the signed total and nothing else.
+ expect(body.payment.amount_atomics).toBe('48200000');
+ expect(body.payment.url).toContain(`solana:${process.env.X402_PAY_TO_SOLANA}`);
+ expect(body.payment.url).toContain('spl-token=');
+ expect(body.payment.reference).toMatch(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/);
+ expect(store.transitions).toEqual([
+ { orderId: '11111111-2222-4333-8444-555555555555', to: 'quoted' },
+ ]);
+ });
+
+ it('takes the price from the token even when the body claims another one', async () => {
+ await postOrder({ token: tokenFor(), shipping: SHIPPING, total: 1, price_usdc: 1, amount: 1 });
+ expect(store.created[0].quote.total).toBe(48.2);
+ });
+
+ it('refuses a token whose payload was edited', async () => {
+ const token = tokenFor();
+ const [prefix, payload, signature] = token.split('.');
+ const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
+ decoded.t = 1; // one dollar instead of forty-eight
+ const forged = `${prefix}.${Buffer.from(JSON.stringify(decoded)).toString('base64url')}.${signature}`;
+ const res = await postOrder({ token: forged, shipping: SHIPPING });
+ expect(res.statusCode).toBe(422);
+ expect(parse(res).error).toBe('quote_invalid');
+ expect(store.created).toHaveLength(0);
+ });
+
+ it('refuses an expired quote the same way it refuses a forged one', async () => {
+ const token = signQuote(quoteShape(), {
+ reportHash: 'abc123',
+ sourceUrl: 'https://cdn.example.test/model.glb',
+ ttlSeconds: -10,
+ });
+ const res = await postOrder({ token, shipping: SHIPPING });
+ expect(res.statusCode).toBe(422);
+ expect(parse(res).error).toBe('quote_invalid');
+ expect(store.created).toHaveLength(0);
+ });
+
+ it('refuses a token this server never signed', async () => {
+ const res = await postOrder({ token: 'pq1.eyJ2IjoxfQ.bm90LWEtc2lnbmF0dXJl', shipping: SHIPPING });
+ expect(res.statusCode).toBe(422);
+ expect(store.created).toHaveLength(0);
+ });
+
+ it('refuses to ship somewhere the quote was not priced for', async () => {
+ const res = await postOrder({ token: tokenFor(), shipping: { ...SHIPPING, country: 'AU' } });
+ expect(res.statusCode).toBe(422);
+ const body = parse(res);
+ expect(body.error).toBe('destination_mismatch');
+ expect(body.quoted_country).toBe('GB');
+ expect(body.shipping_country).toBe('AU');
+ expect(store.created).toHaveLength(0);
+ });
+
+ it('names the missing shipping field rather than failing generically', async () => {
+ const partial = { ...SHIPPING };
+ delete partial.postal_code;
+ const res = await postOrder({ token: tokenFor(), shipping: partial });
+ expect(res.statusCode).toBe(422);
+ expect(parse(res).field).toBe('postal_code');
+ expect(store.created).toHaveLength(0);
+ });
+});
+
+describe('GET /api/print/orders/:id', () => {
+ async function fetchOrder(id) {
+ const req = makeReq({ method: 'GET', url: `/api/print/orders/${id}`, query: { id } });
+ const res = makeRes();
+ await orderDetailHandler(req, res);
+ return res;
+ }
+
+ it('returns the order and its timeline to its owner', async () => {
+ await postOrder({ token: tokenFor(), shipping: SHIPPING });
+ const id = '11111111-2222-4333-8444-555555555555';
+ store.orders.get(id).events = [{ status: 'created', note: 'opened', actor: 'buyer', created_at: '2026-09-02T00:00:00Z' }];
+ const res = await fetchOrder(id);
+ expect(res.statusCode).toBe(200);
+ const body = parse(res);
+ expect(body.order.id).toBe(id);
+ expect(body.events[0].status).toBe('created');
+ });
+
+ it('answers 404, not 403, for an order that belongs to someone else', async () => {
+ await postOrder({ token: tokenFor(), shipping: SHIPPING });
+ sessionUser = OTHER_USER;
+ const res = await fetchOrder('11111111-2222-4333-8444-555555555555');
+ // Confirming an id exists to a stranger is itself a leak.
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('never returns the full shipping address', async () => {
+ await postOrder({ token: tokenFor(), shipping: SHIPPING });
+ const res = await fetchOrder('11111111-2222-4333-8444-555555555555');
+ const body = parse(res);
+ expect(body.order.ship_to).toEqual({ name: 'Ada Lovelace', city: 'London', country: 'GB' });
+ expect(res.body).not.toContain('12 Analytical Way');
+ expect(res.body).not.toContain('EC1A 1AA');
+ });
+});
+
+describe('POST /api/x402/print-order', () => {
+ async function call(body, headers = {}) {
+ const req = makeReq({ method: 'POST', url: '/api/x402/print-order', body, headers });
+ const res = makeRes();
+ await printOrderX402(req, res);
+ return res;
+ }
+
+ it('answers a bodyless probe with a well-formed challenge at the catalog floor', async () => {
+ const res = await call(null);
+ expect(res.statusCode).toBe(402);
+ const body = parse(res);
+ expect(Array.isArray(body.accepts)).toBe(true);
+ expect(body.accepts.length).toBeGreaterThan(0);
+ expect(body.accepts[0].amount).toBe(floorPriceAtomics());
+ expect(body.error).toContain('/api/print/quote');
+ });
+
+ it('quotes the order its own signed total, not a list price', async () => {
+ const res = await call({ token: tokenFor(), shipping: SHIPPING });
+ expect(res.statusCode).toBe(402);
+ const body = parse(res);
+ // 48.20 USDC at 6 decimals. A different order is a different amount.
+ expect(body.accepts.some((a) => a.amount === '48200000')).toBe(true);
+ expect(body.accepts[0].amount).not.toBe(floorPriceAtomics());
+ // Nothing was opened: the caller has not paid yet.
+ expect(store.created).toHaveLength(0);
+ });
+
+ it('refuses a tampered token before issuing any challenge', async () => {
+ const token = tokenFor();
+ const [prefix, payload] = token.split('.');
+ const forged = `${prefix}.${payload}.bm90LWEtc2lnbmF0dXJl`;
+ const res = await call({ token: forged, shipping: SHIPPING });
+ expect(res.statusCode).toBe(422);
+ expect(parse(res).error).toBe('quote_invalid');
+ });
+
+ it('refuses an incomplete address before issuing any challenge', async () => {
+ const partial = { ...SHIPPING };
+ delete partial.city;
+ const res = await call({ token: tokenFor(), shipping: partial });
+ expect(res.statusCode).toBe(422);
+ expect(parse(res).field).toBe('city');
+ });
+
+ it('refuses a destination the quote was not priced for before charging', async () => {
+ const res = await call({ token: tokenFor(), shipping: { ...SHIPPING, country: 'AU' } });
+ expect(res.statusCode).toBe(422);
+ expect(parse(res).error).toBe('destination_mismatch');
+ });
+
+ it('demands a token when a payment header arrives with no order', async () => {
+ const res = await call(null, { 'x-payment': 'deadbeef' });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('token_required');
+ });
+});
diff --git a/tests/materialize-lib.test.js b/tests/materialize-lib.test.js
new file mode 100644
index 000000000..adbea8c72
--- /dev/null
+++ b/tests/materialize-lib.test.js
@@ -0,0 +1,303 @@
+// Pure view logic behind /materialize. These functions decide what a buyer sees
+// about a price and a physical size, so the edges are the point: a slider whose
+// ends disagree with the server rejects at checkout, a scale drawing with the
+// wrong proportion misleads about a real object, and an AR scale factor that is
+// off by a decimal puts a 14 cm figure on the floor at 14 metres.
+import { describe, it, expect } from 'vitest';
+
+import {
+ SHIPPING_COUNTRIES,
+ arScaleAttribute,
+ clampHeight,
+ defaultHeight,
+ formatLeadTime,
+ formatMm,
+ formatUsdc,
+ printabilityView,
+ quoteRows,
+ rejectionView,
+ scaleReference,
+ sliderBounds,
+ timelineView,
+ validateShipping,
+} from '../src/materialize-lib.js';
+
+const REFERENCES = [
+ { id: 'coin', name: 'A coin', heightMm: 24 },
+ { id: 'mug', name: 'Coffee mug', heightMm: 95 },
+ { id: 'hand', name: 'A hand', heightMm: 180 },
+ { id: 'person', name: 'A person', heightMm: 1750 },
+];
+
+const FIT = { id: 'resin-standard', minHeightMm: 41.3, maxHeightMm: 180, limitedBy: { min: 'wall', max: 'material' } };
+
+describe('formatUsdc', () => {
+ it('always shows two decimals, and keeps a credit negative', () => {
+ expect(formatUsdc(6)).toBe('6.00');
+ expect(formatUsdc(34.375)).toBe('34.38');
+ expect(formatUsdc(-6.06)).toBe('-6.06');
+ });
+ it('returns empty for anything that is not a number', () => {
+ expect(formatUsdc(undefined)).toBe('');
+ expect(formatUsdc('free')).toBe('');
+ });
+});
+
+describe('formatMm', () => {
+ it('drops needless precision as the number grows', () => {
+ expect(formatMm(6.42)).toBe('6.4 mm');
+ expect(formatMm(35)).toBe('35 mm');
+ expect(formatMm(140.4)).toBe('140 mm');
+ });
+ it('switches to metres past a metre, which is where mm stops being readable', () => {
+ expect(formatMm(1750)).toBe('1.75 m');
+ });
+ it('can omit the unit for dimension triples', () => {
+ expect(formatMm(35, { unit: false })).toBe('35');
+ });
+});
+
+describe('formatLeadTime', () => {
+ it('counts days up to a fortnight, then weeks', () => {
+ expect(formatLeadTime(12)).toBe('About 12 days to your door');
+ expect(formatLeadTime(22)).toBe('About 3 weeks to your door');
+ });
+ it('never promises a timeline it was not given', () => {
+ expect(formatLeadTime(0)).toBe('Timing confirmed at checkout');
+ expect(formatLeadTime(null)).toBe('Timing confirmed at checkout');
+ });
+});
+
+describe('sliderBounds', () => {
+ it('rounds inward so either end of the track still quotes', () => {
+ const bounds = sliderBounds(FIT);
+ expect(bounds.min).toBe(42); // ceil, never below the server's floor
+ expect(bounds.max).toBe(180); // floor, never above the server's ceiling
+ });
+ it('labels the end of the track with the constraint that set it', () => {
+ const bounds = sliderBounds({ ...FIT, limitedBy: { min: 'wall', max: 'build_volume' } });
+ expect(bounds.minNote).toMatch(/thinnest wall/);
+ expect(bounds.maxNote).toMatch(/print bed/);
+ });
+ it('coarsens the step on a long track so a drag stays on round numbers', () => {
+ expect(sliderBounds({ ...FIT, minHeightMm: 12, maxHeightMm: 90 }).step).toBe(1);
+ expect(sliderBounds({ ...FIT, minHeightMm: 12, maxHeightMm: 280 }).step).toBe(2);
+ expect(sliderBounds({ ...FIT, minHeightMm: 12, maxHeightMm: 600 }).step).toBe(5);
+ });
+ it('returns nothing when no height works, so the panel hides instead of rendering an inverted track', () => {
+ expect(sliderBounds({ ...FIT, minHeightMm: 340, maxHeightMm: 200 })).toBeNull();
+ expect(sliderBounds(null)).toBeNull();
+ });
+});
+
+describe('clampHeight', () => {
+ const bounds = sliderBounds({ ...FIT, minHeightMm: 20, maxHeightMm: 200 });
+ it('snaps onto the slider grid and holds inside both ends', () => {
+ // This track spans 180 mm, so the step is 2 and the grid runs 20, 22, 24…
+ expect(bounds.step).toBe(2);
+ expect(clampHeight(101, bounds)).toBe(102);
+ expect(clampHeight(102, bounds)).toBe(102);
+ expect(clampHeight(5, bounds)).toBe(20);
+ expect(clampHeight(9999, bounds)).toBe(200);
+ });
+ it('falls back to the low end rather than NaN', () => {
+ expect(clampHeight('tall', bounds)).toBe(20);
+ });
+});
+
+describe('defaultHeight', () => {
+ const presets = [
+ { id: 'keychain', heightMm: 35 },
+ { id: 'desk', heightMm: 80 },
+ { id: 'shelf', heightMm: 140 },
+ { id: 'statement', heightMm: 200 },
+ ];
+ it('opens on the largest preset that fits, not the smallest thing the machine makes', () => {
+ expect(defaultHeight(sliderBounds({ ...FIT, minHeightMm: 20, maxHeightMm: 180 }), presets)).toBe(140);
+ });
+ it('falls back to the middle of the track when no preset is in range', () => {
+ const bounds = sliderBounds({ ...FIT, minHeightMm: 150, maxHeightMm: 170 });
+ expect(defaultHeight(bounds, presets)).toBe(160);
+ });
+});
+
+describe('scaleReference', () => {
+ it('picks the everyday object closest in magnitude, so both silhouettes stay legible', () => {
+ expect(scaleReference(35, REFERENCES).reference.id).toBe('coin');
+ expect(scaleReference(110, REFERENCES).reference.id).toBe('mug');
+ expect(scaleReference(200, REFERENCES).reference.id).toBe('hand');
+ });
+ it('draws the taller of the two at full height and the other in true proportion', () => {
+ const view = scaleReference(190, REFERENCES, 200); // beside a 180 mm hand
+ expect(view.modelPx).toBe(200);
+ expect(view.referencePx).toBe(Math.round((180 / 190) * 200));
+ });
+ it('never draws a silhouette too small to see', () => {
+ expect(scaleReference(12, [{ id: 'person', name: 'A person', heightMm: 1750 }], 200).modelPx).toBeGreaterThanOrEqual(6);
+ });
+ it('says the comparison out loud in both directions', () => {
+ expect(scaleReference(190, REFERENCES).caption).toMatch(/1\.1x a hand/);
+ expect(scaleReference(48, REFERENCES).caption).toMatch(/percent of coffee mug/);
+ });
+ it('returns nothing rather than a broken drawing', () => {
+ expect(scaleReference(0, REFERENCES)).toBeNull();
+ expect(scaleReference(100, [])).toBeNull();
+ });
+});
+
+describe('quoteRows', () => {
+ const quote = {
+ lines: [
+ { id: 'setup', label: 'Build setup', detail: 'Charged once', amount: 6 },
+ { id: 'material', label: 'Standard resin', detail: '62.5 cm3', amount: 34.38, estimate: false },
+ { id: 'holder_discount', label: '$THREE holder discount', detail: '', amount: -6.06 },
+ { id: 'shipping', label: 'Shipping', detail: '1.2 kg', amount: 12.45 },
+ ],
+ };
+ it('renders every engine line in order, with no arithmetic of its own', () => {
+ const rows = quoteRows(quote);
+ expect(rows.map((r) => r.id)).toEqual(['setup', 'material', 'holder_discount', 'shipping']);
+ expect(rows.map((r) => r.amountText)).toEqual(['6.00', '34.38', '-6.06', '12.45']);
+ });
+ it('marks a discount as a credit so it can be toned differently', () => {
+ expect(quoteRows(quote).find((r) => r.id === 'holder_discount').credit).toBe(true);
+ expect(quoteRows(quote).find((r) => r.id === 'setup').credit).toBe(false);
+ });
+ it('is empty for a quote that never arrived', () => {
+ expect(quoteRows(null)).toEqual([]);
+ });
+});
+
+describe('printabilityView', () => {
+ const report = {
+ version: 1,
+ score: 86,
+ manifold: true,
+ shells: 2,
+ min_wall_mm: 11.7,
+ bbox_mm: { x: 1188, y: 1985, z: 626 },
+ has_textures: true,
+ deductions: [
+ { id: 'open_edges', label: 'Open edges', detail: 'The surface has 42 holes.', points: 8 },
+ { id: 'loose_shells', label: 'Loose pieces', detail: 'Two shells are not joined.', points: 6 },
+ ],
+ };
+ it('bands the score generously at the top, because 80 prints beautifully', () => {
+ expect(printabilityView({ ...report, score: 94 }).tone).toBe('great');
+ expect(printabilityView({ ...report, score: 86 }).tone).toBe('good');
+ expect(printabilityView({ ...report, score: 50 }).tone).toBe('fair');
+ expect(printabilityView({ ...report, score: 10 }).tone).toBe('poor');
+ });
+ it('only offers a repair for the deductions a repair pass can actually resolve', () => {
+ const view = printabilityView(report);
+ expect(view.issues.find((i) => i.id === 'open_edges').repairable).toBe(true);
+ expect(view.issues.find((i) => i.id === 'loose_shells').repairable).toBe(false);
+ expect(view.repairableCount).toBe(1);
+ });
+ it('reports loose pieces as a fact a buyer should see, not a silent detail', () => {
+ const facts = printabilityView(report).facts;
+ expect(facts.find((f) => f.id === 'shells').value).toBe('2 loose pieces');
+ expect(facts.find((f) => f.id === 'shells').ok).toBe(false);
+ });
+ it('holds the score inside 0 to 100 whatever it is handed', () => {
+ expect(printabilityView({ ...report, score: 140 }).score).toBe(100);
+ expect(printabilityView({ ...report, score: -5 }).score).toBe(0);
+ });
+});
+
+describe('arScaleAttribute', () => {
+ it('turns the quote scale into the three-axis attribute model-viewer reads', () => {
+ expect(arScaleAttribute(0.0604286)).toBe('0.0604286 0.0604286 0.0604286');
+ });
+ it('refuses a scale that would place nothing, rather than defaulting to 1', () => {
+ expect(arScaleAttribute(0)).toBeNull();
+ expect(arScaleAttribute(-2)).toBeNull();
+ expect(arScaleAttribute(undefined)).toBeNull();
+ });
+});
+
+describe('rejectionView', () => {
+ it('carries every failure with its own fix, not just the first', () => {
+ const view = rejectionView({
+ code: 'walls_too_thin',
+ message: 'The thinnest wall would be 0.35 mm.',
+ failures: [
+ { code: 'walls_too_thin', message: 'The thinnest wall would be 0.35 mm.', fix: 'Print at 43 mm or larger.', measured: 0.35, required: 0.6 },
+ ],
+ alternatives: [{ id: 'nylon-sls', name: 'SLS nylon (PA12)', class: 'sls_nylon' }],
+ });
+ expect(view.fixes[0].fix).toMatch(/43 mm/);
+ expect(view.alternatives[0].id).toBe('nylon-sls');
+ expect(view.offerRepair).toBe(true);
+ });
+ it('does not offer a repair for a failure a repair cannot fix', () => {
+ const view = rejectionView({
+ code: 'exceeds_build_volume',
+ message: 'Too wide.',
+ failures: [{ code: 'exceeds_build_volume', message: 'Too wide.', fix: 'Print at 96 mm or under.' }],
+ alternatives: [],
+ });
+ expect(view.offerRepair).toBe(false);
+ });
+});
+
+describe('timelineView', () => {
+ const events = [
+ { status: 'quoted', created_at: '2026-09-01T10:00:00Z', note: null },
+ { status: 'paid', created_at: '2026-09-01T10:04:00Z', note: null },
+ { status: 'screening', created_at: '2026-09-01T10:05:00Z', note: null },
+ { status: 'submitted', created_at: '2026-09-01T12:00:00Z', note: 'Sent to the floor.' },
+ ];
+ it('marks reached steps done, the live one current, and the rest upcoming', () => {
+ const view = timelineView({ status: 'submitted' }, events);
+ const byId = Object.fromEntries(view.steps.map((s) => [s.id, s.state]));
+ expect(byId.quoted).toBe('done');
+ expect(byId.submitted).toBe('current');
+ expect(byId.printing).toBe('upcoming');
+ });
+ it('carries the real timestamp and the operator note onto the step', () => {
+ const step = timelineView({ status: 'submitted' }, events).steps.find((s) => s.id === 'submitted');
+ expect(step.at).toBe('2026-09-01T12:00:00Z');
+ expect(step.note).toBe('Sent to the floor.');
+ });
+ it('stops the rail where a branch happened instead of promising the rest', () => {
+ const view = timelineView({ status: 'rejected' }, [...events, { status: 'rejected', created_at: '2026-09-01T13:00:00Z', note: 'Failed the fabrication gate.' }]);
+ expect(view.branch.status).toBe('rejected');
+ expect(view.branch.event.note).toBe('Failed the fabrication gate.');
+ expect(view.steps.find((s) => s.id === 'printing').state).toBe('stopped');
+ expect(view.steps.find((s) => s.id === 'submitted').state).toBe('done');
+ });
+ it('handles an order with no events at all', () => {
+ const view = timelineView({ status: 'created' }, []);
+ expect(view.branch).toBeNull();
+ expect(view.steps.every((s) => s.state === 'upcoming')).toBe(true);
+ });
+});
+
+describe('validateShipping', () => {
+ const good = { name: 'Ada Lovelace', line1: '1 Analytical Way', city: 'London', postal_code: 'EC1A 1BB', country: 'GB' };
+ it('accepts the minimum the server accepts', () => {
+ expect(validateShipping(good)).toEqual({ valid: true, errors: {} });
+ });
+ it('requires exactly the fields api/_lib/print-store.js requires', () => {
+ for (const field of ['name', 'line1', 'city', 'postal_code', 'country']) {
+ const check = validateShipping({ ...good, [field]: '' });
+ expect(check.valid).toBe(false);
+ expect(check.errors[field]).toBeTruthy();
+ }
+ });
+ it('leaves the optional fields optional', () => {
+ expect(validateShipping({ ...good, line2: '', region: '', phone: '' }).valid).toBe(true);
+ });
+ it('rejects a country that is not a two-letter code, the way the server does', () => {
+ expect(validateShipping({ ...good, country: 'United Kingdom' }).errors.country).toBeTruthy();
+ });
+ it('holds every field to the 120 characters the column stores', () => {
+ expect(validateShipping({ ...good, line1: 'x'.repeat(121) }).errors.line1).toBeTruthy();
+ expect(validateShipping({ ...good, phone: 'x'.repeat(121) }).errors.phone).toBeTruthy();
+ });
+ it('offers only countries the quote engine can price', () => {
+ expect(SHIPPING_COUNTRIES.every((c) => /^[A-Z]{2}$/.test(c.code))).toBe(true);
+ expect(SHIPPING_COUNTRIES.some((c) => c.code === 'US')).toBe(true);
+ });
+});