From 72f9f5fe84ed95901df838afe6ae179fdbdedd97 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Tue, 2 Apr 2024 11:52:55 +0700 Subject: [PATCH] feat: edit branch endpoint --- src/controllers/branch/branch-controller.ts | 56 +++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/controllers/branch/branch-controller.ts b/src/controllers/branch/branch-controller.ts index 6257321..197ec21 100644 --- a/src/controllers/branch/branch-controller.ts +++ b/src/controllers/branch/branch-controller.ts @@ -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 } });