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,33 +241,46 @@ 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")}`;
const code = !headOfficeId
? `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({
include: {
province: true,
district: true,
subDistrict: true,
return await tx.branch.create({
include: {
province: true,
district: true,
subDistrict: true,
},
data: {
...rest,
code,
isHeadOffice: !headOfficeId,
province: { connect: provinceId ? { id: provinceId } : undefined },
district: { connect: districtId ? { id: districtId } : undefined },
subDistrict: { connect: subDistrictId ? { id: subDistrictId } : undefined },
headOffice: { connect: headOfficeId ? { id: headOfficeId } : undefined },
createdBy: req.user.name,
updateBy: req.user.name,
},
});
},
data: {
...rest,
code,
isHeadOffice: !headOfficeId,
province: { connect: provinceId ? { id: provinceId } : undefined },
district: { connect: districtId ? { id: districtId } : undefined },
subDistrict: { connect: subDistrictId ? { id: subDistrictId } : undefined },
headOffice: { connect: headOfficeId ? { id: headOfficeId } : undefined },
createdBy: req.user.name,
updateBy: req.user.name,
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
},
});
);
if (headOfficeId) {
await prisma.branch.updateMany({