feat: auto gen user code

This commit is contained in:
Methapon2001 2024-04-09 13:05:49 +07:00
parent 3abff0594a
commit 3f0ed2c8d6
4 changed files with 113 additions and 32 deletions

View file

@ -1,4 +1,4 @@
import { Prisma, Status } from "@prisma/client";
import { Prisma, Status, UserType } from "@prisma/client";
import {
Body,
Controller,
@ -71,10 +71,23 @@ export class BranchUserController extends Controller {
@Path() branchId: string,
@Body() body: BranchUserBody,
) {
const user = await prisma.user.findMany({
include: { branch: true },
where: { id: { in: body.user } },
});
const [branch, user] = await prisma.$transaction([
prisma.branch.findUnique({
where: { id: branchId },
}),
prisma.user.findMany({
include: { branch: true },
where: { id: { in: body.user } },
}),
]);
if (!branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"missing_or_invalid_parameter",
);
}
if (user.length !== body.user.length) {
throw new HttpError(
@ -84,21 +97,55 @@ export class BranchUserController extends Controller {
);
}
await prisma.user.updateMany({
where: { id: { in: body.user }, status: Status.CREATED },
data: { status: Status.ACTIVE },
});
await prisma.$transaction([
prisma.user.updateMany({
where: { id: { in: body.user }, status: Status.CREATED },
data: { status: Status.ACTIVE },
}),
prisma.branchUser.createMany({
data: user
.filter((a) => !a.branch.some((b) => b.branchId === branchId))
.map((v) => ({
branchId,
userId: v.id,
createdBy: req.user.name,
updateBy: req.user.name,
})),
}),
]);
await prisma.branchUser.createMany({
data: user
.filter((a) => !a.branch.some((b) => b.branchId === branchId))
.map((v) => ({
branchId,
userId: v.id,
createdBy: req.user.name,
updateBy: req.user.name,
})),
});
const group: Record<UserType, string[]> = {
USER: [],
AGENCY: [],
DELEGATE: [],
MESSENGER: [],
};
for (const u of user) group[u.userType].push(u.id);
for (const g of Object.values(UserType)) {
if (group[g].length === 0) continue;
const last = await prisma.user.findFirst({
orderBy: { createdAt: "desc" },
where: {
userType: g,
code: { startsWith: `${branch.code.slice(2, 5).padEnd(3, "0")}` },
},
});
const code = (idx: number) =>
`${branch.code.slice(4).padEnd(3, "0")}${g !== "USER" ? g.charAt(0) : ""}${(+(last?.code?.slice(-4) || 0) + idx + 1).toString().padStart(4, "0")}`;
await prisma.$transaction(
group[g].map((v, i) =>
prisma.user.updateMany({
where: { id: v, code: null },
data: { code: code(i) },
}),
),
);
}
}
@Delete()