refactor: update code gen strategy (customer)

This commit is contained in:
Methapon2001 2024-04-23 11:56:40 +07:00
parent 3fcabd723b
commit 3b8e156e47

View file

@ -122,13 +122,6 @@ export class CustomerController extends Controller {
@Post()
async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) {
const last = await prisma.customer.findFirst({
orderBy: { createdAt: "desc" },
where: { customerType: body.customerType },
});
const code = `${body.customerType}${(+(last?.code.slice(-6) || 0) + 1).toString().padStart(6, "0")}`;
const { customerBranch, ...payload } = body;
const provinceId = body.customerBranch?.reduce<string[]>((acc, cur) => {
@ -173,34 +166,50 @@ export class CustomerController extends Controller {
);
}
const record = await prisma.customer.create({
include: {
branch: {
const record = await prisma.$transaction(
async (tx) => {
const last = await tx.runningNo.upsert({
where: {
key: `CUSTOMER_${body.customerType}`,
},
create: {
key: `CUSTOMER_${body.customerType}`,
value: 1,
},
update: { value: { increment: 1 } },
});
return await prisma.customer.create({
include: {
province: true,
district: true,
subDistrict: true,
branch: {
include: {
province: true,
district: true,
subDistrict: true,
},
},
},
},
},
data: {
...payload,
code,
branch: {
createMany: {
data:
customerBranch?.map((v, i) => ({
...v,
branchNo: `${i + 1}`,
createdBy: req.user.name,
updateBy: req.user.name,
})) || [],
data: {
...payload,
code: `${last.key.slice(9)}${last.value.toString().padStart(6, "0")}`,
branch: {
createMany: {
data:
customerBranch?.map((v, i) => ({
...v,
branchNo: `${i + 1}`,
createdBy: req.user.name,
updateBy: req.user.name,
})) || [],
},
},
createdBy: req.user.name,
updateBy: req.user.name,
},
},
createdBy: req.user.name,
updateBy: req.user.name,
});
},
});
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
this.setStatus(HttpStatus.CREATED);