返回 CodeWhale
model.ts
根目录 / web / lib / merch / model.ts
1 import { MERCH_COUNTRIES, MERCH_PRODUCTS, MERCH_SIZES, MERCH_TARGET_PRICE } from "./catalog";
2 import { validateContributorIdentity } from "../contributor-merch";
3 import { MERCH_LANGUAGES } from "../content/contributor-merch";
4 import type { MerchConfig, QuoteInput, CountryRoute } from "./types";
5
6 export class MerchError extends Error {
7 constructor(readonly status: number, readonly code: string, message: string) { super(message); }
8 }
9 export function object(value: unknown): Record<string, unknown> {
10 if (!value || typeof value !== "object" || Array.isArray(value)) throw new MerchError(422, "invalid_request", "Check the form and try again.");
11 return value as Record<string, unknown>;
12 }
13 function text(value: unknown, max: number, optional = false): string {
14 if ((value === undefined || value === "") && optional) return "";
15 if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw new MerchError(422, "invalid_request", "Check the address and try again.");
16 return value.trim();
17 }
18 export function validateQuoteInput(raw: unknown): QuoteInput {
19 const value = object(raw);
20 const product = MERCH_PRODUCTS.find(p => p.id === value.productId);
21 if (!product || product.kind === "concept" || product.collection !== "launch") throw new MerchError(422, "product_unavailable", "This product is not ready to order.");
22 if (!(MERCH_SIZES as readonly string[]).includes(String(value.size)) || value.color !== "White" || !Number.isInteger(value.quantity) || Number(value.quantity) < 1 || Number(value.quantity) > 5) throw new MerchError(422, "invalid_variant", "Select an available size and quantity.");
23 const country = text(value.country, 2);
24 if (!MERCH_COUNTRIES.some(c => c.code === country)) throw new MerchError(422, "country_unavailable", "This destination needs a shipping review.");
25 const address = object(value.address);
26 const input: QuoteInput = {
27 productId: product.id, size: String(value.size), color: "White", quantity: Number(value.quantity), country,
28 address: { name: text(address.name, 100), line1: text(address.line1, 150), line2: text(address.line2, 150, true), city: text(address.city, 100), region: text(address.region, 100, true), postalCode: text(address.postalCode, 24, true), phone: text(address.phone, 40) },
29 };
30 if (country === "US" || country === "CA") {
31 if (!input.address.region || !input.address.postalCode) throw new MerchError(422, "invalid_address", "Add your state or province and postcode.");
32 }
33 if (product.kind === "contributor") {
34 const c = object(value.contributor);
35 const github = text(c.github, 50, true), contribution = text(c.contribution, 2048, true);
36 if (validateContributorIdentity({ github, contribution }) || !MERCH_LANGUAGES.some(l => l.code === c.language) || !Number.isInteger(c.phraseIndex) || Number(c.phraseIndex) < 0 || Number(c.phraseIndex) > 2) throw new MerchError(422, "invalid_contributor", "Enter a GitHub identity or contribution link and select a print phrase.");
37 input.contributor = { github, contribution, language: String(c.language), phraseIndex: Number(c.phraseIndex) };
38 }
39 return input;
40 }
41 export function parseConfig(raw: string | undefined): MerchConfig | null {
42 if (!raw) return null;
43 try {
44 const value = JSON.parse(raw) as MerchConfig;
45 const origin = new URL(value.siteOrigin);
46 if (!["test", "live"].includes(value.mode) || typeof value.checkoutEnabled !== "boolean" || origin.pathname !== "/" || origin.search || origin.hash || origin.username || origin.password || !(origin.protocol === "https:" || (value.mode === "test" && origin.protocol === "http:" && ["localhost", "127.0.0.1"].includes(origin.hostname))) || !value.countries || !value.products || Array.isArray(value.countries) || Array.isArray(value.products)) return null;
47 return value;
48 } catch { return null; }
49 }
50 export function reviewedRoute(config: MerchConfig, input: QuoteInput) {
51 const route = config.countries[input.country], product = config.products[input.productId]?.[input.country];
52 const designCode = input.productId === "contributor" && input.contributor ? product?.contributorDesigns?.[input.contributor.language]?.[input.contributor.phraseIndex] : product?.designCode;
53 if (!route || product?.approved !== true || !designCode || !product.skuBySize?.[input.size] || route.taxReviewed !== true || route.addressPolicyReviewed !== true || route.supplierPricesUsdReviewed !== true || !Array.isArray(route.allowedPostalPrefixes) || !route.allowedPostalPrefixes.length || route.allowedPostalPrefixes.some(p => typeof p !== "string" || !p.trim()) || !route.taxNote || route.taxNote.length > 250 || !route.regionCode || !route.shippingLevelCode || !["cny", "usd"].includes(route.currency) || ![route.usdExchangeRate, route.feeRate, route.flatFeeUsd, product.productionCostUsd].every(Number.isFinite) || route.usdExchangeRate <= 0 || (route.currency === "usd" && route.usdExchangeRate !== 1) || route.feeRate < 0 || route.feeRate >= .2 || route.flatFeeUsd < 0 || product.productionCostUsd <= 0) throw new MerchError(409, "route_unavailable", "This design and destination are still awaiting a shipping and print review.");
54 const postcode = input.address.postalCode.replace(/\s/g, "").toUpperCase();
55 if (route.blockedPostalPrefixes?.some(p => postcode.startsWith(p.toUpperCase())) || (route.allowedPostalPrefixes?.length && !route.allowedPostalPrefixes.some(p => postcode.startsWith(p.toUpperCase())))) throw new MerchError(409, "address_unavailable", "This address needs a separate delivery quote.");
56 return { route, product, designCode };
57 }
58 export function priceQuote(input: QuoteInput, route: CountryRoute, productionUsd: number, shippingUsd: number) {
59 if (![productionUsd, shippingUsd].every(Number.isFinite) || productionUsd <= 0 || shippingUsd < 0) throw new MerchError(503, "quote_unavailable", "Shipping prices are temporarily unavailable.");
60 const shipping = Math.ceil(shippingUsd * route.usdExchangeRate * 100);
61 const merchandise = input.productId === "contributor" ? Math.ceil(productionUsd * route.usdExchangeRate * 100) : MERCH_TARGET_PRICE[route.currency] * input.quantity;
62 const base = merchandise + shipping;
63 const total = input.productId === "contributor" ? Math.ceil((base + route.flatFeeUsd * route.usdExchangeRate * 100) / (1 - route.feeRate)) : base;
64 if (!Number.isSafeInteger(total) || total <= 0 || total > 1000000) throw new MerchError(503, "quote_unavailable", "This order needs a separate quote.");
65 if (input.productId !== "contributor") {
66 const grossUsd = total / (route.usdExchangeRate * 100), itemUsd = merchandise / (route.usdExchangeRate * 100);
67 const contributionUsd = grossUsd - productionUsd - shippingUsd - grossUsd * route.feeRate - route.flatFeeUsd - itemUsd * .05;
68 if (contributionUsd < itemUsd * .30) throw new MerchError(409, "route_unavailable", "This destination needs a separate price review.");
69 }
70 return { merchandise, shipping, processing: total - base, total };
71 }
72
72 lines TYPESCRIPT