2023-10-02 22:45:16 +02:00

73 lines
2.4 KiB
TypeScript

import HttpCodes from "@Common/system/controller-pattern/HttpCodes";
import { NextFunction, Request, Response } from "express";
import Container from "typedi";
import OfficeFoldersService from "@Services/super-admin/OfficeFoldersService/OfficeFoldersService";
import DeedTypesService from "@Services/super-admin/DeedTypesService/DeedTypesService";
export default async function folderHandler(req: Request, response: Response, next: NextFunction) {
try {
const officeId = req.body.user.office_Id;
const userId = req.body.user.userId;
const splittedReqPath = req.path && req.path.split("/");
const uid = (splittedReqPath as string[]).pop();
const office = req.body.office;
const officeFolderNumber = req.body.folder_number;
const deed = req.body.deed;
if (office && office.uid != officeId) {
response.status(HttpCodes.UNAUTHORIZED).send("Unauthorized with this office");
return;
}
if (deed && deed.deed_type) {
const deedTypeService = Container.get(DeedTypesService);
const deedTypeWithOffice = await deedTypeService.getByUidWithOffice(deed.deed_type.uid!);
if (!deedTypeWithOffice) {
response.status(HttpCodes.NOT_FOUND).send("Deed type not found");
return;
}
if (deedTypeWithOffice.office.uid != officeId) {
response.status(HttpCodes.UNAUTHORIZED).send("Unauthorized with this deed type");
return;
}
}
const officeFolderService = Container.get(OfficeFoldersService);
if (officeFolderNumber && req.method == "POST") {
const officeFoldersWithSameNumber = await officeFolderService.get({
where: { folder_number: officeFolderNumber, office: { uid: officeId } },
});
if (officeFoldersWithSameNumber.length) {
response.status(HttpCodes.BAD_REQUEST).send("Office number already used");
return;
}
}
if (uid) {
const officeFolder = await officeFolderService.getByUidWithStakeholders(uid!);
if (!officeFolder) {
response.status(HttpCodes.NOT_FOUND).send("Office folder not found");
return;
}
if (officeFolder.office_uid != officeId) {
response.status(HttpCodes.UNAUTHORIZED).send("Unauthorized with this office");
return;
}
if(!officeFolder.stakeholders.find(stakeholder => stakeholder.uid === userId)) {
response.status(HttpCodes.UNAUTHORIZED).send("Unauthorized with this user");
return;
}
}
next();
} catch (error) {
console.log(error);
response.status(HttpCodes.INTERNAL_ERROR).send("Internal server error");
return;
}
}