ManiCandles/src/lib/commerce.ts

312 lines
8.5 KiB
TypeScript

import { z } from "zod";
export const uuid = z.string().uuid().toLowerCase();
export const currency = z.enum(["INR", "USD", "EUR", "GBP"]);
export const decimal = z.string().regex(/^\d+(?:\.\d{1,2})?$/);
export const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/);
const text = (max: number, min = 1) =>
z
.string()
.trim()
.min(min)
.max(max)
.regex(/^[^<>\u0000-\u001F\u007F]*$/, "Plain text only");
export const addressInput = z
.object({
recipient: text(160),
line1: text(200),
line2: text(200, 0),
city: text(100),
region: text(100),
postalCode: text(20).regex(/^[A-Za-z0-9 -]+$/),
countryCode: z
.string()
.toUpperCase()
.regex(/^[A-Z]{2}$/),
phone: z.string().regex(/^\+[1-9]\d{6,14}$/),
isDefault: z.boolean(),
})
.strict();
export const address = addressInput.extend({ id: uuid }).strip();
export type Address = z.infer<typeof address>;
export const cart = z.object({
version: z.number().int().nonnegative(),
lines: z.array(
z.object({
variantId: uuid,
quantity: z.number().int().positive(),
variant: z.object({
name: z.string(),
sku: z.string(),
price: decimal,
currency,
active: z.boolean(),
product: z.object({ name: z.string(), status: z.string() }),
}),
}),
),
});
export type Cart = z.infer<typeof cart>;
export const couponCode = text(40)
.toUpperCase()
.regex(/^[A-Z0-9][A-Z0-9_-]{0,39}$/);
export const checkoutInput = z
.object({
cartVersion: z.number().int().min(0).max(2147483646),
addressId: uuid,
idempotencyKey: uuid,
couponCode: couponCode.optional(),
})
.strict();
export type CheckoutIntent = z.infer<typeof checkoutInput>;
export function checkoutIntent(
input: Omit<CheckoutIntent, "idempotencyKey">,
key: string,
) {
return Object.freeze(checkoutInput.parse({ ...input, idempotencyKey: key }));
}
export function money(value: string) {
decimal.parse(value);
const [whole, fraction = ""] = value.split(".");
return `${BigInt(whole)}.${fraction.padEnd(2, "0")}`;
}
export function moneyTotal(lines: { price: string; quantity: number }[]) {
const total = lines.reduce((sum, line) => {
z.number().int().nonnegative().parse(line.quantity);
return (
sum + BigInt(money(line.price).replace(".", "")) * BigInt(line.quantity)
);
}, 0n);
return `${total / 100n}.${(total % 100n).toString().padStart(2, "0")}`;
}
export const orderSummary = z.object({
id: uuid,
status: z.enum(["PENDING_PAYMENT", "CANCELLED", "EXPIRED"]),
currency,
merchandiseTotal: decimal,
createdAt: z.string(),
expiresAt: z.string(),
});
export const order = orderSummary.extend({
subtotal: decimal,
discount: decimal,
pricingStatus: z.enum(["FINALIZED", "UNFINALIZED"]),
taxTotal: decimal.nullable(),
shippingTotal: decimal.nullable(),
payableTotal: decimal.nullable(),
paymentAvailable: z.literal(false),
address: addressInput.omit({ isDefault: true }).strip(),
lines: z.array(
z.object({
variantId: uuid,
sku: z.string(),
productName: z.string(),
variantName: z.string(),
quantity: z.number().int(),
unitPrice: decimal,
lineTotal: decimal,
}),
),
});
export type Order = z.infer<typeof order>;
export const productInput = z
.object({
name: text(160),
slug: text(160).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
description: text(5000, 0),
groupIds: z
.array(uuid)
.max(20)
.refine((v) => new Set(v).size === v.length),
})
.strict();
export const groupInput = z
.object({
name: text(100),
slug: text(100).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
kind: z.enum(["CATEGORY", "COLLECTION"]),
})
.strict();
export const group = groupInput.extend({ id: uuid }).strip();
export const variantInput = z
.object({
sku: text(64)
.toUpperCase()
.regex(/^[A-Z0-9][A-Z0-9_-]*$/),
name: text(160),
price: amount.refine((v) => v !== "0.00"),
currency,
active: z.boolean(),
attributes: z
.record(
z
.string()
.regex(/^[a-z][a-z0-9_]{0,31}$/)
.refine((v) => !["constructor", "prototype"].includes(v)),
text(100),
)
.refine((v) => Object.keys(v).length <= 20),
})
.strict();
export const variant = variantInput
.extend({ id: uuid, price: decimal })
.strip();
export const adminProductSummary = productInput
.pick({ name: true, slug: true })
.extend({ id: uuid, status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]) })
.strip();
export const adminProduct = adminProductSummary.extend({
description: z.string(),
variants: z.array(variant),
groups: z.array(z.object({ group })),
});
export type AdminProduct = z.infer<typeof adminProduct>;
export const userInput = z
.object({
name: text(160),
email: z.string().email().max(254).toLowerCase(),
password: z.string().min(15).max(128),
})
.strict();
export const user = userInput.omit({ password: true }).extend({
id: uuid,
status: z.enum(["PENDING", "ACTIVE", "SUSPENDED"]),
isOwner: z.boolean(),
createdAt: z.string(),
});
export const roleInput = z
.object({
name: text(80),
permissions: z
.array(z.string())
.refine((v) => new Set(v).size === v.length),
})
.strict();
export const role = roleInput
.extend({ id: uuid, isSystem: z.boolean() })
.strip();
export const audit = z.object({
id: uuid,
actorId: uuid.nullable(),
action: z.string(),
targetId: z.string().nullable(),
createdAt: z.string(),
});
export const warehouseInput = z.object({ name: text(100) }).strict();
export const warehouse = warehouseInput.extend({ id: uuid }).strip();
export const stockInput = z
.object({ variantId: uuid, warehouseId: uuid })
.strict();
export const stock = stockInput
.extend({ id: uuid, onHand: z.number().int() })
.strip();
export const stockDetail = stock.extend({
reserved: z.number().int(),
available: z.number().int(),
});
export const adjustmentInput = z
.object({
stockItemId: uuid,
delta: z
.number()
.int()
.min(-1000000)
.max(1000000)
.refine((v) => v !== 0),
reason: text(200),
idempotencyKey: uuid,
})
.strict();
export const ledger = z.object({
id: uuid,
delta: z.number().int(),
reason: z.string(),
createdAt: z.string(),
});
export const reservationInput = z
.object({
stockItemId: uuid,
quantity: z.number().int().min(1).max(1000000),
ttlMinutes: z.number().int().min(1).max(60),
idempotencyKey: uuid,
})
.strict();
export const reservation = z.object({
id: uuid,
orderId: uuid.nullable().optional(),
stockItemId: uuid,
quantity: z.number().int(),
status: z.enum(["ACTIVE", "RELEASED", "COMMITTED", "EXPIRED"]),
expiresAt: z.string(),
});
const couponCommon = z.object({
code: couponCode,
currency,
minimumSubtotal: amount,
maxUses: z.number().int().min(1).max(1000000),
perUserLimit: z.number().int().min(1).max(100),
startsAt: z.string().datetime({ offset: true }),
endsAt: z.string().datetime({ offset: true }),
});
export const couponInput = z
.discriminatedUnion("kind", [
couponCommon
.extend({
kind: z.literal("FIXED"),
amount: amount.refine((v) => v !== "0.00"),
})
.strict(),
couponCommon
.extend({
kind: z.literal("PERCENT"),
percentBps: z.number().int().min(1).max(10000),
})
.strict(),
])
.refine((v) => Date.parse(v.endsAt) > Date.parse(v.startsAt), {
path: ["endsAt"],
message: "End must follow start",
})
.refine((v) => v.perUserLimit <= v.maxUses, {
path: ["perUserLimit"],
message: "Per-user limit exceeds total limit",
});
export const coupon = z.object({
id: uuid,
code: z.string(),
currency,
kind: z.enum(["FIXED", "PERCENT"]),
amount: decimal.nullable(),
percentBps: z.number().nullable(),
minimumSubtotal: decimal,
maxUses: z.number(),
perUserLimit: z.number(),
active: z.boolean(),
startsAt: z.string(),
endsAt: z.string(),
});
export const pricingInput = z
.object({
name: text(100),
currency,
countryCode: z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z]{2}$/),
region: text(100, 0).toUpperCase(),
taxMode: z.enum(["INCLUSIVE", "EXCLUSIVE"]),
merchandiseTaxBps: z.number().int().min(0).max(10000),
shippingFee: amount,
shippingTaxBps: z.number().int().min(0).max(10000),
freeShippingMinimum: amount.nullable(),
})
.strict();
export const pricing = pricingInput
.extend({
id: uuid,
active: z.boolean(),
shippingFee: decimal,
freeShippingMinimum: decimal.nullable(),
})
.strip();