From 8bb3e8a0a0e2d75db227a286c8883348d5d1e276 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Tue, 23 Apr 2024 11:19:16 +0700 Subject: [PATCH] refactor: update code gen strategy (branch user) --- src/controllers/branch-user-controller.ts | 70 +++++++++++------------ 1 file changed, 33 insertions(+), 37 deletions(-) diff --git a/src/controllers/branch-user-controller.ts b/src/controllers/branch-user-controller.ts index d33b307..c9059a4 100644 --- a/src/controllers/branch-user-controller.ts +++ b/src/controllers/branch-user-controller.ts @@ -1,4 +1,4 @@ -import { Prisma, Status, UserType } from "@prisma/client"; +import { Branch, Prisma, Status, User, UserType } from "@prisma/client"; import { Body, Controller, @@ -20,6 +20,37 @@ import { RequestWithUser } from "../interfaces/user"; type BranchUserBody = { user: string[] }; +async function userBranchCodeGen(branch: Branch, user: User[]) { + await prisma.$transaction( + async (tx) => { + for (const usr of user) { + if (usr.code !== null) continue; + + const typ = usr.userType; + + const last = await tx.runningNo.upsert({ + where: { + key: `BR_USR_${branch.code.slice(4).padEnd(3, "0")}${typ !== "USER" ? typ.charAt(0) : ""}`, + }, + create: { + key: `BR_USR_${branch.code.slice(4).padEnd(3, "0")}${typ !== "USER" ? typ.charAt(0) : ""}`, + value: 1, + }, + update: { value: { increment: 1 } }, + }); + + await prisma.user.update({ + where: { id: usr.id }, + data: { + code: `${last.key.slice(7)}${last.value.toString().padStart(4, "0")}`, + }, + }); + } + }, + { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, + ); +} + @Route("api/branch/{branchId}/user") @Tags("Branch User") @Security("keycloak") @@ -114,42 +145,7 @@ export class BranchUserController extends Controller { }), ]); - const group: Record = { - USER: [], - AGENCY: [], - DELEGATE: [], - MESSENGER: [], - }; - - for (const u of user) group[u.userType].push(u.id); - - for (const g of Object.values(UserType)) { - if (group[g].length === 0) continue; - - const last = await prisma.branchUser.findFirst({ - orderBy: { createdAt: "desc" }, - include: { user: true }, - where: { - branchId, - user: { - userType: g, - code: { startsWith: `${branch.code.slice(4).padEnd(3, "0")}` }, - }, - }, - }); - - const code = (idx: number) => - `${branch.code.slice(4).padEnd(3, "0")}${g !== "USER" ? g.charAt(0) : ""}${(+(last?.user.code?.slice(-4) || 0) + idx + 1).toString().padStart(4, "0")}`; - - await prisma.$transaction( - group[g].map((v, i) => - prisma.user.updateMany({ - where: { id: v, code: null }, - data: { code: code(i) }, - }), - ), - ); - } + await userBranchCodeGen(branch, user); } @Delete()