feat: create customer branch endpoint

This commit is contained in:
Methapon2001 2024-04-05 13:51:36 +07:00
parent a90400b348
commit fd37eb6520

View file

@ -93,4 +93,67 @@ type CustomerBranchUpdate = {
@Tags("Customer Branch")
@Security("keycloak")
export class CustomerBranchController extends Controller {
@Post()
async create(@Request() req: RequestWithUser, @Body() body: CustomerBranchCreate) {
if (body.provinceId || body.districtId || body.subDistrictId || body.customerId) {
const [province, district, subDistrict, customer] = 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.customer.findFirst({ where: { id: body.customerId || undefined } }),
]);
if (body.provinceId && !province)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Province cannot be found.",
"missing_or_invalid_parameter",
);
if (body.districtId && !district)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"District cannot be found.",
"missing_or_invalid_parameter",
);
if (body.subDistrictId && !subDistrict)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Sub-district cannot be found.",
"missing_or_invalid_parameter",
);
if (body.customerId && !customer)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Customer cannot be found.",
"missing_or_invalid_parameter",
);
}
const { provinceId, districtId, subDistrictId, customerId, ...rest } = body;
const record = await prisma.customerBranch.create({
include: {
province: true,
district: true,
subDistrict: true,
},
data: {
...rest,
customer: { connect: { id: customerId } },
province: { connect: provinceId ? { id: provinceId } : undefined },
district: { connect: districtId ? { id: districtId } : undefined },
subDistrict: { connect: subDistrictId ? { id: subDistrictId } : undefined },
createdBy: req.user.name,
updateBy: req.user.name,
},
});
await prisma.customer.update({
where: { id: customerId, status: Status.CREATED },
data: { status: Status.ACTIVE },
});
this.setStatus(HttpStatus.CREATED);
return record;
}
}