diff --git a/src/controllers/product/type-controller.ts b/src/controllers/product/type-controller.ts new file mode 100644 index 0000000..14a7e6b --- /dev/null +++ b/src/controllers/product/type-controller.ts @@ -0,0 +1,108 @@ +import { + Body, + Controller, + Delete, + Get, + Put, + Path, + Post, + Query, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { Prisma, Status } from "@prisma/client"; + +import prisma from "../../db"; +import { RequestWithUser } from "../../interfaces/user"; +import HttpError from "../../interfaces/http-error"; +import HttpStatus from "../../interfaces/http-status"; + +type ProductTypeCreate = { + code: string; + name: string; + detail: string; + remark: string; +}; + +type ProductTypeUpdate = { + code?: string; + name?: string; + detail?: string; + remark?: string; +}; + +@Route("api/product-type") +@Tags("Product Type") +@Security("keycloak") +export class ProductType extends Controller { + @Get() + async getProductType(@Query() query: string = "") { + const where = { + OR: [{ name: { contains: query } }, { detail: { contains: query } }], + } satisfies Prisma.ProductTypeWhereInput; + const result = prisma.productType.findMany({ orderBy: { createdAt: "asc" }, where }); + return result; + } + + @Get("{typeId}") + async getProductTypeById(@Path() typeId: string) { + const record = await prisma.productType.findFirst({ + where: { id: typeId }, + }); + + if (!record) + throw new HttpError(HttpStatus.NOT_FOUND, "Product type cannot be found.", "data_not_found"); + + return record; + } + + @Post() + async createProductType(@Request() req: RequestWithUser, @Body() body: ProductTypeCreate) { + const record = await prisma.productType.create({ + data: { + ...body, + createdBy: req.user.name, + updateBy: req.user.name, + }, + }); + + this.setStatus(HttpStatus.CREATED); + + return record; + } + + @Put("{typeId}") + async editProductType( + @Request() req: RequestWithUser, + @Body() body: ProductTypeUpdate, + @Path() typeId: string, + ) { + if (!(await prisma.productType.findUnique({ where: { id: typeId } }))) { + throw new HttpError(HttpStatus.NOT_FOUND, "Product type cannot be found.", "data_not_found"); + } + + const record = await prisma.work.update({ + data: { ...body, updateBy: req.user.name }, + where: { id: typeId }, + }); + + return record; + } + + @Delete("{typeId}") + async deleteProductType(@Path() typeId: string) { + const record = await prisma.productType.findFirst({ where: { id: typeId } }); + + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "Product type cannot be found.", "data_not_found"); + } + + if (record.status !== Status.CREATED) { + throw new HttpError(HttpStatus.FORBIDDEN, "Product type is in used.", "data_in_used"); + } + + return await prisma.productType.delete({ where: { id: typeId } }); + } +}