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

481 lines
13 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,
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";
2024-09-10 15:19:31 +07:00
import { deleteFile, fileLocation, getFile, listFile, setFile } from "../utils/minio";
import { isUsedError, notFoundError, relationError } from "../utils/error";
import { queryOrNot } from "../utils/relation";
2024-06-12 14:16:06 +07:00
2024-07-03 17:28:00 +07:00
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"head_of_accountant",
"accountant",
"head_of_sale",
2024-07-03 17:28:00 +07:00
];
2024-06-12 14:16:06 +07:00
function globalAllow(user: RequestWithUser["user"]) {
const allowList = ["system", "head_of_admin", "head_of_accountant", "head_of_sale"];
return allowList.some((v) => user.roles?.includes(v));
}
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;
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;
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,
2024-06-12 14:16:06 +07:00
) {
const where = {
OR: queryOrNot<Prisma.ProductWhereInput[]>(query, [
{ name: { contains: query } },
{ detail: { contains: query } },
{ code: { contains: query, mode: "insensitive" } },
]),
AND: {
...filterStatus(activeOnly ? Status.ACTIVE : status),
productGroup: {
status: activeOnly ? { not: Status.INACTIVE } : undefined,
registeredBranch: activeOnly
? {
OR: [
{ headOffice: { status: { not: Status.INACTIVE } } },
{ headOffice: null, status: { not: Status.INACTIVE } },
],
}
: undefined,
},
OR: [
...(productGroupId
? [
shared
? {
OR: [
{ productGroupId },
2024-11-13 15:18:00 +07:00
{
shared: true,
productGroup: {
registeredBranch: {
OR: permissionCondCompany(req.user, { activeOnly }),
},
2024-11-13 15:18:00 +07:00
},
},
{
productGroup: {
shared: true,
registeredBranch: {
OR: permissionCondCompany(req.user, { activeOnly }),
},
},
},
],
}
: { productGroupId },
]
: []),
...(isSystem(req.user)
? []
: [
{
productGroup: {
2024-11-13 15:18:00 +07:00
id: productGroupId,
registeredBranch: { OR: permissionCondCompany(req.user, { activeOnly }) },
},
2024-09-10 17:00:21 +07:00
},
]),
],
},
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: {
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 },
});
}
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
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
}
}
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));
}
}