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,7 +166,20 @@ export class CustomerController extends Controller {
); );
} }
const record = await prisma.customer.create({ const record = await prisma.$transaction(
async (tx) => {
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: {
branch: { branch: {
include: { include: {
@ -185,7 +191,7 @@ export class CustomerController extends Controller {
}, },
data: { data: {
...payload, ...payload,
code, code: `${last.key.slice(9)}${last.value.toString().padStart(6, "0")}`,
branch: { branch: {
createMany: { createMany: {
data: data:
@ -201,6 +207,9 @@ export class CustomerController extends Controller {
updateBy: req.user.name, updateBy: req.user.name,
}, },
}); });
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
this.setStatus(HttpStatus.CREATED); this.setStatus(HttpStatus.CREATED);