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, { 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; export type CustomerCreate = { status?: Status; customerType: CustomerType; customerName: string; customerNameEN: string; taxNo?: string | null; customerBranch?: { status?: Status; legalPersonNo: string; taxNo: string | null; name: string; nameEN: string; addressEN: string; address: string; zipCode: string; email: string; telephoneNo: string; registerName: string; registerDate: Date; authorizedCapital: string; employmentOffice: string; bussinessType: string; bussinessTypeEN: string; jobPosition: string; jobPositionEN: string; jobDescription: string; saleEmployee: string; payDate: Date; wageRate: number; subDistrictId?: string | null; districtId?: string | null; provinceId?: string | null; }[]; }; export type CustomerUpdate = { status?: "ACTIVE" | "INACTIVE"; customerType?: CustomerType; customerName?: string; customerNameEN?: string; taxNo?: string | null; customerBranch?: { id?: string; status?: Status; legalPersonNo: string; taxNo: string | null; name: string; nameEN: string; addressEN: string; address: string; zipCode: string; email: string; telephoneNo: string; registerName: string; registerDate: Date; authorizedCapital: string; employmentOffice: string; bussinessType: string; bussinessTypeEN: string; jobPosition: string; jobPositionEN: string; jobDescription: string; saleEmployee: string; payDate: Date; wageRate: number; subDistrictId?: string | null; districtId?: string | null; provinceId?: string | null; }[]; }; function imageLocation(id: string) { return `customer/${id}/profile-image`; } @Route("api/v1/customer") @Tags("Customer") @Security("keycloak") export class CustomerController extends Controller { @Get("type-stats") 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() async list( @Query() customerType?: CustomerType, @Query() query: string = "", @Query() page: number = 1, @Query() pageSize: number = 30, @Query() includeBranch: boolean = false, ) { const where = { OR: [ { customerName: { contains: query }, customerType }, { customerNameEN: { contains: query }, customerType }, ], } satisfies Prisma.CustomerWhereInput; const [result, total] = await prisma.$transaction([ prisma.customer.findMany({ include: { branch: includeBranch ? { include: { province: true, district: true, subDistrict: true, }, } : undefined, }, orderBy: { createdAt: "asc" }, where, take: pageSize, skip: (page - 1) * pageSize, }), prisma.customer.count({ where }), ]); return { result: await Promise.all( result.map(async (v) => ({ ...v, imageUrl: await presignedGetObjectIfExist( MINIO_BUCKET, imageLocation(v.id), 12 * 60 * 60, ), })), ), page, pageSize, total, }; } @Get("{customerId}") async getById(@Path() customerId: string) { const record = await prisma.customer.findFirst({ include: { branch: { include: { province: true, district: true, subDistrict: true, }, }, }, where: { id: customerId }, }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "data_not_found"); return Object.assign(record, { imageUrl: await presignedGetObjectIfExist( MINIO_BUCKET, imageLocation(record.id), 12 * 60 * 60, ), }); } @Post() async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) { const { customerBranch, ...payload } = body; const provinceId = body.customerBranch?.reduce((acc, cur) => { if (cur.provinceId && !acc.includes(cur.provinceId)) return acc.concat(cur.provinceId); return acc; }, []); const districtId = body.customerBranch?.reduce((acc, cur) => { if (cur.districtId && !acc.includes(cur.districtId)) return acc.concat(cur.districtId); return acc; }, []); const subDistrictId = body.customerBranch?.reduce((acc, cur) => { if (cur.subDistrictId && !acc.includes(cur.subDistrictId)) return acc.concat(cur.subDistrictId); return acc; }, []); const [province, district, subDistrict] = await prisma.$transaction([ prisma.province.findMany({ where: { id: { in: provinceId } } }), prisma.district.findMany({ where: { id: { in: districtId } } }), prisma.subDistrict.findMany({ where: { id: { in: subDistrictId } } }), ]); if (provinceId && province.length !== provinceId?.length) { throw new HttpError( HttpStatus.BAD_REQUEST, "Some province cannot be found.", "missing_or_invalid_parameter", ); } if (districtId && district.length !== districtId?.length) { throw new HttpError( HttpStatus.BAD_REQUEST, "Some district cannot be found.", "missing_or_invalid_parameter", ); } if (subDistrictId && subDistrict.length !== subDistrictId?.length) { throw new HttpError( HttpStatus.BAD_REQUEST, "Some sub district cannot be found.", "missing_or_invalid_parameter", ); } const record = await prisma.$transaction( async (tx) => { const last = await tx.runningNo.upsert({ where: { key: `CUSTOMER_${body.customerType}`, }, create: { key: `CUSTOMER_${body.customerType}`, value: 1, }, update: { value: { increment: 1 } }, }); return await prisma.customer.create({ include: { branch: { include: { province: true, district: true, subDistrict: true, }, }, }, data: { ...payload, code: `${last.key.slice(9)}${last.value.toString().padStart(6, "0")}`, branch: { createMany: { data: customerBranch?.map((v, i) => ({ ...v, branchNo: i + 1, createdBy: req.user.name, updateBy: req.user.name, })) || [], }, }, createdBy: req.user.name, updateBy: req.user.name, }, }); }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, ); this.setStatus(HttpStatus.CREATED); return Object.assign(record, { imageUrl: await presignedGetObjectIfExist( MINIO_BUCKET, imageLocation(record.id), 12 * 60 * 60, ), imageUploadUrl: await minio.presignedPutObject( MINIO_BUCKET, imageLocation(record.id), 12 * 60 * 60, ), }); } @Put("{customerId}") async editById( @Path() customerId: string, @Request() req: RequestWithUser, @Body() body: CustomerUpdate, ) { if (!(await prisma.customer.findUnique({ where: { id: customerId } }))) { throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "data_not_found"); } const provinceId = body.customerBranch?.reduce((acc, cur) => { if (cur.provinceId && !acc.includes(cur.provinceId)) return acc.concat(cur.provinceId); return acc; }, []); const districtId = body.customerBranch?.reduce((acc, cur) => { if (cur.districtId && !acc.includes(cur.districtId)) return acc.concat(cur.districtId); return acc; }, []); const subDistrictId = body.customerBranch?.reduce((acc, cur) => { if (cur.subDistrictId && !acc.includes(cur.subDistrictId)) return acc.concat(cur.subDistrictId); return acc; }, []); const [province, district, subDistrict] = await prisma.$transaction([ prisma.province.findMany({ where: { id: { in: provinceId } } }), prisma.district.findMany({ where: { id: { in: districtId } } }), prisma.subDistrict.findMany({ where: { id: { in: subDistrictId } } }), ]); if (provinceId && province.length !== provinceId?.length) { throw new HttpError( HttpStatus.BAD_REQUEST, "Some province cannot be found.", "missing_or_invalid_parameter", ); } if (districtId && district.length !== districtId?.length) { throw new HttpError( HttpStatus.BAD_REQUEST, "Some district cannot be found.", "missing_or_invalid_parameter", ); } if (subDistrictId && subDistrict.length !== subDistrictId?.length) { throw new HttpError( HttpStatus.BAD_REQUEST, "Some sub district cannot be found.", "missing_or_invalid_parameter", ); } const { customerBranch, ...payload } = body; const relation = await prisma.customerBranch.findMany({ where: { customerId, }, }); if ( customerBranch && relation.find((a) => !customerBranch.find((b) => a.id === b.id) && a.status !== "CREATED") ) { throw new HttpError( HttpStatus.BAD_REQUEST, "One or more branch cannot be delete and is missing.", "missing_or_invalid_parameter", ); } const record = await prisma.customer .update({ include: { branch: { include: { province: true, district: true, subDistrict: true, }, }, }, where: { id: customerId }, data: { ...payload, branch: (customerBranch && { deleteMany: { id: { notIn: customerBranch.map((v) => v.id).filter((v): v is string => !!v) || [], }, status: Status.CREATED, }, upsert: customerBranch.map((v, i) => ({ where: { id: v.id || "" }, create: { ...v, branchNo: i + 1, createdBy: req.user.name, updateBy: req.user.name, id: undefined, }, update: { ...v, branchNo: i + 1, updateBy: req.user.name, }, })), }) || undefined, updateBy: req.user.name, }, }) .then((v) => { if (customerBranch) { relation .filter((a) => !customerBranch.find((b) => b.id === a.id)) .forEach((deleted) => { new Promise((resolve, reject) => { const item: string[] = []; const stream = minio.listObjectsV2(MINIO_BUCKET, `customer/${deleted.id}`); stream.on("data", (v) => v && v.name && item.push(v.name)); stream.on("end", () => resolve(item)); stream.on("error", () => reject(new Error("MinIO error."))); }).then((list) => { list.map(async (v) => { await minio.removeObject(MINIO_BUCKET, v, { forceDelete: true, }); }); }); }); } return v; }); return Object.assign(record, { imageUrl: await presignedGetObjectIfExist( MINIO_BUCKET, imageLocation(record.id), 12 * 60 * 60, ), imageUploadUrl: await minio.presignedPutObject( MINIO_BUCKET, imageLocation(record.id), 12 * 60 * 60, ), }); } @Delete("{customerId}") 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.", "data_not_found"); } if (record.status !== Status.CREATED) { throw new HttpError(HttpStatus.FORBIDDEN, "Customer is in used.", "data_in_used"); } return await prisma.customer.delete({ where: { id: customerId } }).then((v) => { new Promise((resolve, reject) => { const item: string[] = []; const stream = minio.listObjectsV2(MINIO_BUCKET, `customer/${customerId}`); stream.on("data", (v) => v && v.name && item.push(v.name)); stream.on("end", () => resolve(item)); stream.on("error", () => reject(new Error("MinIO error."))); }).then((list) => { list.map(async (v) => { await minio.removeObject(MINIO_BUCKET, v, { forceDelete: true, }); }); }); return v; }); } }