add rts routes

This commit is contained in:
2025-01-21 11:54:09 +05:30
parent 7e3218f84e
commit a54541518c
15 changed files with 653 additions and 28 deletions

88
src/rts/rts.controller.ts Normal file
View File

@@ -0,0 +1,88 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { CreateRtsInput, UpdateRtsInput, UploadRtsInput } from "./rts.schema";
import {
createRts,
deleteRts,
getRts,
listRts,
newUpload,
updateRts,
} from "./rts.service";
import { PageQueryParams } from "../pagination";
export async function createRtsHandler(req: FastifyRequest, res: FastifyReply) {
const input = req.body as CreateRtsInput;
try {
const rts = await createRts(input, req.user);
return res.code(201).send(rts);
} catch (err) {
return err;
}
}
export async function getRtsHandler(req: FastifyRequest, res: FastifyReply) {
const { rtsId } = req.params as { rtsId: string };
try {
const rts = await getRts(rtsId, req.user.tenantId);
if (rts == null) return res.code(404).send({ error: "resource not found" });
return res.code(200).send(rts);
} catch (err) {
return err;
}
}
export async function listRtsHandler(req: FastifyRequest, res: FastifyReply) {
const queryParams = req.query as PageQueryParams;
try {
const rtsList = await listRts(queryParams, req.user.tenantId);
return res.code(200).send(rtsList);
} catch (err) {
return err;
}
}
export async function updateRtsHandler(req: FastifyRequest, res: FastifyReply) {
const input = req.body as UpdateRtsInput;
const { rtsId } = req.params as { rtsId: string };
try {
const updatedRts = await updateRts(rtsId, input, req.user.tenantId);
if (!updatedRts) return res.code(404).send({ error: "resource not found" });
return res.code(200).send(updateRts);
} catch (err) {
return err;
}
}
export async function deleteRtsHandler(req: FastifyRequest, res: FastifyReply) {
const { rtsId } = req.params as { rtsId: string };
try {
const deleteResult = await deleteRts(rtsId, req.user.tenantId);
if (deleteResult.deletedCount == 0)
return res.code(404).send({ error: "resource not found" });
return res.code(204).send();
} catch (err) {
return err;
}
}
export async function newFilesHandler(req: FastifyRequest, res: FastifyReply) {
const input = req.body as UploadRtsInput;
const { rtsId } = req.params as { rtsId: string };
try {
const updatedRts = await newUpload(rtsId, input, req.user);
if (!updatedRts) return res.code(404).send({ error: "resource not found" });
return res.code(200).send(updateRts);
} catch (err) {
return err;
}
}

98
src/rts/rts.route.ts Normal file
View File

@@ -0,0 +1,98 @@
import { FastifyInstance } from "fastify";
import { $rts } from "./rts.schema";
import {
createRtsHandler,
deleteRtsHandler,
getRtsHandler,
listRtsHandler,
newFilesHandler,
updateRtsHandler,
} from "./rts.controller";
import { hideFields } from "../auth";
export async function rtsRoutes(fastify: FastifyInstance) {
fastify.post(
"/",
{
schema: {
body: $rts("rtsCreateInput"),
},
config: { requiredClaims: ["rts:write"] },
preHandler: [fastify.authorize],
},
createRtsHandler
);
fastify.get(
"/:rtsId",
{
schema: {
params: {
type: "object",
properties: {
rtsId: { type: "string" },
},
},
},
config: { requiredClaims: ["rts:read"] },
preHandler: [fastify.authorize],
},
getRtsHandler
);
fastify.get(
"/",
{
schema: {
querystring: $rts("pageQueryParams"),
},
config: { requiredClaims: ["rts:read"] },
preHandler: [fastify.authorize],
},
listRtsHandler
);
fastify.patch(
"/:rtsId",
{
schema: {
params: {
type: "object",
properties: { rtsId: { type: "string" } },
},
body: $rts("rtsUpdateInput"),
},
},
updateRtsHandler
);
fastify.delete(
"/:rtsId",
{
schema: {
params: {
type: "object",
properties: { rtsId: { type: "string" } },
},
},
config: { requiredClaims: ["rts:delete"] },
preHandler: [fastify.authorize],
},
deleteRtsHandler
);
fastify.post(
"/:rtsId/files",
{
schema: {
body: $rts("rtsNewUpload"),
},
config: { requiredClaims: ["rts:write"] },
preHandler: [fastify.authorize],
},
newFilesHandler
);
fastify.addHook("onSend", hideFields("rts"));
}

115
src/rts/rts.schema.ts Normal file
View File

@@ -0,0 +1,115 @@
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<typeof rtsCreateInput>;
export type UpdateRtsInput = z.infer<typeof rtsUpdateInput>;
export type UploadRtsInput = z.infer<typeof rtsNewUpload>;
export const { schemas: rtsSchemas, $ref: $rts } = buildJsonSchemas(
{
rtsCreateInput,
rtsUpdateInput,
rtsNewUpload,
pageQueryParams,
},
{ $id: "rts" }
);

154
src/rts/rts.service.ts Normal file
View File

@@ -0,0 +1,154 @@
import {
CreateRtsInput,
rtsFields,
rtsModel,
UpdateRtsInput,
UploadRtsInput,
} from "./rts.schema";
import { AuthenticatedUser } from "../auth";
import { generateId } from "../utils/id";
import { getFilterObject, getSortObject, PageQueryParams } from "../pagination";
export async function createRts(
input: CreateRtsInput,
user: AuthenticatedUser
) {
if (!input.files) {
return await rtsModel.create({
...input,
tenantId: user.tenantId,
pid: generateId(),
createdAt: new Date(),
createdBy: user.userId ?? null,
});
} else {
return await rtsModel.create({
tenantId: user.tenantId,
pid: generateId(),
county: input.county,
client: input.client,
documents: [
{
files: input.files,
createdAt: new Date(),
createdBy: user.userId ?? null,
},
],
createdAt: new Date(),
createdBy: user.userId ?? null,
});
}
}
export async function getRts(id: string, tenantId: string) {
return await rtsModel
.findOne({ pid: id, tenantId: tenantId })
.populate({ path: "createdBy", select: "pid name avatar" });
}
export async function listRts(params: PageQueryParams, tenantId: string) {
const page = params.page || 1;
const pageSize = params.pageSize || 10;
const sortObj = getSortObject(params, rtsFields);
const filterObj = getFilterObject(params, rtsFields);
const rtsList = await rtsModel.aggregate([
{
$match: { $and: [{ tenantId: tenantId }, ...filterObj] },
},
{
$lookup: {
from: "organizations",
localField: "county",
foreignField: "_id",
as: "countyRec",
pipeline: [{ $project: { _id: 1, pid: 1, name: 1, type: 1 } }],
},
},
{
$lookup: {
from: "organizations",
localField: "client",
foreignField: "_id",
as: "clientRec",
pipeline: [{ $project: { _id: 1, pid: 1, name: 1, type: 1 } }],
},
},
{
$lookup: {
from: "users",
localField: "createdBy",
foreignField: "_id",
as: "createdRec",
pipeline: [{ $project: { _id: 1, pid: 1, name: 1, avatar: 1 } }],
},
},
{
$project: {
_id: 1,
pid: 1,
county: { $arrayElemAt: ["$countyRec", 0] },
client: { $arrayElemAt: ["$clientRec", 0] },
statusPipeline: 1,
createdAt: 1,
createdBy: { $arrayElemAt: ["$createdRec", 0] },
},
},
{
$facet: {
metadata: [{ $count: "count" }],
data: [
{ $skip: (page - 1) * pageSize },
{ $limit: pageSize },
{ $sort: sortObj },
],
},
},
]);
if (rtsList[0].data.length === 0)
return { rts: [], metadata: { count: 0, page, pageSize } };
return {
rts: rtsList[0]?.data,
metadata: {
count: rtsList[0].metadata[0].count,
page,
pageSize,
},
};
}
export async function updateRts(
id: string,
input: UpdateRtsInput,
tenantId: string
) {
return await rtsModel.findOneAndUpdate(
{ pid: id, tenantId: tenantId },
input
);
}
export async function deleteRts(id: string, tenantId: string) {
return await rtsModel.deleteOne({ pid: id, tenantId: tenantId });
}
export async function newUpload(
id: string,
newUpload: UploadRtsInput,
user: AuthenticatedUser
) {
return await rtsModel.findOneAndUpdate(
{ pid: id, tenantId: user.tenantId },
{
$push: {
documents: {
files: newUpload.files,
createdAt: new Date(),
createdBy: user.userId,
},
},
}
);
}