refactor: update code gen strategy (customer)

This commit is contained in:
Methapon2001 2024-04-23 11:56:40 +07:00
parent 3fcabd723b
commit 3b8e156e47

View file

@ -122,13 +122,6 @@ export class CustomerController extends Controller {
@Post() @Post()
async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) { async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) {
const last = await prisma.customer.findFirst({
orderBy: { createdAt: "desc" },
where: { customerType: body.customerType },
});
const code = `${body.customerType}${(+(last?.code.slice(-6) || 0) + 1).toString().padStart(6, "0")}`;
const { customerBranch, ...payload } = body; const { customerBranch, ...payload } = body;
const provinceId = body.customerBranch?.reduce<string[]>((acc, cur) => { const provinceId = body.customerBranch?.reduce<string[]>((acc, cur) => {
@ -173,34 +166,50 @@ export class CustomerController extends Controller {
); );
} }
const record = await prisma.customer.create({ const record = await prisma.$transaction(
include: { async (tx) => {
branch: { const last = await tx.runningNo.upsert({
where: {
key: `CUSTOMER_${body.customerType}`,
},
create: {
key: `CUSTOMER_${body.customerType}`,
value: 1,
},
update: { value: { increment: 1 } },
});
return await prisma.customer.create({
include: { include: {
province: true, branch: {
district: true, include: {
subDistrict: true, province: true,
district: true,
subDistrict: true,
},
},
}, },
}, data: {
}, ...payload,
data: { code: `${last.key.slice(9)}${last.value.toString().padStart(6, "0")}`,
...payload, branch: {
code, createMany: {
branch: { data:
createMany: { customerBranch?.map((v, i) => ({
data: ...v,
customerBranch?.map((v, i) => ({ branchNo: `${i + 1}`,
...v, createdBy: req.user.name,
branchNo: `${i + 1}`, updateBy: req.user.name,
createdBy: req.user.name, })) || [],
updateBy: req.user.name, },
})) || [], },
createdBy: req.user.name,
updateBy: req.user.name,
}, },
}, });
createdBy: req.user.name,
updateBy: req.user.name,
}, },
}); { isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
this.setStatus(HttpStatus.CREATED); this.setStatus(HttpStatus.CREATED);