import { Prisma, Status } from "@prisma/client"; import { Body, Controller, Delete, Get, Patch, 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 BranchCreate = { code: string; taxNo: string; nameEN: string; nameTH: string; addressEN: string; addressTH: string; zipCode: string; email: string; telephoneNo: string; longitude: string; latitude: string; subDistrictId?: string | null; districtId?: string | null; provinceId?: string | null; headOfficeId?: string | null; }; type BranchUpdate = { code?: string; taxNo?: string; nameEN?: string; nameTH?: string; addressEN?: string; addressTH?: string; zipCode?: string; email?: string; telephoneNo?: string; longitude?: string; latitude?: string; subDistrictId?: string | null; districtId?: string | null; provinceId?: string | null; headOfficeId?: string | null; }; @Route("api/branch") @Tags("Branch") @Security("keycloak") export class BranchController extends Controller { @Get() async getBranch( @Query() zipCode?: string, @Query() query: string = "", @Query() page: number = 1, @Query() pageSize: number = 30, ) { const where = { OR: [ { nameEN: { contains: query }, zipCode }, { nameTH: { contains: query }, zipCode }, { email: { contains: query }, zipCode }, ], } satisfies Prisma.BranchWhereInput; const [result, total] = await prisma.$transaction([ prisma.branch.findMany({ include: { province: true, district: true, subDistrict: true, }, where, take: pageSize, skip: (page - 1) * pageSize, }), prisma.branch.count({ where }), ]); return { result, page, pageSize, total }; } @Get("{branchId}") async getBranchById(@Path() branchId: string) { return await prisma.branch.findFirst({ include: { province: true, district: true, subDistrict: true, }, where: { id: branchId }, }); } @Delete("{branchId}") async deleteBranch(@Path() branchId: string) { const record = await prisma.branch.findFirst({ where: { id: branchId } }); if (!record) { throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found."); } if (record.status === Status.USED) { throw new HttpError(HttpStatus.FORBIDDEN, "Branch is in used."); } return await prisma.branch.delete({ where: { id: branchId } }); } }