import { buildJsonSchemas } from "fastify-zod"; import mongoose from "mongoose"; import z from "zod"; import { pageQueryParams } from "../pagination"; const rtsSchema = new mongoose.Schema({ tenantId: { type: String, required: true }, pid: { type: String, required: true, unique: true, }, documents: [ new mongoose.Schema( { files: Array, createdAt: Date, createdBy: { type: mongoose.Types.ObjectId, ref: "user", }, }, { _id: false } ), ], county: { type: mongoose.Types.ObjectId, required: true, ref: "organization", }, client: { type: mongoose.Types.ObjectId, ref: "organization", }, statusPipeline: new mongoose.Schema( { currentStage: Number, stages: [ { name: String, date: Date, description: String, }, ], }, { _id: false } ), createdAt: Date, createdBy: { type: mongoose.Types.ObjectId, ref: "user", }, }); export const rtsFields = Object.keys(rtsSchema.paths).filter( (path) => path !== "__v" ); export const rtsModel = mongoose.model("rts", rtsSchema, "rts"); const files = z .object({ pid: z.string().optional(), name: z.string(), type: z.enum(["folder", "file"]), size: z.number().optional(), files: z.array(z.lazy(() => files)).optional(), }) .superRefine((data, ctx) => { const validateRecursive = (file: any) => { if (file.type === "file" && !file.pid) { ctx.addIssue({ path: ["pid"], message: 'pid is required when type is "file"', code: z.ZodIssueCode.custom, }); } if (file.files) { file.files.forEach((nestedFile: any) => { validateRecursive(nestedFile); }); } }; validateRecursive(data); }); const rtsCreateInput = z.object({ county: z.string(), client: z.string().optional(), files: z.array(files).optional(), }); const rtsUpdateInput = z.object({ county: z.string().optional(), client: z.string().optional(), }); const rtsNewUpload = z.object({ files: z.array(files), }); export type CreateRtsInput = z.infer; export type UpdateRtsInput = z.infer; export type UploadRtsInput = z.infer; export const { schemas: rtsSchemas, $ref: $rts } = buildJsonSchemas( { rtsCreateInput, rtsUpdateInput, rtsNewUpload, pageQueryParams, }, { $id: "rts" } );