refactor: branch code gen transaction

This commit is contained in:
Methapon2001 2024-04-22 17:05:08 +07:00
parent 6b8aa241eb
commit 00dff0814f

View file

@ -241,16 +241,24 @@ export class BranchController extends Controller {
const year = new Date().getFullYear();
const last = await prisma.branch.findFirst({
orderBy: { createdAt: "desc" },
where: { headOfficeId: headOfficeId ?? null },
const record = await prisma.$transaction(
async (tx) => {
const last = await tx.runningNo.upsert({
where: {
key: !headOfficeId ? `HQ${year.toString().slice(2)}` : `BR${head?.code.slice(2, 5)}`,
},
create: {
key: !headOfficeId ? `HQ${year.toString().slice(2)}` : `BR${head?.code.slice(2, 5)}`,
value: 1,
},
update: { value: { increment: 1 } },
});
const code = !headOfficeId
? `HQ${year.toString().slice(2)}${+(last?.code.slice(-1) || 0) + 1}`
: `BR${head?.code.slice(2, 5)}${(+(last?.code.slice(-2) || 0) + 1).toString().padStart(2, "0")}`;
? `HQ${year.toString().slice(2)}${last.value}`
: `BR${head?.code.slice(2, 5)}${last.value.toString().padStart(2, "0")}`;
const record = await prisma.branch.create({
return await tx.branch.create({
include: {
province: true,
district: true,
@ -268,6 +276,11 @@ export class BranchController extends Controller {
updateBy: req.user.name,
},
});
},
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
},
);
if (headOfficeId) {
await prisma.branch.updateMany({