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

631 lines
17 KiB
TypeScript
Raw Normal View History

2024-04-05 11:37:40 +07:00
import { Prisma, Status } from "@prisma/client";
import {
Body,
Controller,
Delete,
Get,
Path,
Post,
Put,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
import { RequestWithUser } from "../interfaces/user";
import prisma from "../db";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
2024-09-11 15:06:27 +07:00
import minio, { deleteFolder } from "../services/minio";
2024-09-05 15:06:23 +07:00
import { isSystem } from "../utils/keycloak";
2024-09-11 15:06:27 +07:00
import {
branchRelationPermInclude,
createPermCheck,
createPermCondition,
} from "../services/permission";
2024-09-09 14:51:17 +07:00
import { filterStatus } from "../services/prisma";
2024-09-11 15:06:27 +07:00
import { connectOrDisconnect, connectOrNot, whereAddressQuery } from "../utils/relation";
import { notFoundError, relationError } from "../utils/error";
2024-04-05 11:37:40 +07:00
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
}
const MINIO_BUCKET = process.env.MINIO_BUCKET;
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 16:51:42 +07:00
function globalAllow(user: RequestWithUser["user"]) {
const allowList = ["system", "head_of_admin", "admin", "head_of_account", "head_of_sale"];
2024-09-04 16:51:42 +07:00
return allowList.some((v) => user.roles?.includes(v));
}
2024-04-05 11:37:40 +07:00
2024-09-11 15:06:27 +07:00
const permissionCond = createPermCondition(globalAllow);
const permissionCheck = createPermCheck(globalAllow);
2024-04-05 11:37:40 +07:00
function imageLocation(id: string) {
return `employee/profile-img-${id}`;
}
2024-04-05 11:42:03 +07:00
2024-06-07 10:44:40 +07:00
function attachmentLocation(customerId: string, branchId: string) {
return `customer/${customerId}/branch/${branchId}`;
}
2024-09-16 14:37:03 +07:00
export type CustomerBranchCreate = {
2024-04-05 11:42:03 +07:00
customerId: string;
2024-09-16 14:37:03 +07:00
// 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-04-05 11:42:03 +07:00
2024-09-16 11:03:34 +07:00
telephoneNo: string;
2024-04-05 11:42:03 +07:00
status?: Status;
2024-09-16 11:03:34 +07:00
homeCode: string;
employmentOffice: string;
employmentOfficeEN: string;
2024-04-05 11:42:03 +07:00
address: string;
2024-08-20 16:17:41 +07:00
addressEN: string;
2024-09-11 15:06:27 +07:00
soi?: string | null;
soiEN?: string | null;
moo?: string | null;
mooEN?: string | null;
street?: string | null;
streetEN?: string | null;
2024-08-20 16:17:41 +07:00
2024-04-05 11:42:03 +07:00
email: string;
2024-09-16 11:03:34 +07:00
contactTel: string;
officeTel: string;
2024-08-21 16:52:59 +07:00
contactName: string;
2024-09-16 11:03:34 +07:00
agent: string;
2024-04-05 11:42:03 +07:00
2024-08-20 16:17:41 +07:00
businessType: string;
2024-04-23 18:09:08 +07:00
jobPosition: string;
jobDescription: string;
2024-09-16 11:03:34 +07:00
payDate: string;
payDateEN: string;
2024-06-07 14:02:31 +07:00
wageRate: number;
2024-09-16 11:03:34 +07:00
wageRateText: string;
2024-04-23 18:09:08 +07:00
2024-04-05 11:42:03 +07:00
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
};
2024-08-20 16:17:41 +07:00
export type CustomerBranchUpdate = (
| {
// NOTE: About (Natural Person)
citizenId: string;
}
| {
// NOTE: About (Legal Entity)
legalPersonNo: string;
registerName?: string;
registerNameEN?: string;
registerDate?: Date;
authorizedCapital?: string;
2024-09-16 11:03:34 +07:00
authorizedName: string;
authorizedNameEN: string;
2024-08-20 16:17:41 +07:00
}
) & {
2024-04-05 11:42:03 +07:00
customerId?: string;
2024-09-16 13:31:47 +07:00
customerName?: string;
2024-04-05 11:42:03 +07:00
2024-09-16 11:03:34 +07:00
telephoneNo: string;
2024-04-05 11:42:03 +07:00
status?: "ACTIVE" | "INACTIVE";
2024-09-16 11:03:34 +07:00
homeCode?: string;
address?: string;
addressEN?: string;
2024-09-11 15:06:27 +07:00
soi?: string | null;
soiEN?: string | null;
moo?: string | null;
mooEN?: string | null;
street?: string | null;
streetEN?: string | null;
2024-04-05 11:42:03 +07:00
email?: string;
2024-09-16 11:03:34 +07:00
contactTel?: string;
officeTel?: string;
2024-08-21 16:52:59 +07:00
contactName?: string;
2024-09-16 11:03:34 +07:00
agent?: string;
2024-04-05 11:42:03 +07:00
2024-08-21 12:56:39 +07:00
businessType?: string;
2024-04-23 18:09:08 +07:00
jobPosition?: string;
jobDescription?: string;
2024-09-16 11:03:34 +07:00
payDate?: string;
payDateEN?: string;
2024-06-10 15:24:06 +07:00
wageRate?: number;
2024-09-16 11:03:34 +07:00
wageRateText?: string;
2024-04-23 18:09:08 +07:00
2024-04-05 11:42:03 +07:00
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
};
2024-06-06 09:42:02 +07:00
@Route("api/v1/customer-branch")
2024-04-05 11:37:40 +07:00
@Tags("Customer Branch")
export class CustomerBranchController extends Controller {
2024-04-05 14:55:24 +07:00
@Get()
@Security("keycloak")
2024-04-05 14:55:24 +07:00
async list(
2024-09-05 16:14:03 +07:00
@Request() req: RequestWithUser,
2024-04-05 14:55:24 +07:00
@Query() zipCode?: string,
@Query() customerId?: string,
2024-06-13 17:21:22 +07:00
@Query() status?: Status,
@Query() includeCustomer?: boolean,
2024-04-05 14:55:24 +07:00
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
2024-09-09 14:59:15 +07:00
OR: query
? [
{ registerName: { contains: query } },
{ registerNameEN: { contains: query } },
{ email: { contains: query } },
{ code: { contains: query } },
2024-09-13 13:27:12 +07:00
{ firstName: { contains: query } },
{ firstNameEN: { contains: query } },
{ lastName: { contains: query } },
{ lastNameEN: { contains: query } },
2024-09-11 15:06:27 +07:00
...whereAddressQuery(query),
2024-09-09 14:59:15 +07:00
]
: undefined,
2024-09-05 16:14:03 +07:00
AND: {
customer: isSystem(req.user)
? undefined
: {
registeredBranch: {
2024-09-11 15:06:27 +07:00
OR: permissionCond(req.user),
2024-09-05 16:14:03 +07:00
},
},
customerId,
subDistrict: zipCode ? { zipCode } : undefined,
...filterStatus(status),
},
} satisfies Prisma.CustomerBranchWhereInput;
2024-04-05 14:55:24 +07:00
const [result, total] = await prisma.$transaction([
prisma.customerBranch.findMany({
2024-06-24 13:20:59 +07:00
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
2024-04-05 14:55:24 +07:00
include: {
customer: includeCustomer,
2024-04-05 14:55:24 +07:00
province: true,
district: true,
subDistrict: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
_count: true,
2024-04-05 14:55:24 +07:00
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.customerBranch.count({ where }),
]);
return { result, page, pageSize, total };
}
2024-04-05 15:09:44 +07:00
@Get("{branchId}")
@Security("keycloak")
2024-04-05 15:09:44 +07:00
async getById(@Path() branchId: string) {
const record = await prisma.customerBranch.findFirst({
include: {
2024-08-27 18:14:50 +07:00
customer: true,
2024-04-05 15:09:44 +07:00
province: true,
district: true,
subDistrict: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
2024-04-05 15:09:44 +07:00
},
where: { id: branchId },
});
2024-09-11 15:06:27 +07:00
if (!record) throw notFoundError("Branch");
2024-04-05 15:09:44 +07:00
return record;
}
2024-04-05 15:07:29 +07:00
@Get("{branchId}/employee")
@Security("keycloak")
2024-04-05 15:07:29 +07:00
async listEmployee(
@Path() branchId: string,
@Query() zipCode?: string,
2024-08-22 11:44:44 +07:00
@Query() gender?: string,
@Query() status?: Status,
2024-04-05 15:07:29 +07:00
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
OR: [
2024-08-22 11:44:44 +07:00
{ firstName: { contains: query } },
{ firstNameEN: { contains: query } },
{ lastName: { contains: query } },
{ lastNameEN: { contains: query } },
2024-09-11 15:06:27 +07:00
...whereAddressQuery(query),
2024-04-05 15:07:29 +07:00
],
2024-08-22 11:44:44 +07:00
AND: {
...filterStatus(status),
customerBranchId: branchId,
subDistrict: zipCode ? { zipCode } : undefined,
gender,
},
2024-04-05 15:07:29 +07:00
} satisfies Prisma.EmployeeWhereInput;
const [result, total] = await prisma.$transaction([
prisma.employee.findMany({
2024-04-09 08:51:22 +07:00
orderBy: { createdAt: "asc" },
2024-04-05 15:07:29 +07:00
include: {
province: true,
district: true,
subDistrict: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
2024-04-05 15:07:29 +07:00
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.employee.count({ where }),
]);
return {
result: await Promise.all(
result.map(async (v) => ({
...v,
profileImageUrl: await minio.presignedGetObject(
MINIO_BUCKET,
imageLocation(v.id),
12 * 60 * 60,
),
})),
),
page,
pageSize,
total,
};
}
2024-04-05 13:51:36 +07:00
@Post()
@Security("keycloak", MANAGE_ROLES)
2024-04-05 13:51:36 +07:00
async create(@Request() req: RequestWithUser, @Body() body: CustomerBranchCreate) {
const [province, district, subDistrict, customer] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId || undefined } }),
prisma.district.findFirst({ where: { id: body.districtId || undefined } }),
prisma.subDistrict.findFirst({ where: { id: body.subDistrictId || undefined } }),
prisma.customer.findFirst({
where: { id: body.customerId || undefined },
include: {
2024-09-05 15:06:23 +07:00
registeredBranch: {
include: branchRelationPermInclude(req.user),
2024-09-05 15:06:23 +07:00
},
branch: {
take: 1,
orderBy: { createdAt: "asc" },
},
},
}),
]);
2024-09-11 15:06:27 +07:00
if (body.provinceId && !province) throw relationError("Province");
if (body.districtId && !district) throw relationError("District");
if (body.subDistrictId && !subDistrict) throw relationError("SubDistrict");
if (!customer) throw relationError("Customer");
2024-04-05 13:51:36 +07:00
2024-09-11 15:06:27 +07:00
let company = await permissionCheck(req.user, customer.registeredBranch).then(
(v) => (v.headOffice || v).code,
);
2024-09-05 15:06:23 +07:00
2024-04-05 13:51:36 +07:00
const { provinceId, districtId, subDistrictId, customerId, ...rest } = body;
2024-04-23 18:09:08 +07:00
const record = await prisma.$transaction(
async (tx) => {
const headoffice = customer.branch.at(0);
const headofficeCode = headoffice?.code.slice(0, -3);
2024-08-20 16:17:41 +07:00
let runningKey = "";
if (headofficeCode) {
2024-09-11 15:06:27 +07:00
runningKey = `CUSTOMER_BRANCH_${company}_${headofficeCode}`;
} else if ("citizenId" in body) {
2024-09-11 15:06:27 +07:00
runningKey = `CUSTOMER_BRANCH_${company}_${body.citizenId}`;
2024-08-20 16:17:41 +07:00
} else {
2024-09-11 15:06:27 +07:00
runningKey = `CUSTOMER_BRANCH_${company}_${body.legalPersonNo}`;
2024-08-20 16:17:41 +07:00
}
const last = await tx.runningNo.upsert({
where: { key: runningKey },
create: {
key: runningKey,
value: 1,
},
update: { value: { increment: 1 } },
});
if (headoffice) {
await tx.customerBranch.updateMany({
where: {
id: headoffice.id,
status: "CREATED",
},
data: { status: "ACTIVE" },
});
}
2024-08-20 16:17:41 +07:00
return await tx.customerBranch.create({
include: {
province: true,
district: true,
subDistrict: true,
createdBy: true,
updatedBy: true,
},
data: {
...rest,
code: `${runningKey.replace(`CUSTOMER_BRANCH_${company}_`, "")}-${`${last.value - 1}`.padStart(2, "0")}`,
codeCustomer: runningKey.replace(`CUSTOMER_BRANCH_${company}_`, ""),
2024-08-20 16:17:41 +07:00
customer: { connect: { id: customerId } },
province: { connect: provinceId ? { id: provinceId } : undefined },
district: { connect: districtId ? { id: districtId } : undefined },
subDistrict: { connect: subDistrictId ? { id: subDistrictId } : undefined },
createdBy: { connect: { id: req.user.sub } },
updatedBy: { connect: { id: req.user.sub } },
},
});
2024-04-05 13:51:36 +07:00
},
2024-04-23 18:09:08 +07:00
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
2024-04-05 13:51:36 +07:00
this.setStatus(HttpStatus.CREATED);
return record;
}
2024-04-05 14:15:38 +07:00
@Put("{branchId}")
@Security("keycloak", MANAGE_ROLES)
2024-04-05 14:15:38 +07:00
async editById(
@Request() req: RequestWithUser,
@Body() body: CustomerBranchUpdate,
@Path() branchId: string,
) {
const branch = await prisma.customerBranch.findUnique({
where: { id: branchId },
include: {
customer: {
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
},
},
},
});
if (!branch) {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
}
await permissionCheck(req.user, branch.customer.registeredBranch);
2024-09-05 15:06:23 +07:00
if (!body.customerId) body.customerId = branch.customerId;
2024-04-05 14:15:38 +07:00
if (body.provinceId || body.districtId || body.subDistrictId || body.customerId) {
const [province, district, subDistrict, customer] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId || undefined } }),
prisma.district.findFirst({ where: { id: body.districtId || undefined } }),
prisma.subDistrict.findFirst({ where: { id: body.subDistrictId || undefined } }),
2024-09-05 15:06:23 +07:00
prisma.customer.findFirst({
where: { id: body.customerId || undefined },
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
2024-09-05 15:06:23 +07:00
},
},
}),
2024-04-05 14:15:38 +07:00
]);
2024-09-11 15:06:27 +07:00
if (body.provinceId && !province) throw relationError("Province");
if (body.districtId && !district) throw relationError("District");
if (body.subDistrictId && !subDistrict) throw relationError("SubDistrict");
if (!customer) throw relationError("Customer");
await permissionCheck(req.user, customer.registeredBranch);
2024-04-05 14:15:38 +07:00
}
2024-08-20 16:17:41 +07:00
const { provinceId, districtId, subDistrictId, customerId, ...rest } = body;
return await prisma.customerBranch.update({
where: { id: branchId },
include: {
province: true,
district: true,
subDistrict: true,
createdBy: true,
updatedBy: true,
},
data: {
...rest,
statusOrder: +(rest.status === "INACTIVE"),
2024-09-11 15:06:27 +07:00
customer: connectOrNot(customerId),
province: connectOrDisconnect(provinceId),
district: connectOrDisconnect(districtId),
subDistrict: connectOrDisconnect(subDistrictId),
2024-08-20 16:17:41 +07:00
updatedBy: { connect: { id: req.user.sub } },
},
});
2024-04-05 14:15:38 +07:00
}
2024-04-05 15:13:33 +07:00
@Delete("{branchId}")
@Security("keycloak", MANAGE_ROLES)
2024-09-05 15:06:23 +07:00
async delete(@Request() req: RequestWithUser, @Path() branchId: string) {
2024-06-07 10:44:40 +07:00
const record = await prisma.customerBranch.findFirst({
where: { id: branchId },
2024-09-05 15:06:23 +07:00
include: {
customer: {
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
2024-09-05 15:06:23 +07:00
},
},
},
},
2024-06-07 10:44:40 +07:00
});
2024-04-05 15:13:33 +07:00
2024-09-11 15:06:27 +07:00
if (!record) throw notFoundError("Customer Branch");
2024-04-05 15:13:33 +07:00
await permissionCheck(req.user, record.customer.registeredBranch);
2024-09-05 15:06:23 +07:00
2024-04-05 15:13:33 +07:00
if (record.status !== Status.CREATED) {
2024-06-24 13:14:44 +07:00
throw new HttpError(
HttpStatus.FORBIDDEN,
"Customer branch is in used.",
"customerBranchInUsed",
);
2024-04-05 15:13:33 +07:00
}
2024-07-01 14:38:07 +07:00
return await prisma.customerBranch
.delete({
include: { createdBy: true, updatedBy: true },
where: { id: branchId },
})
.then((v) => {
2024-09-11 15:06:27 +07:00
deleteFolder(MINIO_BUCKET, `${attachmentLocation(record.customerId, branchId)}/`);
2024-07-01 14:38:07 +07:00
return v;
2024-06-07 10:44:40 +07:00
});
}
}
@Route("api/v1/customer-branch/{branchId}/attachment")
@Tags("Customer Branch")
@Security("keycloak")
export class CustomerAttachmentController extends Controller {
@Get()
async listAttachment(@Path() branchId: string) {
const record = await prisma.customerBranch.findFirst({
where: { id: branchId },
});
if (!record) {
throw new HttpError(
HttpStatus.NOT_FOUND,
"Customer branch cannot be found.",
2024-06-14 05:58:14 +00:00
"customerBranchNotFound",
2024-06-07 10:44:40 +07:00
);
}
const list = await new Promise<string[]>((resolve, reject) => {
const item: string[] = [];
const stream = minio.listObjectsV2(
MINIO_BUCKET,
`${attachmentLocation(record.customerId, branchId)}/`,
);
stream.on("data", (v) => v && v.name && item.push(v.name));
stream.on("end", () => resolve(item));
stream.on("error", () => reject(new Error("MinIO error.")));
});
return list.map((v) => v.split("/").at(-1) as string);
2024-06-07 10:44:40 +07:00
}
@Get("{filename}")
async getAttachment(
@Request() req: RequestWithUser,
@Path() branchId: string,
@Path() filename: string,
) {
const record = await prisma.customerBranch.findFirst({
where: { id: branchId },
});
if (!record) {
throw new HttpError(
HttpStatus.NOT_FOUND,
"Customer branch cannot be found.",
"customerBranchNotFound",
);
}
return await minio.presignedGetObject(
MINIO_BUCKET,
`${attachmentLocation(record.customerId, branchId)}/${filename}`,
12 * 60 * 60,
);
}
@Put("{filename}")
async addAttachment(
@Request() req: RequestWithUser,
@Path() branchId: string,
@Path() filename: string,
) {
2024-06-07 10:44:40 +07:00
const record = await prisma.customerBranch.findFirst({
where: { id: branchId },
});
if (!record) {
throw new HttpError(
HttpStatus.NOT_FOUND,
"Customer branch cannot be found.",
2024-06-14 05:58:14 +00:00
"customerBranchNotFound",
2024-06-07 10:44:40 +07:00
);
}
return req.res?.redirect(
await minio.presignedPutObject(
MINIO_BUCKET,
`${attachmentLocation(record.customerId, branchId)}/${filename}`,
12 * 60 * 60,
),
2024-06-07 10:44:40 +07:00
);
}
@Delete("{filename}")
async deleteAttachment(@Path() branchId: string, @Path() filename: string) {
2024-06-07 10:44:40 +07:00
const record = await prisma.customerBranch.findFirst({
where: { id: branchId },
});
if (!record) {
throw new HttpError(
HttpStatus.NOT_FOUND,
"Customer branch cannot be found.",
2024-06-14 05:58:14 +00:00
"customerBranchNotFound",
2024-06-07 10:44:40 +07:00
);
}
await minio.removeObject(
MINIO_BUCKET,
`${attachmentLocation(record.customerId, branchId)}/${filename}`,
{ forceDelete: true },
2024-06-07 10:44:40 +07:00
);
2024-04-05 15:13:33 +07:00
}
2024-04-05 11:37:40 +07:00
}