import { Body, Controller, Delete, Get, Put, Path, Post, Query, Request, Route, Security, Tags, } from "tsoa"; import prisma from "../db"; import HttpError from "../interfaces/http-error"; import HttpStatus from "../interfaces/http-status"; import { RequestWithUser } from "../interfaces/user"; type BranchContactCreate = { telephoneNo: string; }; type BranchContactUpdate = { telephoneNo?: string; }; @Route("api/v1/branch/{branchId}/contact") @Tags("Branch Contact") @Security("keycloak") export class BranchContactController extends Controller { @Get() async getBranchContact( @Path() branchId: string, @Query() page: number = 1, @Query() pageSize: number = 30, ) { const [result, total] = await prisma.$transaction([ prisma.branchContact.findMany({ orderBy: { createdAt: "asc" }, where: { branchId }, take: pageSize, skip: (page - 1) * pageSize, }), prisma.branchContact.count({ where: { branchId } }), ]); return { result, page, pageSize, total, }; } @Get("{contactId}") async getBranchContactById(@Path() branchId: string, @Path() contactId: string) { const record = await prisma.branchContact.findFirst({ where: { id: contactId, branchId } }); if (!record) { throw new HttpError( HttpStatus.NOT_FOUND, "Branch contact cannot be found.", "branchContactNotFound", ); } return record; } @Post() async createBranchContact( @Request() req: RequestWithUser, @Path() branchId: string, @Body() body: BranchContactCreate, ) { if (!(await prisma.branch.findFirst({ where: { id: branchId } }))) { throw new HttpError(HttpStatus.BAD_REQUEST, "Branch cannot be found.", "branchBadReq"); } const record = await prisma.branchContact.create({ data: { ...body, branchId, createdByUserId: req.user.sub, updatedByUserId: req.user.sub }, }); this.setStatus(HttpStatus.CREATED); return record; } @Put("{contactId}") async editBranchContact( @Request() req: RequestWithUser, @Body() body: BranchContactUpdate, @Path() branchId: string, @Path() contactId: string, ) { if ( !(await prisma.branchContact.findUnique({ where: { id: contactId, branchId }, })) ) { throw new HttpError( HttpStatus.NOT_FOUND, "Branch contact cannot be found.", "branchContactNotFound", ); } const record = await prisma.branchContact.update({ data: { ...body, updatedByUserId: req.user.sub }, where: { id: contactId, branchId }, }); return record; } @Delete("{contactId}") async deleteBranchContact(@Path() branchId: string, @Path() contactId: string) { const result = await prisma.branchContact.deleteMany({ where: { id: contactId, branchId } }); if (result.count <= 0) { throw new HttpError( HttpStatus.NOT_FOUND, "Branch contact cannot be found.", "branchContactNotFound", ); } } }