Add permits module

This commit is contained in:
2024-12-21 16:26:01 +05:30
parent cc2665544b
commit 6c1399ddd4
9 changed files with 412 additions and 2 deletions

View File

@@ -0,0 +1,116 @@
import { PageQueryParams } from "../pagination";
import { generateId } from "../utils/id";
import {
CreatePermitInput,
permitModel,
UpdatePermitInput,
} from "./permit.schema";
export async function createPermit(input: CreatePermitInput, tenantId: string) {
const permit = await permitModel.create({
tenantId: tenantId,
pid: generateId(),
...input,
});
return permit;
}
export async function getPermit(permitId: string, tenantId: string) {
return await permitModel
.findOne({
$and: [{ tenantId: tenantId }, { pid: permitId }],
})
.populate("county")
.populate("client")
.populate("assignedTo");
}
export async function listPermits(params: PageQueryParams, tenantId: string) {
const page = params.page || 1;
const pageSize = params.pageSize || 10;
const permitsList = await permitModel.aggregate([
{
$match: { $and: [{ tenantId: tenantId }] },
},
{
$lookup: {
from: "organizations",
localField: "county",
foreignField: "_id",
as: "countyRec",
},
},
{
$lookup: {
from: "organizations",
localField: "client",
foreignField: "_id",
as: "clientRec",
},
},
{
$lookup: {
from: "permits",
localField: "assignedTo",
foreignField: "_id",
as: "assignedRec",
},
},
{
$project: {
_id: 0,
pid: 1,
permitNumber: 1,
county: { $arrayElemAt: ["$countyRec", 0] },
client: { $arrayElemAt: ["$clientRec", 0] },
permitDate: 1,
stage: 1,
status: 1,
assignedTo: { $arrayElemAt: ["$assignedRec", 0] },
},
},
{
$facet: {
metadata: [{ $count: "count" }],
data: [{ $skip: (page - 1) * pageSize }, { $limit: pageSize }],
},
},
]);
return {
permits: permitsList[0].data,
metadata: {
count: permitsList[0].metadata[0].count,
page,
pageSize,
},
};
}
export async function updatePermit(
input: UpdatePermitInput,
permitId: string,
tenantId: string
) {
const updatePermitResult = await permitModel
.findOneAndUpdate(
{
$and: [{ tenantId: tenantId }, { pid: permitId }],
},
{ ...input, updatedAt: new Date() },
{ new: true }
)
.populate("county")
.populate("client")
.populate("assignedTo");
return updatePermitResult;
}
export async function deletePermit(permitId: string, tenantId: string) {
return await permitModel.deleteOne({
$and: [{ tenantId: tenantId }, { pid: permitId }],
});
}