From c841fa84edb2e4d611dc350eb0900adc9bb55746 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Tue, 2 Apr 2024 11:19:12 +0700 Subject: [PATCH] feat: create branch endpoint --- src/controllers/branch/branch-controller.ts | 35 +++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/controllers/branch/branch-controller.ts b/src/controllers/branch/branch-controller.ts index ef032bd..6257321 100644 --- a/src/controllers/branch/branch-controller.ts +++ b/src/controllers/branch/branch-controller.ts @@ -105,6 +105,41 @@ export class BranchController extends Controller { }); } + @Post() + async createBranch(@Request() req: RequestWithUser, @Body() body: BranchCreate) { + if (body.provinceId || body.districtId || body.subDistrictId || 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; + + return await prisma.branch.create({ + data: { + ...rest, + isHeadOffice: headOfficeId === null, + province: { connect: provinceId ? { id: provinceId } : undefined }, + district: { connect: districtId ? { id: districtId } : undefined }, + subDistrict: { connect: subDistrictId ? { id: subDistrictId } : undefined }, + headOffice: { connect: headOfficeId ? { id: headOfficeId } : undefined }, + createdBy: req.user.name, + updateBy: req.user.name, + }, + }); + } + @Delete("{branchId}") async deleteBranch(@Path() branchId: string) { const record = await prisma.branch.findFirst({ where: { id: branchId } });