refactor: branch code gen transaction
This commit is contained in:
parent
6b8aa241eb
commit
00dff0814f
1 changed files with 36 additions and 23 deletions
|
|
@ -241,33 +241,46 @@ 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,
|
||||||
subDistrict: 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,
|
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
|
||||||
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,
|
|
||||||
},
|
},
|
||||||
});
|
);
|
||||||
|
|
||||||
if (headOfficeId) {
|
if (headOfficeId) {
|
||||||
await prisma.branch.updateMany({
|
await prisma.branch.updateMany({
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue