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 quantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Enter exactly three decimal places").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, })), });