import { z } from "zod"; import { currency, uuid } from "./commerce.ts"; const plainText = (max: number, min = 1) => z.string().trim().min(min).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text"); const directoryInput = z.object({ name: plainText(160), code: z.string().trim().toUpperCase().max(32).regex(/^[A-Z0-9][A-Z0-9_-]*$/, "Use letters, numbers, hyphens or underscores"), active: z.boolean(), }); export const supplierInput = directoryInput.extend({ contactName: plainText(160), email: z.string().email().max(254).toLowerCase(), phone: z.string().trim().regex(/^\+?[0-9 ()-]{7,24}$/, "Enter a valid phone number").max(24), }).strict(); export const materialInput = directoryInput.extend({ kind: z.enum(["WAX", "FRAGRANCE", "WICK", "DYE", "VESSEL", "PACKAGING", "LABEL", "OTHER"]), unit: z.enum(["GRAM", "KILOGRAM", "MILLILITRE", "LITRE", "PIECE", "METRE"]), }).strict(); export const supplier = supplierInput.extend({ id: uuid }).strip(); export const material = materialInput.extend({ id: uuid }).strip(); const fixedQuantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Enter exactly three decimal places"); const quantity = fixedQuantity.refine((value) => value !== "0.000", "Quantity must be positive"); export const supplyTermsInput = z.object({ supplierSku: plainText(64, 0), leadTimeDays: z.number().int().min(0).max(365), minOrderQuantity: quantity, unitPrice: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{2}$/, "Enter exactly two decimal places"), currency, active: z.boolean(), }).strict(); // Prisma serializes Decimal values without trailing zeroes. const decimalResponse = z.string().regex(/^\d+(\.\d+)?$/); export const supplyTerms = supplyTermsInput.extend({ id: uuid, materialId: uuid, minOrderQuantity: decimalResponse, unitPrice: decimalResponse, }).strip(); export const supplierMaterial = supplyTerms.extend({ material }); export const purchaseOrderInput = z.object({ supplierId: uuid, expectedDeliveryDate: z.string().date().optional(), lines: z.array(z.object({ materialId: uuid, quantity }).strict()).min(1, "Enter a quantity for at least one material").max(100).refine( (lines) => new Set(lines.map((line) => line.materialId)).size === lines.length, "Select each material once", ), }).strict(); export const purchaseOrder = z.object({ id: uuid, reference: z.string(), status: z.enum(["DRAFT", "ISSUED", "CANCELLED"]), currency, supplier: supplier.pick({ id: true, name: true }), expectedDeliveryAt: z.string().datetime().nullable(), merchandiseTotal: decimalResponse, lines: z.array(z.object({ id: uuid, materialName: z.string(), materialCode: z.string(), quantity: decimalResponse, unit: materialInput.shape.unit, unitPrice: decimalResponse, lineTotal: decimalResponse, })), }); export const receiptInput = z.object({ deliveryNote: z.string().trim().min(1).max(80).optional(), lines: z.array(z.object({ purchaseOrderLineId: uuid, quantity }).strict()).min(1).max(100) .refine((lines) => new Set(lines.map((line) => line.purchaseOrderLineId)).size === lines.length), }).strict(); const inspection = z.object({ acceptedQuantity: decimalResponse, rejectedQuantity: decimalResponse, rejectionReason: z.string().nullable(), }); export const goodsReceipt = z.object({ id: uuid, deliveryNote: z.string().nullable(), createdAt: z.string().datetime(), lines: z.array(z.object({ id: uuid, purchaseOrderLineId: uuid, quantity: z.string().regex(/^\d+(\.\d{1,3})?$/), inspection: inspection.nullable(), })).min(1), }); const inspectionInput = z.object({ lines: z.array(z.object({ receiptLineId: uuid, acceptedQuantity: fixedQuantity, rejectedQuantity: fixedQuantity, rejectionReason: z.string().trim().min(1).max(500).optional(), }).strict()).min(1).max(100), }).strict(); const thousandths = (value: string) => { const [whole, fraction = ""] = value.split("."); return BigInt(whole + fraction.padEnd(3, "0")); }; export function parseInspection(value: unknown, receipt: z.infer) { const input = inspectionInput.parse(value); const received = new Map(receipt.lines.map((line) => [line.id, line.quantity])); if (input.lines.length !== received.size || new Set(input.lines.map((line) => line.receiptLineId)).size !== received.size) { throw new Error("Enter one decision for each receipt line."); } for (const line of input.lines) { const delivered = received.get(line.receiptLineId); if (!delivered || thousandths(line.acceptedQuantity) + thousandths(line.rejectedQuantity) !== thousandths(delivered)) { throw new Error("Accepted and rejected quantities must add up to the delivered quantity on each line."); } if (line.rejectedQuantity !== "0.000" && !line.rejectionReason) { throw new Error("Enter a rejection reason for each rejected quantity."); } } return input; }