49 lines
2.0 KiB
TypeScript
49 lines
2.0 KiB
TypeScript
import { z } from "zod";
|
|
import { uuid } from "./commerce.ts";
|
|
|
|
export const maxDocumentBytes = 2 * 1024 * 1024;
|
|
const pdfFilename = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,115}\.pdf$/);
|
|
const decisionOutcome = z.enum(["APPROVED", "REJECTED"]);
|
|
|
|
export const documentInput = z.object({
|
|
code: z.string().trim().max(32).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/).toUpperCase(),
|
|
kind: z.enum(["REGISTRATION", "TAX_CERTIFICATE", "COMPLIANCE_CERTIFICATE", "OTHER"]),
|
|
title: z.string().trim().min(1).max(160),
|
|
}).strict();
|
|
|
|
export const supplierDocument = documentInput.extend({ id: uuid }).strip();
|
|
export const documentVersion = z.object({
|
|
id: uuid,
|
|
uploadedById: uuid,
|
|
version: z.number().int().min(1).max(20),
|
|
filename: pdfFilename,
|
|
mimeType: z.literal("application/pdf"),
|
|
size: z.number().int().min(1).max(maxDocumentBytes),
|
|
createdAt: z.string().datetime(),
|
|
decision: z.object({
|
|
outcome: decisionOutcome,
|
|
reason: z.string().nullable(),
|
|
}).nullable(),
|
|
});
|
|
export const documentDetails = supplierDocument.extend({ versions: z.array(documentVersion).max(20) });
|
|
|
|
export const documentDecision = z.object({
|
|
outcome: decisionOutcome,
|
|
reason: z.string().trim().min(1).max(500).optional(),
|
|
}).strict().refine((value) => value.outcome !== "REJECTED" || Boolean(value.reason), {
|
|
path: ["reason"],
|
|
message: "Enter a reason for rejecting this version.",
|
|
});
|
|
|
|
export function prepareDocumentUpload(file: FormDataEntryValue | null) {
|
|
if (!(file instanceof File) || !file.size) throw new Error("Choose a PDF file.");
|
|
if (file.size > maxDocumentBytes) throw new Error("Choose a PDF up to 2 MiB.");
|
|
if (!pdfFilename.safeParse(file.name).success) {
|
|
throw new Error("Use a simple .pdf filename with letters, numbers, dots, hyphens or underscores.");
|
|
}
|
|
if (file.type && file.type !== "application/pdf") throw new Error("Choose a PDF file.");
|
|
const body = new FormData();
|
|
body.append("file", file.type ? file : new File([file], file.name, { type: "application/pdf" }));
|
|
return body;
|
|
}
|