diff --git a/src/controllers/10-business-type-controller.ts b/src/controllers/10-business-type-controller.ts new file mode 100644 index 0000000..2cd80a6 --- /dev/null +++ b/src/controllers/10-business-type-controller.ts @@ -0,0 +1,111 @@ +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 { Prisma } from "@prisma/client"; +import { queryOrNot } from "../utils/relation"; +import { notFoundError } from "../utils/error"; + +type BusinessTypePayload = { + name: string; + nameEN: string; +}; + +@Route("api/v1/business-type") +@Tags("Business Type") +export class businessTypeController extends Controller { + @Get() + @Security("keycloak") + async getList( + @Request() req: RequestWithUser, + @Query() query: string = "", + @Query() page: number = 1, + @Query() pageSize: number = 30, + ) { + const where = { + OR: queryOrNot(query, [ + { name: { contains: query, mode: "insensitive" } }, + { nameEN: { contains: query, mode: "insensitive" } }, + ]), + } satisfies Prisma.BusinessTypeWhereInput; + + const [result, total] = await prisma.$transaction([ + prisma.businessType.findMany({ + where, + }), + prisma.businessType.count({ where }), + ]); + + return { result, page, pageSize, total }; + } + + @Post() + @Security("keycloak") + async createBusinessType(@Request() req: RequestWithUser, @Body() body: BusinessTypePayload) { + return await prisma.businessType.create({ + data: { + ...body, + createdByUserId: req.user.sub, + updatedByUserId: req.user.sub, + }, + }); + } + + @Get(":businessTypeId") + @Security("keycloak") + async getBusinessTypeById(@Path() businessTypeId: string) { + return await prisma.businessType.findUnique({ + where: { id: businessTypeId }, + }); + } + + @Put(":businessTypeId") + @Security("keycloak") + async updateBusinessType( + @Request() req: RequestWithUser, + @Path() businessTypeId: string, + @Body() body: BusinessTypePayload, + ) { + return await prisma.$transaction(async (tx) => { + const record = await tx.businessType.findUnique({ + where: { id: businessTypeId }, + }); + + if (!record) throw notFoundError("BusinessType"); + return await prisma.businessType.update({ + where: { id: businessTypeId }, + data: { + ...body, + updatedByUserId: req.user.sub, + }, + }); + }); + } + + @Delete(":businessTypeId") + @Security("keycloak") + async deleteBusinessType(@Path() businessTypeId: string) { + return await prisma.$transaction(async (tx) => { + const record = await tx.businessType.findUnique({ + where: { id: businessTypeId }, + }); + + if (!record) throw notFoundError("BusinessType"); + return await prisma.businessType.delete({ + where: { id: businessTypeId }, + }); + }); + } +}