jws-backend/src/controllers/04-product-controller.ts

645 lines
19 KiB
TypeScript
Raw Normal View History

2024-06-12 14:16:06 +07:00
import {
Body,
Controller,
Delete,
Get,
Put,
Path,
Post,
Request,
Route,
Security,
Tags,
2024-06-13 15:47:11 +07:00
Query,
2025-04-18 15:39:02 +07:00
UploadedFile,
2024-06-12 14:16:06 +07:00
} from "tsoa";
2024-11-29 11:54:00 +07:00
import { Prisma, Product, Status } from "@prisma/client";
2024-06-12 14:16:06 +07:00
2024-09-05 09:19:48 +07:00
import prisma from "../db";
import { RequestWithUser } from "../interfaces/user";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import {
branchRelationPermInclude,
createPermCheck,
createPermCondition,
} from "../services/permission";
import { isSystem } from "../utils/keycloak";
import { filterStatus } from "../services/prisma";
import { deleteFile, deleteFolder, fileLocation, getFile, listFile, setFile } from "../utils/minio";
import { isUsedError, notFoundError, relationError } from "../utils/error";
2025-04-17 13:41:22 +07:00
import { queryOrNot, whereDateQuery } from "../utils/relation";
2025-04-18 15:39:02 +07:00
import spreadsheet from "../utils/spreadsheet";
2024-06-12 14:16:06 +07:00
2024-07-03 17:28:00 +07:00
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"executive",
"accountant",
"branch_admin",
"branch_manager",
"branch_accountant",
2024-07-03 17:28:00 +07:00
];
2024-06-12 14:16:06 +07:00
function globalAllow(user: RequestWithUser["user"]) {
const listAllowed = ["system", "head_of_admin", "admin", "executive", "accountant"];
return user.roles?.some((v) => listAllowed.includes(v)) || false;
}
const permissionCondCompany = createPermCondition((_) => true);
const permissionCond = createPermCondition(globalAllow);
const permissionCheck = createPermCheck(globalAllow);
2024-06-12 14:16:06 +07:00
type ProductCreate = {
2024-06-20 13:31:07 +07:00
status?: Status;
2024-10-16 15:10:54 +07:00
code: string;
2024-06-12 14:16:06 +07:00
name: string;
detail: string;
2024-06-14 16:53:48 +07:00
process: number;
2024-06-12 14:16:06 +07:00
price: number;
agentPrice: number;
serviceCharge: number;
2024-09-03 14:06:02 +07:00
vatIncluded?: boolean;
2024-10-15 09:42:16 +07:00
calcVat?: boolean;
2025-01-27 11:50:16 +07:00
agentPriceVatIncluded?: boolean;
agentPriceCalcVat?: boolean;
serviceChargeVatIncluded?: boolean;
serviceChargeCalcVat?: boolean;
2024-09-03 14:07:30 +07:00
expenseType?: string;
2024-09-10 15:51:22 +07:00
selectedImage?: string;
shared?: boolean;
2024-09-03 14:06:02 +07:00
productGroupId: string;
2024-06-14 16:53:48 +07:00
remark?: string;
document?: string[];
2024-06-12 14:16:06 +07:00
};
type ProductUpdate = {
2024-06-20 13:31:07 +07:00
status?: "ACTIVE" | "INACTIVE";
2024-06-14 16:53:48 +07:00
name?: string;
detail?: string;
process?: number;
price?: number;
agentPrice?: number;
serviceCharge?: number;
remark?: string;
2024-09-03 14:06:02 +07:00
vatIncluded?: boolean;
2024-10-15 09:42:16 +07:00
calcVat?: boolean;
2025-01-27 11:50:16 +07:00
agentPriceVatIncluded?: boolean;
agentPriceCalcVat?: boolean;
serviceChargeVatIncluded?: boolean;
serviceChargeCalcVat?: boolean;
2024-09-03 14:07:30 +07:00
expenseType?: string;
2024-09-10 15:51:22 +07:00
selectedImage?: string;
shared?: boolean;
2024-09-03 14:06:02 +07:00
productGroupId?: string;
document?: string[];
2024-06-12 14:16:06 +07:00
};
@Route("api/v1/product")
@Tags("Product")
export class ProductController extends Controller {
2024-06-18 14:07:24 +07:00
@Get("stats")
@Security("keycloak")
async getProductStats(@Request() req: RequestWithUser, @Query() productGroupId?: string) {
return await prisma.product.count({
where: {
productGroupId,
2024-09-10 17:00:21 +07:00
OR: isSystem(req.user)
? undefined
2024-09-10 17:00:21 +07:00
: [
{
productGroup: {
registeredBranch: { OR: permissionCond(req.user) },
},
},
{
shared: true,
productGroup: {
registeredBranch: { OR: permissionCondCompany(req.user) },
2024-09-10 17:00:21 +07:00
},
},
{
productGroup: {
shared: true,
registeredBranch: { OR: permissionCondCompany(req.user) },
},
},
2024-09-10 17:00:21 +07:00
],
},
});
2024-06-18 14:07:24 +07:00
}
2024-06-12 14:16:06 +07:00
@Get()
2024-06-18 10:56:28 +07:00
@Security("keycloak")
2024-06-12 14:16:06 +07:00
async getProduct(
@Request() req: RequestWithUser,
@Query() status?: Status,
@Query() shared?: boolean,
2024-09-03 14:06:02 +07:00
@Query() productGroupId?: string,
2024-06-13 15:47:11 +07:00
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
2024-11-29 11:54:00 +07:00
@Query() orderField?: keyof Product,
@Query() orderBy?: "asc" | "desc",
@Query() activeOnly?: boolean,
2025-04-17 13:41:22 +07:00
@Query() startDate?: Date,
@Query() endDate?: Date,
2024-06-12 14:16:06 +07:00
) {
// NOTE: will be used to scope product within product group that is shared between branch but not company when select shared product if user is system
const targetGroup =
productGroupId && req.user.roles.includes("system")
? await prisma.productGroup.findFirst({
where: { id: productGroupId },
})
: undefined;
if (targetGroup !== undefined && !targetGroup) throw notFoundError("Product Group");
const targetBranchId = targetGroup?.registeredBranchId;
2024-06-12 14:16:06 +07:00
const where = {
OR: queryOrNot<Prisma.ProductWhereInput[]>(query, [
2025-04-09 11:54:52 +07:00
{ name: { contains: query, mode: "insensitive" } },
{ detail: { contains: query, mode: "insensitive" } },
{ code: { contains: query, mode: "insensitive" } },
]),
AND: {
...filterStatus(activeOnly ? Status.ACTIVE : status),
productGroup: {
status: activeOnly ? { not: Status.INACTIVE } : undefined,
registeredBranch: { OR: permissionCondCompany(req.user, { activeOnly, targetBranchId }) },
},
OR: [
...(productGroupId
? [
shared
? {
OR: [
{ productGroupId },
2024-11-13 15:18:00 +07:00
{
shared: true,
productGroup: {
registeredBranch: {
OR: permissionCondCompany(req.user, { activeOnly, targetBranchId }),
},
2024-11-13 15:18:00 +07:00
},
},
{
productGroup: {
shared: true,
registeredBranch: {
OR: permissionCondCompany(req.user, { activeOnly, targetBranchId }),
},
},
},
],
}
: { productGroupId },
]
: []),
],
},
2025-04-17 13:41:22 +07:00
...whereDateQuery(startDate, endDate),
2024-06-12 14:16:06 +07:00
} satisfies Prisma.ProductWhereInput;
const [result, total] = await prisma.$transaction([
prisma.product.findMany({
2024-07-01 14:38:07 +07:00
include: {
2024-11-08 09:32:33 +07:00
document: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
2024-11-29 11:54:00 +07:00
orderBy: [
{ statusOrder: "asc" },
...((orderField && orderBy && [{ [orderField]: orderBy }]) || []),
{ createdAt: "asc" },
],
2024-06-12 14:16:06 +07:00
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.product.count({ where }),
]);
return {
2024-11-08 09:32:33 +07:00
result: result.map((v) => ({ ...v, document: v.document.map((doc) => doc.name) })),
2024-06-12 14:16:06 +07:00
page,
pageSize,
total,
};
}
@Get("{productId}")
2024-06-18 10:56:28 +07:00
@Security("keycloak")
2024-06-12 14:16:06 +07:00
async getProductById(@Path() productId: string) {
const record = await prisma.product.findFirst({
2024-07-01 14:38:07 +07:00
include: {
2024-11-08 09:32:33 +07:00
document: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
2024-06-12 14:16:06 +07:00
where: { id: productId },
});
2024-09-11 14:40:28 +07:00
if (!record) throw notFoundError("Product");
2024-06-12 14:16:06 +07:00
2024-11-08 09:32:33 +07:00
return { ...record, document: record.document.map((doc) => doc.name) };
2024-06-17 16:52:06 +07:00
}
2024-06-12 14:16:06 +07:00
@Post()
2024-07-03 17:28:00 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-06-12 14:16:06 +07:00
async createProduct(@Request() req: RequestWithUser, @Body() body: ProductCreate) {
const [productGroup, productSameName] = await prisma.$transaction([
2024-09-03 14:06:02 +07:00
prisma.productGroup.findFirst({
2024-07-03 17:28:00 +07:00
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
2024-07-03 17:28:00 +07:00
createdBy: true,
updatedBy: true,
},
2024-09-03 14:06:02 +07:00
where: { id: body.productGroupId },
2024-07-03 17:28:00 +07:00
}),
prisma.product.findMany({
where: {
productGroup: {
registeredBranch: {
OR: permissionCondCompany(req.user),
},
},
name: body.name,
},
}),
2024-07-03 17:28:00 +07:00
]);
if (!productGroup) throw relationError("Product Group");
if (productSameName.some((v) => v.code.slice(0, -3) === body.code.toUpperCase())) {
2024-06-17 16:52:06 +07:00
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Product with the same name and code already exists",
"productNameExists",
2024-06-17 16:52:06 +07:00
);
}
await permissionCheck(req.user, productGroup.registeredBranch);
2024-07-03 17:28:00 +07:00
2024-06-12 14:16:06 +07:00
const record = await prisma.$transaction(
async (tx) => {
const branch = productGroup.registeredBranch;
const company = (branch.headOffice || branch).code;
2024-06-12 14:16:06 +07:00
const last = await tx.runningNo.upsert({
where: {
key: `PRODUCT_${company}_${body.code.toLocaleUpperCase()}`,
2024-06-12 14:16:06 +07:00
},
create: {
key: `PRODUCT_${company}_${body.code.toLocaleUpperCase()}`,
2024-06-12 14:16:06 +07:00
value: 1,
},
update: { value: { increment: 1 } },
});
return await prisma.product.create({
2024-07-01 14:38:07 +07:00
include: {
createdBy: true,
updatedBy: true,
},
2024-06-12 14:16:06 +07:00
data: {
...body,
document: body.document
? {
createMany: { data: body.document.map((v) => ({ name: v })) },
}
: undefined,
2024-06-24 13:14:44 +07:00
statusOrder: +(body.status === "INACTIVE"),
2024-06-12 14:16:06 +07:00
code: `${body.code.toLocaleUpperCase()}${last.value.toString().padStart(3, "0")}`,
2024-07-01 13:24:02 +07:00
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
2024-06-12 14:16:06 +07:00
},
});
},
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
},
);
2024-09-03 14:06:02 +07:00
if (productGroup.status === "CREATED") {
await prisma.productGroup.update({
2024-07-01 14:38:07 +07:00
include: {
createdBy: true,
updatedBy: true,
},
2024-09-03 14:06:02 +07:00
where: { id: body.productGroupId },
data: { status: Status.ACTIVE },
});
}
2024-06-12 14:16:06 +07:00
this.setStatus(HttpStatus.CREATED);
return record;
2024-06-12 14:16:06 +07:00
}
@Put("{productId}")
2024-07-03 17:28:00 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-06-12 14:16:06 +07:00
async editProduct(
@Request() req: RequestWithUser,
@Body() body: ProductUpdate,
@Path() productId: string,
) {
const [product, productGroup] = await prisma.$transaction([
2024-07-03 17:28:00 +07:00
prisma.product.findUnique({
include: {
productGroup: {
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
2024-07-03 17:28:00 +07:00
},
},
},
where: { id: productId },
}),
2024-09-03 14:06:02 +07:00
prisma.productGroup.findFirst({
2024-07-03 17:28:00 +07:00
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
2024-07-03 17:28:00 +07:00
createdBy: true,
updatedBy: true,
},
2024-09-03 14:06:02 +07:00
where: { id: body.productGroupId },
2024-07-03 17:28:00 +07:00
}),
]);
2024-09-11 14:40:28 +07:00
if (!product) throw notFoundError("Product");
if (!!body.productGroupId && !productGroup) throw relationError("Product Group");
2024-06-17 16:52:06 +07:00
await permissionCheck(req.user, product.productGroup.registeredBranch);
if (body.productGroupId && productGroup) {
await permissionCheck(req.user, productGroup.registeredBranch);
2024-07-03 17:28:00 +07:00
}
const record = await prisma.product.update({
2024-07-01 14:38:07 +07:00
include: {
2025-03-05 13:58:58 +07:00
productGroup: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
data: {
...body,
document: body.document
? {
deleteMany: {},
createMany: { data: body.document.map((v) => ({ name: v })) },
}
: undefined,
statusOrder: +(body.status === "INACTIVE"),
updatedByUserId: req.user.sub,
},
where: { id: productId },
});
if (productGroup?.status === "CREATED") {
2024-09-03 14:06:02 +07:00
await prisma.productGroup.updateMany({
where: { id: body.productGroupId, status: Status.CREATED },
data: { status: Status.ACTIVE },
});
}
2025-03-05 13:58:58 +07:00
await prisma.notification.create({
data: {
title: "สินค้ามีการเปลี่ยนแปลง / Product Updated",
detail: "รหัส / code : " + record.code,
groupReceiver: {
create: [{ name: "sale" }, { name: "head_of_sale" }],
},
registeredBranchId: record.productGroup.registeredBranchId,
},
});
return record;
2024-06-12 14:16:06 +07:00
}
@Delete("{productId}")
2024-07-03 17:28:00 +07:00
@Security("keycloak", MANAGE_ROLES)
async deleteProduct(@Request() req: RequestWithUser, @Path() productId: string) {
const record = await prisma.product.findFirst({
include: {
productGroup: {
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
2024-07-03 17:28:00 +07:00
},
},
},
where: { id: productId },
});
2024-06-12 14:16:06 +07:00
2024-09-11 14:40:28 +07:00
if (!record) throw notFoundError("Product");
2024-06-12 14:16:06 +07:00
if (record.status !== Status.CREATED) throw isUsedError("Product");
2024-06-12 14:16:06 +07:00
await deleteFolder(fileLocation.product.img(productId));
2024-07-01 14:38:07 +07:00
return await prisma.product.delete({
include: {
createdBy: true,
updatedBy: true,
},
where: { id: productId },
});
2024-06-12 14:16:06 +07:00
}
2025-04-18 15:39:02 +07:00
2025-04-22 09:37:10 +07:00
@Post("import-product")
2025-04-18 15:39:02 +07:00
@Security("keycloak", MANAGE_ROLES)
async importProduct(
@Request() req: RequestWithUser,
@UploadedFile() file: Express.Multer.File,
@Query() productGroupId: string,
) {
if (!file?.buffer) throw notFoundError("File");
const buffer = new Uint8Array(file.buffer).buffer;
const dataFile = await spreadsheet.readExcel(buffer, {
header: true,
worksheet: "Sheet1",
});
let dataName: string[] = [];
2025-04-22 09:37:10 +07:00
const data = dataFile.map((item: any) => {
2025-04-18 15:39:02 +07:00
dataName.push(item.name);
return {
...item,
expenseType:
item.expenseType === "ค่าธรรมเนียม"
? "fee"
: item.expenseType === "ค่าบริการ"
? "serviceFee"
: "processingFee",
shared: item.shared === "ใช่" ? true : false,
price:
typeof item.price === "number"
? item.price
2025-04-23 09:03:03 +07:00
: +parseFloat(item.price?.replace(",", "") || "0").toFixed(6),
2025-04-18 15:39:02 +07:00
calcVat: item.calcVat === "ใช่" ? true : false,
vatIncluded: item.vatIncluded === "รวม" ? true : false,
agentPrice:
typeof item.agentPrice === "number"
? item.agentPrice
2025-04-23 09:03:03 +07:00
: +parseFloat(item.agentPrice?.replace(",", "") || "0").toFixed(6),
2025-04-18 15:39:02 +07:00
agentPriceCalcVat: item.agentPriceCalcVat === "ใช่" ? true : false,
agentPriceVatIncluded: item.agentPriceVatIncluded === "รวม" ? true : false,
serviceCharge:
typeof item.serviceCharge === "number"
? item.serviceCharge
2025-04-23 09:03:03 +07:00
: +parseFloat(item.serviceCharge?.replace(",", "") || "0").toFixed(6),
2025-04-18 15:39:02 +07:00
serviceChargeCalcVat: item.serviceChargeCalcVat === "ใช่" ? true : false,
serviceChargeVatIncluded: item.serviceChargeVatIncluded === "รวม" ? true : false,
};
});
const [productGroup, productSameName] = await prisma.$transaction([
prisma.productGroup.findFirst({
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
createdBy: true,
updatedBy: true,
},
where: { id: productGroupId },
}),
prisma.product.findMany({
where: {
productGroup: {
2025-04-22 11:20:11 +07:00
id: productGroupId,
2025-04-18 15:39:02 +07:00
registeredBranch: {
OR: permissionCondCompany(req.user),
},
},
name: { in: dataName },
},
}),
]);
if (!productGroup) throw relationError("Product Group");
await permissionCheck(req.user, productGroup.registeredBranch);
let dataProduct: ProductCreate[] = [];
const record = await prisma.$transaction(
async (tx) => {
const branch = productGroup.registeredBranch;
const company = (branch.headOffice || branch).code;
await Promise.all(
data.map(async (item) => {
const dataDuplicate = productSameName.some(
(v) => v.code.slice(0, -3) === item.code.toUpperCase() && v.name === item.name,
);
if (!dataDuplicate) {
const last = await tx.runningNo.upsert({
where: {
key: `PRODUCT_${company}_${item.code.toLocaleUpperCase()}`,
},
create: {
key: `PRODUCT_${company}_${item.code.toLocaleUpperCase()}`,
value: 1,
},
update: { value: { increment: 1 } },
});
dataProduct.push({
...item,
code: `${item.code.toLocaleUpperCase()}${last.value.toString().padStart(3, "0")}`,
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
productGroupId: productGroupId,
});
}
}),
);
2025-04-18 15:39:02 +07:00
return await prisma.product.createManyAndReturn({
data: dataProduct,
include: {
createdBy: true,
updatedBy: true,
},
});
},
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
},
);
if (productGroup.status === "CREATED") {
await prisma.productGroup.update({
include: {
createdBy: true,
updatedBy: true,
},
where: { id: productGroupId },
data: { status: Status.ACTIVE },
});
}
this.setStatus(HttpStatus.CREATED);
return record;
}
2024-06-12 14:16:06 +07:00
}
2024-09-10 15:19:31 +07:00
@Route("api/v1/product/{productId}")
@Tags("Product")
export class ProductFileController extends Controller {
async checkPermission(user: RequestWithUser["user"], id: string) {
const data = await prisma.product.findUnique({
include: {
productGroup: {
include: {
registeredBranch: {
include: branchRelationPermInclude(user),
},
},
},
},
where: { id },
});
2024-09-11 14:40:28 +07:00
if (!data) throw notFoundError("Product");
2024-09-10 15:19:31 +07:00
await permissionCheck(user, data.productGroup.registeredBranch);
}
@Get("image")
@Security("keycloak")
async listImage(@Request() req: RequestWithUser, @Path() productId: string) {
await this.checkPermission(req.user, productId);
return await listFile(fileLocation.product.img(productId));
}
@Get("image/{name}")
async getImage(@Request() req: RequestWithUser, @Path() productId: string, @Path() name: string) {
return req.res?.redirect(await getFile(fileLocation.product.img(productId, name)));
}
@Put("image/{name}")
@Security("keycloak")
async putImage(@Request() req: RequestWithUser, @Path() productId: string, @Path() name: string) {
if (!req.headers["content-type"]?.startsWith("image/")) {
throw new HttpError(HttpStatus.BAD_REQUEST, "Not a valid image.", "notValidImage");
}
await this.checkPermission(req.user, productId);
return req.res?.redirect(await setFile(fileLocation.product.img(productId, name)));
}
@Delete("image/{name}")
@Security("keycloak")
async delImage(@Request() req: RequestWithUser, @Path() productId: string, @Path() name: string) {
await this.checkPermission(req.user, productId);
return await deleteFile(fileLocation.product.img(productId, name));
}
}