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