From 3b8e156e47d4f388db95688cca44e6aebeba8903 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Tue, 23 Apr 2024 11:56:40 +0700 Subject: [PATCH] refactor: update code gen strategy (customer) --- src/controllers/customer-controller.ts | 71 +++++++++++++++----------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/src/controllers/customer-controller.ts b/src/controllers/customer-controller.ts index 8fbe421..d251748 100644 --- a/src/controllers/customer-controller.ts +++ b/src/controllers/customer-controller.ts @@ -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((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);