feat: create branch endpoint

This commit is contained in:
Methapon2001 2024-04-02 11:19:12 +07:00
parent a39b9de423
commit c841fa84ed

View file

@ -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 } });