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

@ -12,7 +12,7 @@ import {
Security,
Tags,
} from "tsoa";
import { Prisma, Status } from "@prisma/client";
import { Prisma, Status, UserType } from "@prisma/client";
import prisma from "../db";
import minio from "../services/minio";
@ -31,7 +31,7 @@ type UserCreate = {
keycloakId: string;
userType: string;
userType: UserType;
userRole: string;
firstName: string;
@ -40,7 +40,6 @@ type UserCreate = {
lastNameEN: string;
gender: string;
code?: string;
registrationNo?: string;
startDate?: Date;
retireDate?: Date;
@ -66,7 +65,7 @@ type UserCreate = {
type UserUpdate = {
status?: "ACTIVE" | "INACTIVE";
userType?: string;
userType?: UserType;
userRole?: string;
firstName?: string;
@ -75,7 +74,6 @@ type UserUpdate = {
lastNameEN?: string;
gender?: string;
code?: string;
registrationNo?: string;
startDate?: Date;
retireDate?: Date;
@ -108,7 +106,7 @@ function imageLocation(id: string) {
export class UserController extends Controller {
@Get()
async getUser(
@Query() userType?: string,
@Query() userType?: UserType,
@Query() zipCode?: string,
@Query() query: string = "",
@Query() page: number = 1,
@ -276,10 +274,36 @@ export class UserController extends Controller {
const { provinceId, districtId, subDistrictId, ...rest } = body;
const user = await prisma.user.findFirst({
where: { id: userId },
});
if (!user) {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "data_not_found");
}
const lastUserOfType =
body.userType &&
body.userType !== user.userType &&
user.code &&
(await prisma.user.findFirst({
orderBy: { createdAt: "desc" },
where: {
userType: body.userType,
code: { startsWith: `${user.code?.slice(0, 3)}` },
},
}));
console.log(lastUserOfType);
const record = await prisma.user.update({
include: { province: true, district: true, subDistrict: true },
data: {
...rest,
code:
(lastUserOfType &&
`${user.code?.slice(0, 3)}${body.userType !== "USER" ? body.userType?.charAt(0) : ""}${(+(lastUserOfType?.code?.slice(-4) || 0) + 1).toString().padStart(4, "0")}`) ||
undefined,
province: {
connect: provinceId ? { id: provinceId } : undefined,
disconnect: provinceId === null || undefined,
@ -296,9 +320,7 @@ export class UserController extends Controller {
},
where: { id: userId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "User cannot be found.");
}
return Object.assign(record, {
profileImageUrl: await minio.presignedGetObject(
MINIO_BUCKET,