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

664 lines
18 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,
Head,
2024-04-05 10:57:43 +07:00
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 {
branchActiveOnlyCond,
branchRelationPermInclude,
createPermCheck,
createPermCondition,
} from "../services/permission";
2024-09-09 14:51:17 +07:00
import { filterStatus } from "../services/prisma";
import {
deleteFile,
deleteFolder,
fileLocation,
getFile,
getPresigned,
listFile,
setFile,
} from "../utils/minio";
import { isUsedError, notFoundError, relationError } from "../utils/error";
2025-04-17 13:41:22 +07:00
import { connectOrNot, queryOrNot, whereDateQuery } from "../utils/relation";
import { json2csv } from "json-2-csv";
2024-04-05 10:53:52 +07:00
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"executive",
"accountant",
"branch_admin",
"branch_manager",
"branch_accountant",
2025-07-04 13:26:26 +07:00
"head_of_sale",
"sale",
];
2024-09-04 15:21:11 +07:00
function globalAllow(user: RequestWithUser["user"]) {
const listAllowed = MANAGE_ROLES;
return user.roles?.some((v) => listAllowed.includes(v)) || false;
2024-09-04 15:21:11 +07:00
}
2024-04-05 10:53:52 +07:00
const permissionCondCompany = createPermCondition((_) => true);
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;
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-10-28 10:51:51 +07:00
agentUserId?: string;
2024-09-13 13:27:12 +07:00
businessTypeId?: string | null;
2024-09-13 13:27:12 +07:00
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,
@Query() company: boolean = false,
@Query() activeBranchOnly?: boolean,
2025-04-17 13:41:22 +07:00
@Query() startDate?: Date,
@Query() endDate?: Date,
@Query() businessType?: string,
@Query() province?: string,
@Query() district?: string,
@Query() subDistrict?: string,
2024-04-05 11:00:31 +07:00
) {
const where = {
OR: queryOrNot<Prisma.CustomerWhereInput[]>(query, [
2025-04-09 11:54:52 +07:00
{ branch: { some: { namePrefix: { contains: query, mode: "insensitive" } } } },
{ branch: { some: { registerName: { contains: query, mode: "insensitive" } } } },
{ branch: { some: { registerNameEN: { contains: query, mode: "insensitive" } } } },
{ branch: { some: { firstName: { contains: query, mode: "insensitive" } } } },
{ branch: { some: { firstNameEN: { contains: query, mode: "insensitive" } } } },
{ branch: { some: { lastName: { contains: query, mode: "insensitive" } } } },
{ branch: { some: { lastNameEN: { contains: query, mode: "insensitive" } } } },
]),
2024-09-05 16:14:03 +07:00
AND: {
customerType,
...filterStatus(status),
registeredBranch: isSystem(req.user)
? branchActiveOnlyCond(activeBranchOnly)
: {
OR: company
? permissionCondCompany(req.user, { activeOnly: activeBranchOnly })
: permissionCond(req.user, { activeOnly: activeBranchOnly }),
},
2024-09-05 16:14:03 +07:00
},
branch: {
some: {
AND: [
businessType
? {
2025-09-17 12:58:14 +07:00
OR: [{ businessType: { id: businessType } }],
}
: {},
province
? {
2025-09-17 12:58:14 +07:00
OR: [{ province: { id: province } }],
}
: {},
district
? {
2025-09-17 12:58:14 +07:00
OR: [{ district: { id: district } }],
}
: {},
subDistrict
? {
2025-09-17 12:58:14 +07:00
OR: [{ subDistrict: { id: subDistrict } }],
}
: {},
],
},
},
2025-04-17 13:41:22 +07:00
...whereDateQuery(startDate, endDate),
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: {
2025-07-11 11:13:18 +07:00
businessType: true,
province: true,
district: true,
subDistrict: true,
},
omit: {
otpCode: true,
otpExpires: true,
userId: 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,
},
omit: {
otpCode: true,
otpExpires: true,
userId: true,
},
2024-09-13 13:27:12 +07:00
take: 1,
orderBy: { createdAt: "asc" },
},
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
// businessType: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,
},
omit: {
otpCode: true,
otpExpires: true,
userId: 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,
},
omit: {
otpCode: true,
otpExpires: true,
userId: 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}_`, ""),
2025-07-15 15:17:53 +07:00
businessType: connectOrNot(v.businessTypeId),
businessTypeId: undefined,
2024-10-28 10:51:51 +07:00
agentUser: connectOrNot(v.agentUserId),
agentUserId: undefined,
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);
}
if (!!body.registeredBranchId && !branch) throw relationError("Branch");
2024-09-23 18:14:33 +07:00
let companyBefore = (customer.registeredBranch.headOffice || customer.registeredBranch).code;
let companyAfter =
!!body.registeredBranchId && branch ? (branch.headOffice || branch).code : false;
if (companyBefore && companyAfter && companyBefore !== companyAfter) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Cannot move between different headoffice",
"crossCompanyNotPermit",
);
}
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,
},
omit: {
otpCode: true,
otpExpires: true,
userId: true,
},
2024-06-07 11:14:34 +07:00
},
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) throw notFoundError("Customer");
2024-04-05 11:02:23 +07:00
await permissionCheck(req.user, record.registeredBranch);
2024-09-04 15:21:11 +07:00
if (record.status !== Status.CREATED) throw isUsedError("Customer");
2024-04-05 11:02:23 +07:00
await prisma.$transaction(async (tx) => {
await deleteFolder(`customer/${customerId}`);
const data = await tx.customer.delete({
include: {
branch: {
omit: {
otpCode: true,
otpExpires: true,
userId: true,
},
},
registeredBranch: {
include: {
headOffice: true,
},
},
},
where: { id: customerId },
});
await tx.runningNo.deleteMany({
where: {
key: {
in: data.branch.map(
(v) =>
`CUSTOMER_BRANCH_${(data.registeredBranch.headOffice || data.registeredBranch).code}_${v.code.slice(0, -3)}`,
),
},
},
});
2024-10-17 14:45:42 +07:00
return 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
);
}
@Head("{name}")
async headImage(
@Request() req: RequestWithUser,
@Path() customerId: string,
@Path() name: string,
) {
return req.res?.redirect(
await getPresigned("head", fileLocation.customer.img(customerId, name), 12 * 60 * 60),
);
}
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
}
@Route("api/v1/customer-export")
@Tags("Customer")
export class CustomerExportController extends CustomerController {
@Get()
@Security("keycloak")
async exportCustomer(
@Request() req: RequestWithUser,
@Query() customerType?: CustomerType,
@Query() query: string = "",
@Query() status?: Status,
@Query() page: number = 1,
@Query() pageSize: number = 30,
@Query() includeBranch: boolean = false,
@Query() company: boolean = false,
@Query() activeBranchOnly?: boolean,
@Query() startDate?: Date,
@Query() endDate?: Date,
2025-09-17 12:39:10 +07:00
@Query() businessType?: string,
@Query() province?: string,
@Query() district?: string,
@Query() subDistrict?: string,
) {
const ret = await this.list(
req,
customerType,
query,
status,
page,
pageSize,
includeBranch,
company,
activeBranchOnly,
startDate,
endDate,
2025-09-17 12:39:10 +07:00
businessType,
province,
district,
subDistrict,
);
this.setHeader("Content-Type", "text/csv");
return json2csv(
ret.result.map((v) => Object.assign(v, { branch: v.branch.at(0) ?? null })),
{ useDateIso8601Format: true, expandNestedObjects: true },
);
}
}