jws-backend/src/controllers/branch/branch-controller.ts

123 lines
2.7 KiB
TypeScript
Raw Normal View History

import { Prisma, Status } from "@prisma/client";
2024-04-02 09:28:36 +07:00
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;
};
2024-04-02 09:28:36 +07:00
@Route("api/branch")
@Tags("Branch")
@Security("keycloak")
export class BranchController extends Controller {
2024-04-02 09:29:20 +07:00
@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 },
});
}
2024-04-02 10:45:37 +07:00
@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 } });
}
2024-04-02 09:28:36 +07:00
}