feat: edit branch endpoint

This commit is contained in:
Methapon2001 2024-04-02 11:52:55 +07:00
parent c841fa84ed
commit 72f9f5fe84

View file

@ -140,6 +140,62 @@ export class BranchController extends Controller {
});
}
@Patch("{branchId}")
async editBranch(
@Request() req: RequestWithUser,
@Body() body: BranchUpdate,
@Path() branchId: string,
) {
if (body.subDistrictId || body.districtId || body.provinceId || body.headOfficeId) {
const [province, district, subDistrict, branch] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId || undefined } }),
prisma.district.findFirst({ where: { id: body.districtId || undefined } }),
prisma.subDistrict.findFirst({ where: { id: body.subDistrictId || undefined } }),
prisma.branch.findFirst({ where: { id: body.headOfficeId || undefined } }),
]);
if (body.provinceId && !province)
throw new HttpError(HttpStatus.BAD_REQUEST, "Province cannot be found.");
if (body.districtId && !district)
throw new HttpError(HttpStatus.BAD_REQUEST, "District cannot be found.");
if (body.subDistrictId && !subDistrict)
throw new HttpError(HttpStatus.BAD_REQUEST, "Sub-district cannot be found.");
if (body.headOfficeId && !branch)
throw new HttpError(HttpStatus.BAD_REQUEST, "Head branch cannot be found.");
}
const { provinceId, districtId, subDistrictId, headOfficeId, ...rest } = body;
const record = await prisma.branch.update({
include: { province: true, district: true, subDistrict: true },
data: {
...rest,
isHeadOffice: headOfficeId === null,
province: {
connect: provinceId ? { id: provinceId } : undefined,
disconnect: provinceId === null || undefined,
},
district: {
connect: districtId ? { id: districtId } : undefined,
disconnect: districtId === null || undefined,
},
subDistrict: {
connect: subDistrictId ? { id: subDistrictId } : undefined,
disconnect: subDistrictId === null || undefined,
},
headOffice: {
connect: headOfficeId ? { id: headOfficeId } : undefined,
disconnect: headOfficeId === null || undefined,
},
updateBy: req.user.name,
},
where: { id: branchId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.");
}
return record;
}
@Delete("{branchId}")
async deleteBranch(@Path() branchId: string) {
const record = await prisma.branch.findFirst({ where: { id: branchId } });