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

419 lines
10 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";
import { Prisma, Status } from "@prisma/client";
2024-09-05 09:19:48 +07:00
import prisma from "../db";
import minio, { presignedGetObjectIfExist } from "../services/minio";
import { RequestWithUser } from "../interfaces/user";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
2024-06-12 14:16:06 +07:00
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
}
const MINIO_BUCKET = process.env.MINIO_BUCKET;
2024-07-03 17:28:00 +07:00
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"branch_manager",
2024-09-04 14:01:59 +07:00
"head_of_account",
"account",
2024-07-03 17:28:00 +07:00
];
2024-06-12 14:16:06 +07:00
type ProductCreate = {
2024-06-20 13:31:07 +07:00
status?: Status;
2024-07-02 16:19:38 +07:00
code:
| "DOE"
| "IMM"
| "TM"
| "HP"
| "MOUC"
| "MOUL"
| "AC"
| "doe"
| "imm"
| "tm"
| "hp"
| "mouc"
| "moul"
| "ac";
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-09-03 14:07:30 +07:00
expenseType?: string;
2024-09-03 14:06:02 +07:00
productGroupId: string;
2024-06-14 16:53:48 +07:00
remark?: string;
2024-07-03 17:28:00 +07:00
registeredBranchId?: 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-09-03 14:07:30 +07:00
expenseType?: string;
2024-09-03 14:06:02 +07:00
productGroupId?: string;
2024-07-03 17:28:00 +07:00
registeredBranchId?: string;
2024-06-12 14:16:06 +07:00
};
function imageLocation(id: string) {
return `product/${id}/image`;
}
2024-07-03 17:28:00 +07:00
function globalAllow(roles?: string[]) {
2024-09-04 14:12:57 +07:00
return ["system", "head_of_admin", "admin", "branch_manager", "head_of_account"].some((v) =>
roles?.includes(v),
2024-07-03 17:28:00 +07:00
);
}
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")
2024-09-03 14:06:02 +07:00
async getProductStats(@Query() productGroupId?: string) {
return await prisma.product.count({ where: { productGroupId } });
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(
@Query() status?: Status,
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-07-04 11:27:19 +07:00
@Query() registeredBranchId?: string,
2024-06-12 14:16:06 +07:00
) {
const filterStatus = (val?: Status) => {
if (!val) return {};
return val !== Status.CREATED && val !== Status.ACTIVE
? { status: val }
: { OR: [{ status: Status.CREATED }, { status: Status.ACTIVE }] };
};
2024-06-12 14:16:06 +07:00
const where = {
OR: [
2024-09-03 14:06:02 +07:00
{ name: { contains: query }, productGroupId, ...filterStatus(status) },
{ detail: { contains: query }, productGroupId, ...filterStatus(status) },
],
2024-07-04 11:27:19 +07:00
AND: registeredBranchId
? {
OR: [{ registeredBranchId: registeredBranchId }, { registeredBranchId: null }],
}
: undefined,
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: {
createdBy: true,
updatedBy: true,
},
2024-06-24 13:20:59 +07:00
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
2024-06-12 14:16:06 +07:00
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.product.count({ where }),
]);
return {
result: await Promise.all(
result.map(async (v) => ({
...v,
imageUrl: await presignedGetObjectIfExist(
MINIO_BUCKET,
imageLocation(v.id),
12 * 60 * 60,
),
})),
),
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: {
createdBy: true,
updatedBy: true,
},
2024-06-12 14:16:06 +07:00
where: { id: productId },
});
if (!record) {
2024-06-14 04:41:03 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound");
2024-06-12 14:16:06 +07:00
}
return Object.assign(record, {
imageUrl: await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(record.id), 60 * 60),
});
}
2024-06-17 16:52:06 +07:00
@Get("{productId}/image")
async getProductImageById(@Request() req: RequestWithUser, @Path() productId: string) {
const url = await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(productId), 60 * 60);
2024-06-17 17:32:44 +07:00
2024-06-17 16:52:06 +07:00
if (!url) {
throw new HttpError(HttpStatus.NOT_FOUND, "Image cannot be found", "imageNotFound");
}
2024-06-17 17:32:44 +07:00
return req.res?.redirect(url);
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) {
2024-09-03 14:06:02 +07:00
const [productGroup, branch] = await prisma.$transaction([
prisma.productGroup.findFirst({
2024-07-03 17:28:00 +07:00
include: {
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.branch.findFirst({
2024-08-14 20:40:31 +07:00
include: { user: { where: { userId: req.user.sub } } },
2024-07-03 17:28:00 +07:00
where: { id: body.registeredBranchId },
}),
]);
if (!globalAllow(req.user.roles) && !branch?.user.find((v) => v.userId === req.user.sub)) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
2024-06-17 16:52:06 +07:00
2024-09-03 14:06:02 +07:00
if (!productGroup) {
2024-06-17 16:52:06 +07:00
throw new HttpError(
HttpStatus.BAD_REQUEST,
2024-09-03 14:06:02 +07:00
"Product Group cannot be found.",
"relationProductGroupNotFound",
2024-06-17 16:52:06 +07:00
);
}
2024-07-03 17:28:00 +07:00
if (body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
2024-06-12 14:16:06 +07:00
const record = await prisma.$transaction(
async (tx) => {
const last = await tx.runningNo.upsert({
where: {
key: `PRODUCT_${body.code.toLocaleUpperCase()}`,
},
create: {
key: `PRODUCT_${body.code.toLocaleUpperCase()}`,
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,
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 Object.assign(record, {
imageUrl: await presignedGetObjectIfExist(
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
imageUploadUrl: await minio.presignedPutObject(
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
});
}
@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,
) {
2024-09-03 14:06:02 +07:00
const [product, productGroup, branch] = await prisma.$transaction([
2024-07-03 17:28:00 +07:00
prisma.product.findUnique({
include: {
registeredBranch: {
where: {
user: { some: { userId: req.user.sub } },
},
},
},
where: { id: productId },
}),
2024-09-03 14:06:02 +07:00
prisma.productGroup.findFirst({
2024-07-03 17:28:00 +07:00
include: {
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.branch.findFirst({ where: { id: body.registeredBranchId } }),
]);
if (!product) {
2024-06-14 04:41:03 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound");
2024-06-12 14:16:06 +07:00
}
2024-07-03 17:28:00 +07:00
if (!globalAllow(req.user.roles) && !product.registeredBranch) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
2024-06-17 16:52:06 +07:00
2024-09-03 14:06:02 +07:00
if (!productGroup) {
2024-06-17 16:52:06 +07:00
throw new HttpError(
HttpStatus.BAD_REQUEST,
2024-09-03 14:06:02 +07:00
"Product Group cannot be found.",
"relationProductGroupNotFound",
2024-06-17 16:52:06 +07:00
);
}
2024-07-03 17:28:00 +07:00
if (body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
const record = await prisma.product.update({
2024-07-01 14:38:07 +07:00
include: {
createdBy: true,
updatedBy: true,
},
2024-07-01 13:24:02 +07:00
data: { ...body, statusOrder: +(body.status === "INACTIVE"), updatedByUserId: req.user.sub },
where: { id: productId },
});
2024-09-03 14:06:02 +07:00
if (productGroup.status === "CREATED") {
await prisma.productGroup.updateMany({
where: { id: body.productGroupId, status: Status.CREATED },
data: { status: Status.ACTIVE },
});
}
2024-06-12 14:16:06 +07:00
return Object.assign(record, {
2024-06-19 13:35:45 +07:00
imageUrl: await presignedGetObjectIfExist(
2024-06-12 14:16:06 +07:00
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
2024-06-19 13:35:45 +07:00
imageUploadUrl: await minio.presignedPutObject(
2024-06-12 14:16:06 +07:00
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
});
}
@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: {
registeredBranch: {
where: {
user: { some: { userId: req.user.sub } },
},
},
},
where: { id: productId },
});
2024-06-12 14:16:06 +07:00
if (!record) {
2024-06-14 04:41:03 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound");
2024-06-12 14:16:06 +07:00
}
2024-07-03 17:28:00 +07:00
if (!globalAllow(req.user.roles) && !record.registeredBranch) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
2024-06-12 14:16:06 +07:00
if (record.status !== Status.CREATED) {
2024-06-14 04:41:03 +00:00
throw new HttpError(HttpStatus.FORBIDDEN, "Product is in used.", "productInUsed");
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
}
}