import { CustomerType, Prisma, Status } from "@prisma/client"; 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 minio, { deleteFolder, presignedGetObjectIfExist } from "../services/minio"; import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; if (!process.env.MINIO_BUCKET) { throw Error("Require MinIO bucket."); } const MINIO_BUCKET = process.env.MINIO_BUCKET; const MANAGE_ROLES = ["system", "head_of_admin", "admin", "branch_manager", "head_of_sale", "sale"]; export type CustomerCreate = { registeredBranchId?: string; status?: Status; customerType: CustomerType; namePrefix: string; firstName: string; firstNameEN?: string; lastName: string; lastNameEN?: string; gender: string; birthDate: Date; }; export type CustomerUpdate = { registeredBranchId?: string; status?: "ACTIVE" | "INACTIVE"; customerType?: CustomerType; namePrefix?: string; firstName?: string; firstNameEN?: string; lastName?: string; lastNameEN?: string; gender?: string; birthDate?: Date; }; function imageLocation(id: string) { return `customer/${id}/profile-image`; } @Route("api/v1/customer") @Tags("Customer") export class CustomerController extends Controller { @Get("type-stats") @Security("keycloak") async stat() { const list = await prisma.customer.groupBy({ by: "customerType", _count: true, }); return list.reduce>( (a, c) => { a[c.customerType] = c._count; return a; }, { CORP: 0, PERS: 0, }, ); } @Get() @Security("keycloak") async list( @Query() customerType?: CustomerType, @Query() query: string = "", @Query() status?: Status, @Query() page: number = 1, @Query() pageSize: number = 30, @Query() includeBranch: boolean = false, ) { const filterStatus = (val?: Status) => { if (!val) return {}; return val !== Status.CREATED && val !== Status.ACTIVE ? { status: val } : { OR: [{ status: Status.CREATED }, { status: Status.ACTIVE }] }; }; const where = { OR: [ { namePrefix: { contains: query } }, { firstName: { contains: query } }, { firstNameEN: { contains: query } }, ], AND: { customerType, ...filterStatus(status) }, } satisfies Prisma.CustomerWhereInput; const [result, total] = await prisma.$transaction([ prisma.customer.findMany({ include: { _count: true, branch: includeBranch ? { include: { province: true, district: true, subDistrict: true, }, orderBy: { createdAt: "asc" }, } : undefined, createdBy: true, updatedBy: true, }, orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }], where, take: pageSize, skip: (page - 1) * pageSize, }), prisma.customer.count({ where }), ]); return { result, page, pageSize, total }; } @Get("{customerId}") @Security("keycloak") async getById(@Path() customerId: string) { const [record, countEmployee] = await prisma.$transaction([ prisma.customer.findFirst({ include: { branch: { include: { province: true, district: true, subDistrict: true, }, orderBy: { createdAt: "asc" }, }, createdBy: true, updatedBy: true, }, where: { id: customerId }, }), prisma.employee.count({ where: { customerBranch: { customerId } } }), ]); if (!record) { throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound"); } return Object.assign(record, { _count: { employee: countEmployee } }); } @Post() @Security("keycloak", MANAGE_ROLES) async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) { const [branch] = await prisma.$transaction([ prisma.branch.findFirst({ where: { id: body.registeredBranchId } }), ]); if (!!body.registeredBranchId && !branch) { throw new HttpError( HttpStatus.BAD_REQUEST, "Branch cannot be found.", "relationBranchNotFound", ); } if (!body.registeredBranchId) { body.registeredBranchId = undefined; } const record = await prisma.$transaction( async (tx) => { await tx.branch.updateMany({ where: { id: body.registeredBranchId, status: "CREATED", }, data: { status: "INACTIVE", statusOrder: 1, }, }); return await tx.customer.create({ include: { branch: { include: { province: true, district: true, subDistrict: true, }, }, createdBy: true, updatedBy: true, }, data: { ...body, statusOrder: +(body.status === "INACTIVE"), createdByUserId: req.user.sub, updatedByUserId: req.user.sub, }, }); }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, ); this.setStatus(HttpStatus.CREATED); return record; } @Put("{customerId}") @Security("keycloak", MANAGE_ROLES) async editById( @Path() customerId: string, @Request() req: RequestWithUser, @Body() body: CustomerUpdate, ) { const customer = await prisma.customer.findUnique({ where: { id: customerId } }); if (!customer) { throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound"); } const [branch] = await prisma.$transaction([ prisma.customer.findUnique({ where: { id: customerId } }), prisma.branch.findFirst({ where: { id: body.registeredBranchId } }), ]); if (!!body.registeredBranchId && !branch) { throw new HttpError( HttpStatus.BAD_REQUEST, "Branch cannot be found.", "relationBranchNotFound", ); } if (!body.registeredBranchId) { body.registeredBranchId = undefined; } const record = await prisma.$transaction(async (tx) => { return await tx.customer.update({ include: { branch: { include: { province: true, district: true, subDistrict: true, }, }, createdBy: true, updatedBy: true, }, where: { id: customerId }, data: { ...body, statusOrder: +(body.status === "INACTIVE"), updatedByUserId: req.user.sub, }, }); }); return record; } @Delete("{customerId}") @Security("keycloak", MANAGE_ROLES) async deleteById(@Path() customerId: string) { const record = await prisma.customer.findFirst({ where: { id: customerId } }); if (!record) { throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound"); } if (record.status !== Status.CREATED) { throw new HttpError(HttpStatus.FORBIDDEN, "Customer is in used.", "customerInUsed"); } return await prisma.customer .delete({ where: { id: customerId } }) .then( async (data) => await deleteFolder(MINIO_BUCKET, `customer/${customerId}`).then(() => data), ); } @Get("{customerId}/image") async getCustomerImageById(@Request() req: RequestWithUser, @Path() customerId: string) { const url = await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(customerId), 60 * 60); if (!url) { throw new HttpError(HttpStatus.NOT_FOUND, "Image cannot be found", "imageNotFound"); } return req.res?.redirect(url); } @Put("{customerId}/image") @Security("keycloak", MANAGE_ROLES) async setCustomerImageById(@Request() req: RequestWithUser, @Path() customerId: string) { const record = await prisma.customer.findFirst({ where: { id: customerId, }, }); if (!record) { throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound"); } return req.res?.redirect( await minio.presignedPutObject(MINIO_BUCKET, imageLocation(customerId), 12 * 60 * 60), ); } }