jws-backend/src/controllers/03-customer-controller.ts

475 lines
13 KiB
TypeScript
Raw Normal View History

2024-04-09 13:58:04 +07:00
import { CustomerType, Prisma, Status } from "@prisma/client";
2024-04-05 10:57:43 +07:00
import {
Body,
Controller,
Delete,
Get,
Path,
Post,
Put,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
2024-04-05 10:53:52 +07:00
import { RequestWithUser } from "../interfaces/user";
import prisma from "../db";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
2024-09-05 09:01:34 +07:00
import { isSystem } from "../utils/keycloak";
import {
branchRelationPermInclude,
createPermCheck,
createPermCondition,
} from "../services/permission";
2024-09-09 14:51:17 +07:00
import { filterStatus } from "../services/prisma";
2024-09-12 10:39:58 +07:00
import { deleteFile, deleteFolder, fileLocation, getFile, listFile, setFile } from "../utils/minio";
import { notFoundError, relationError } from "../utils/error";
2024-09-16 15:10:37 +07:00
import { connectOrNot } from "../utils/relation";
2024-04-05 10:53:52 +07:00
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"head_of_account",
"account",
"head_of_sale",
2024-09-09 11:13:53 +07:00
"sale",
];
2024-09-04 15:21:11 +07:00
function globalAllow(user: RequestWithUser["user"]) {
const allowList = ["system", "head_of_admin", "admin", "head_of_account", "head_of_sale"];
2024-09-04 15:21:11 +07:00
return allowList.some((v) => user.roles?.includes(v));
}
2024-04-05 10:53:52 +07:00
const permissionCond = createPermCondition(globalAllow);
const permissionCheck = createPermCheck(globalAllow);
2024-09-13 13:27:12 +07:00
export type CustomerCreate = {
2024-09-12 15:08:07 +07:00
registeredBranchId: string;
2024-04-09 13:58:04 +07:00
customerType: CustomerType;
2024-09-13 13:27:12 +07:00
status?: Status;
2024-09-10 15:45:58 +07:00
selectedImage?: string;
2024-09-13 13:27:12 +07:00
2024-09-16 14:37:03 +07:00
branch: {
// NOTE: About (Natural Person)
citizenId?: string;
namePrefix?: string;
firstName?: string;
firstNameEN?: string;
lastName?: string;
lastNameEN?: string;
gender?: string;
birthDate?: Date;
// NOTE: About (Legal Entity)
legalPersonNo?: string;
registerName?: string;
registerNameEN?: string;
registerDate?: Date;
authorizedCapital?: string;
authorizedName?: string;
authorizedNameEN?: string;
customerName?: string;
2024-09-16 11:03:34 +07:00
telephoneNo: string;
2024-09-13 13:27:12 +07:00
status?: Status;
2024-09-16 11:03:34 +07:00
homeCode: string;
employmentOffice: string;
employmentOfficeEN: string;
2024-09-13 13:27:12 +07:00
address: string;
addressEN: string;
soi?: string | null;
soiEN?: string | null;
moo?: string | null;
mooEN?: string | null;
street?: string | null;
streetEN?: string | null;
email: string;
2024-09-16 11:03:34 +07:00
contactTel: string;
officeTel: string;
2024-09-13 13:27:12 +07:00
contactName: string;
2024-09-16 11:03:34 +07:00
agent: string;
2024-09-13 13:27:12 +07:00
businessType: string;
jobPosition: string;
jobDescription: string;
2024-09-16 11:03:34 +07:00
payDate: string;
payDateEN: string;
2024-09-13 13:27:12 +07:00
wageRate: number;
2024-09-16 11:03:34 +07:00
wageRateText: string;
2024-09-13 13:27:12 +07:00
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
2024-09-16 14:37:03 +07:00
}[];
2024-04-05 10:53:52 +07:00
};
2024-09-13 13:27:12 +07:00
export type CustomerUpdate = {
2024-07-03 14:36:11 +07:00
registeredBranchId?: string;
2024-04-05 10:53:52 +07:00
status?: "ACTIVE" | "INACTIVE";
2024-08-27 13:28:51 +07:00
customerType?: CustomerType;
2024-09-10 15:45:58 +07:00
selectedImage?: string;
2024-04-05 10:53:52 +07:00
};
2024-06-06 09:42:02 +07:00
@Route("api/v1/customer")
2024-04-05 10:53:52 +07:00
@Tags("Customer")
export class CustomerController extends Controller {
2024-06-07 09:09:49 +07:00
@Get("type-stats")
2024-07-02 17:29:51 +07:00
@Security("keycloak")
2024-09-09 09:10:41 +07:00
async stat(@Request() req: RequestWithUser) {
2024-06-07 09:09:49 +07:00
const list = await prisma.customer.groupBy({
by: "customerType",
_count: true,
2024-09-09 09:10:41 +07:00
where: {
registeredBranch: isSystem(req.user) ? undefined : { OR: permissionCond(req.user) },
2024-09-09 09:10:41 +07:00
},
2024-06-07 09:09:49 +07:00
});
return list.reduce<Record<CustomerType, number>>(
(a, c) => {
a[c.customerType] = c._count;
return a;
},
{
CORP: 0,
PERS: 0,
},
);
}
2024-04-05 11:00:31 +07:00
@Get()
2024-07-02 17:29:51 +07:00
@Security("keycloak")
2024-04-05 11:00:31 +07:00
async list(
2024-09-05 16:14:03 +07:00
@Request() req: RequestWithUser,
2024-06-10 14:11:45 +07:00
@Query() customerType?: CustomerType,
2024-04-05 11:00:31 +07:00
@Query() query: string = "",
2024-06-13 17:21:22 +07:00
@Query() status?: Status,
2024-04-05 11:00:31 +07:00
@Query() page: number = 1,
@Query() pageSize: number = 30,
@Query() includeBranch: boolean = false,
2024-04-05 11:00:31 +07:00
) {
const where = {
2024-09-13 13:27:12 +07:00
OR: query
? [
{ branch: { some: { namePrefix: { contains: query } } } },
{ branch: { some: { firstName: { contains: query } } } },
{ branch: { some: { firstNameEN: { contains: query } } } },
{ branch: { some: { lastName: { contains: query } } } },
{ branch: { some: { lastNameEN: { contains: query } } } },
]
: undefined,
2024-09-05 16:14:03 +07:00
AND: {
customerType,
...filterStatus(status),
registeredBranch: isSystem(req.user) ? undefined : { OR: permissionCond(req.user) },
2024-09-05 16:14:03 +07:00
},
2024-04-05 11:00:31 +07:00
} satisfies Prisma.CustomerWhereInput;
const [result, total] = await prisma.$transaction([
prisma.customer.findMany({
include: {
_count: true,
branch: includeBranch
? {
include: {
province: true,
district: true,
subDistrict: true,
},
2024-09-16 11:03:34 +07:00
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
}
2024-09-13 13:27:12 +07:00
: {
include: {
province: true,
district: true,
subDistrict: true,
},
take: 1,
orderBy: { createdAt: "asc" },
},
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
2024-06-24 13:20:59 +07:00
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
2024-04-05 11:00:31 +07:00
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.customer.count({ where }),
]);
return { result, page, pageSize, total };
2024-04-05 11:00:31 +07:00
}
2024-04-05 11:00:44 +07:00
@Get("{customerId}")
2024-07-02 17:29:51 +07:00
@Security("keycloak")
2024-04-05 11:00:44 +07:00
async getById(@Path() customerId: string) {
const [record, countEmployee] = await prisma.$transaction([
prisma.customer.findFirst({
include: {
branch: {
include: {
province: true,
district: true,
subDistrict: true,
},
orderBy: { createdAt: "asc" },
},
createdBy: true,
updatedBy: true,
},
where: { id: customerId },
}),
prisma.employee.count({ where: { customerBranch: { customerId } } }),
]);
2024-09-12 10:39:58 +07:00
if (!record) throw notFoundError("Customer");
return Object.assign(record, { _count: { employee: countEmployee } });
2024-04-05 11:00:44 +07:00
}
2024-04-05 10:53:52 +07:00
@Post()
2024-07-03 14:36:11 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-04-05 10:53:52 +07:00
async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) {
2024-09-13 13:27:12 +07:00
const [registeredBranch] = await prisma.$transaction([
2024-09-04 15:21:11 +07:00
prisma.branch.findFirst({
where: { id: body.registeredBranchId },
include: branchRelationPermInclude(req.user),
2024-09-04 15:21:11 +07:00
}),
]);
2024-09-13 13:27:12 +07:00
await permissionCheck(req.user, registeredBranch);
const record = await prisma.$transaction(
async (tx) => {
await tx.branch.updateMany({
where: {
id: body.registeredBranchId,
status: "CREATED",
},
data: {
status: "INACTIVE",
statusOrder: 1,
},
2024-08-09 09:44:51 +07:00
});
2024-09-13 13:27:12 +07:00
const { branch, ...rest } = body;
const company = (registeredBranch?.headOffice || registeredBranch)?.code;
const headoffice = branch[0];
if (!headoffice) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Require at least one branch as headoffice",
"requireOneMinBranch",
);
}
const runningKey = `CUSTOMER_BRANCH_${company}_${"citizenId" in headoffice ? headoffice.citizenId : headoffice.legalPersonNo}`;
2024-09-13 13:27:12 +07:00
const last = await tx.runningNo.upsert({
where: { key: runningKey },
create: {
key: runningKey,
value: branch.length,
},
update: { value: { increment: branch.length } },
});
return await tx.customer.create({
include: {
branch: {
include: {
province: true,
district: true,
subDistrict: true,
},
},
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
data: {
2024-09-13 13:27:12 +07:00
...rest,
branch: {
create: branch.map((v, i) => ({
...v,
code: `${runningKey.replace(`CUSTOMER_BRANCH_${company}_`, "")}-${`${last.value - branch.length + i}`.padStart(2, "0")}`,
codeCustomer: runningKey.replace(`CUSTOMER_BRANCH_${company}_`, ""),
2024-09-16 15:10:37 +07:00
province: connectOrNot(v.provinceId),
provinceId: undefined,
district: connectOrNot(v.districtId),
districtId: undefined,
subDistrict: connectOrNot(v.subDistrictId),
subDistrictId: undefined,
2024-09-13 13:27:12 +07:00
createdBy: { connect: { id: req.user.sub } },
updatedBy: { connect: { id: req.user.sub } },
})),
},
statusOrder: +(body.status === "INACTIVE"),
2024-07-01 13:24:02 +07:00
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
},
});
2024-04-05 10:53:52 +07:00
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
2024-04-05 10:53:52 +07:00
this.setStatus(HttpStatus.CREATED);
return record;
2024-04-05 10:53:52 +07:00
}
2024-04-05 11:02:23 +07:00
2024-04-05 11:18:01 +07:00
@Put("{customerId}")
2024-07-03 14:36:11 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-04-05 11:18:01 +07:00
async editById(
@Path() customerId: string,
@Request() req: RequestWithUser,
@Body() body: CustomerUpdate,
) {
2024-09-12 10:39:58 +07:00
if (body.registeredBranchId === "") body.registeredBranchId = undefined;
2024-09-04 15:21:11 +07:00
const customer = await prisma.customer.findUnique({
where: { id: customerId },
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
},
});
2024-09-12 10:39:58 +07:00
if (!customer) throw notFoundError("Branch");
const [branch] = await prisma.$transaction([
2024-09-04 15:21:11 +07:00
prisma.branch.findFirst({
where: { id: body.registeredBranchId },
include: branchRelationPermInclude(req.user),
2024-09-04 15:21:11 +07:00
}),
]);
2024-09-12 10:39:58 +07:00
if (!!body.registeredBranchId && !branch) throw relationError("Branch");
if (customer.registeredBranch) {
await permissionCheck(req.user, customer.registeredBranch);
}
if (body.registeredBranchId !== undefined && branch) {
await permissionCheck(req.user, branch);
}
const record = await prisma.$transaction(async (tx) => {
return await tx.customer.update({
2024-06-07 11:14:34 +07:00
include: {
branch: {
include: {
province: true,
district: true,
subDistrict: true,
},
},
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
2024-06-07 11:14:34 +07:00
},
where: { id: customerId },
data: {
...body,
statusOrder: +(body.status === "INACTIVE"),
2024-07-01 13:24:02 +07:00
updatedByUserId: req.user.sub,
2024-06-07 11:14:34 +07:00
},
});
2024-04-05 11:18:01 +07:00
});
return record;
2024-04-05 11:18:01 +07:00
}
2024-04-05 11:02:23 +07:00
@Delete("{customerId}")
2024-07-03 14:36:11 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-09-04 15:21:11 +07:00
async deleteById(@Path() customerId: string, @Request() req: RequestWithUser) {
const record = await prisma.customer.findFirst({
where: { id: customerId },
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
2024-09-04 15:21:11 +07:00
},
},
});
2024-04-05 11:02:23 +07:00
if (!record) {
2024-06-14 05:58:14 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
2024-04-05 11:02:23 +07:00
}
await permissionCheck(req.user, record.registeredBranch);
2024-09-04 15:21:11 +07:00
2024-04-05 11:02:23 +07:00
if (record.status !== Status.CREATED) {
2024-06-14 05:58:14 +00:00
throw new HttpError(HttpStatus.FORBIDDEN, "Customer is in used.", "customerInUsed");
2024-04-05 11:02:23 +07:00
}
return await prisma.customer
.delete({ where: { id: customerId } })
2024-09-12 10:39:58 +07:00
.then((data) => deleteFolder(`customer/${customerId}`).then(() => data));
2024-04-05 11:02:23 +07:00
}
2024-09-10 09:56:46 +07:00
}
2024-09-10 09:56:46 +07:00
@Route("api/v1/customer/{customerId}/image")
@Tags("Customer")
export class CustomerImageController extends Controller {
2024-09-12 10:39:58 +07:00
private async checkPermission(user: RequestWithUser["user"], id: string) {
const data = await prisma.customer.findUnique({
include: {
registeredBranch: {
include: branchRelationPermInclude(user),
},
},
where: { id },
});
if (!data) throw notFoundError("Customer");
await permissionCheck(user, data.registeredBranch);
}
2024-09-10 09:56:46 +07:00
@Get()
@Security("keycloak")
2024-09-12 10:39:58 +07:00
async listImage(@Request() req: RequestWithUser, @Path() customerId: string) {
await this.checkPermission(req.user, customerId);
2024-09-10 09:56:46 +07:00
return await listFile(fileLocation.customer.img(customerId));
}
2024-09-10 09:56:46 +07:00
@Get("{name}")
async getImage(
@Request() req: RequestWithUser,
@Path() customerId: string,
@Path() name: string,
) {
return req.res?.redirect(
2024-09-12 10:39:58 +07:00
await getFile(fileLocation.customer.img(customerId, name), 12 * 60 * 60),
2024-09-10 09:56:46 +07:00
);
}
2024-09-10 09:56:46 +07:00
@Put("{name}")
@Security("keycloak")
async putImage(
@Request() req: RequestWithUser,
@Path() customerId: string,
@Path() name: string,
) {
2024-09-12 10:39:58 +07:00
await this.checkPermission(req.user, customerId);
return req.res?.redirect(
2024-09-12 10:39:58 +07:00
await setFile(fileLocation.customer.img(customerId, name), 12 * 60 * 60),
);
}
2024-09-10 09:56:46 +07:00
@Delete("{name}")
@Security("keycloak")
async deleteImage(
@Request() req: RequestWithUser,
@Path() customerId: string,
@Path() name: string,
) {
2024-09-12 10:39:58 +07:00
await this.checkPermission(req.user, customerId);
await deleteFile(fileLocation.customer.img(customerId, name));
2024-09-10 09:56:46 +07:00
}
2024-04-05 10:53:52 +07:00
}