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

330 lines
8.5 KiB
TypeScript
Raw Normal View History

2024-04-09 13:58:04 +07:00
import { CustomerType, Prisma, Status } from "@prisma/client";
2024-04-05 10:57:43 +07:00
import {
Body,
Controller,
Delete,
Get,
Path,
Post,
Put,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
2024-04-05 10:53:52 +07:00
import { RequestWithUser } from "../interfaces/user";
import prisma from "../db";
import minio, { deleteFolder, presignedGetObjectIfExist } from "../services/minio";
2024-04-05 10:53:52 +07:00
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;
2024-09-04 14:12:57 +07:00
const MANAGE_ROLES = ["system", "head_of_admin", "admin", "branch_manager", "head_of_sale", "sale"];
2024-04-05 10:53:52 +07:00
export type CustomerCreate = {
2024-07-03 14:36:11 +07:00
registeredBranchId?: string;
2024-04-05 10:53:52 +07:00
status?: Status;
2024-04-09 13:58:04 +07:00
customerType: CustomerType;
namePrefix: string;
firstName: string;
firstNameEN?: string;
lastName: string;
lastNameEN?: string;
gender: string;
birthDate: Date;
2024-04-05 10:53:52 +07:00
};
export type CustomerUpdate = {
2024-07-03 14:36:11 +07:00
registeredBranchId?: string;
2024-04-05 10:53:52 +07:00
status?: "ACTIVE" | "INACTIVE";
2024-08-27 13:28:51 +07:00
customerType?: CustomerType;
namePrefix?: string;
firstName?: string;
firstNameEN?: string;
2024-08-27 13:28:51 +07:00
lastName?: string;
lastNameEN?: string;
2024-08-27 13:28:51 +07:00
gender?: string;
birthDate?: Date;
2024-04-05 10:53:52 +07:00
};
function imageLocation(id: string) {
2024-06-07 10:44:40 +07:00
return `customer/${id}/profile-image`;
}
2024-06-06 09:42:02 +07:00
@Route("api/v1/customer")
2024-04-05 10:53:52 +07:00
@Tags("Customer")
export class CustomerController extends Controller {
2024-06-07 09:09:49 +07:00
@Get("type-stats")
2024-07-02 17:29:51 +07:00
@Security("keycloak")
2024-06-07 09:09:49 +07:00
async stat() {
const list = await prisma.customer.groupBy({
by: "customerType",
_count: true,
});
return list.reduce<Record<CustomerType, number>>(
(a, c) => {
a[c.customerType] = c._count;
return a;
},
{
CORP: 0,
PERS: 0,
},
);
}
2024-04-05 11:00:31 +07:00
@Get()
2024-07-02 17:29:51 +07:00
@Security("keycloak")
2024-04-05 11:00:31 +07:00
async list(
2024-06-10 14:11:45 +07:00
@Query() customerType?: CustomerType,
2024-04-05 11:00:31 +07:00
@Query() query: string = "",
2024-06-13 17:21:22 +07:00
@Query() status?: Status,
2024-04-05 11:00:31 +07:00
@Query() page: number = 1,
@Query() pageSize: number = 30,
@Query() includeBranch: boolean = false,
2024-04-05 11:00:31 +07:00
) {
const filterStatus = (val?: Status) => {
if (!val) return {};
return val !== Status.CREATED && val !== Status.ACTIVE
? { status: val }
: { OR: [{ status: Status.CREATED }, { status: Status.ACTIVE }] };
};
2024-04-05 11:00:31 +07:00
const where = {
2024-06-10 14:11:45 +07:00
OR: [
{ namePrefix: { contains: query } },
{ firstName: { contains: query } },
{ firstNameEN: { contains: query } },
2024-06-10 14:11:45 +07:00
],
AND: { customerType, ...filterStatus(status) },
2024-04-05 11:00:31 +07:00
} 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,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
2024-06-24 13:20:59 +07:00
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
2024-04-05 11:00:31 +07:00
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.customer.count({ where }),
]);
return { result, page, pageSize, total };
2024-04-05 11:00:31 +07:00
}
2024-04-05 11:00:44 +07:00
@Get("{customerId}")
2024-07-02 17:29:51 +07:00
@Security("keycloak")
2024-04-05 11:00:44 +07:00
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) {
2024-06-14 05:58:14 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
}
return Object.assign(record, { _count: { employee: countEmployee } });
2024-04-05 11:00:44 +07:00
}
2024-04-05 10:53:52 +07:00
@Post()
2024-07-03 14:36:11 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-04-05 10:53:52 +07:00
async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) {
const [branch] = await prisma.$transaction([
2024-07-03 14:36:11 +07:00
prisma.branch.findFirst({ where: { id: body.registeredBranchId } }),
]);
if (!!body.registeredBranchId && !branch) {
2024-07-03 14:36:11 +07:00
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,
},
2024-08-09 09:44:51 +07:00
});
return await tx.customer.create({
include: {
branch: {
include: {
province: true,
district: true,
subDistrict: true,
},
},
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
data: {
...body,
statusOrder: +(body.status === "INACTIVE"),
2024-07-01 13:24:02 +07:00
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
},
});
2024-04-05 10:53:52 +07:00
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
2024-04-05 10:53:52 +07:00
this.setStatus(HttpStatus.CREATED);
return record;
2024-04-05 10:53:52 +07:00
}
2024-04-05 11:02:23 +07:00
2024-04-05 11:18:01 +07:00
@Put("{customerId}")
2024-07-03 14:36:11 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-04-05 11:18:01 +07:00
async editById(
@Path() customerId: string,
@Request() req: RequestWithUser,
@Body() body: CustomerUpdate,
) {
const customer = await prisma.customer.findUnique({ where: { id: customerId } });
if (!customer) {
2024-06-14 05:58:14 +00:00
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({
2024-06-07 11:14:34 +07:00
include: {
branch: {
include: {
province: true,
district: true,
subDistrict: true,
},
},
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
2024-06-07 11:14:34 +07:00
},
where: { id: customerId },
data: {
...body,
statusOrder: +(body.status === "INACTIVE"),
2024-07-01 13:24:02 +07:00
updatedByUserId: req.user.sub,
2024-06-07 11:14:34 +07:00
},
});
2024-04-05 11:18:01 +07:00
});
return record;
2024-04-05 11:18:01 +07:00
}
2024-04-05 11:02:23 +07:00
@Delete("{customerId}")
2024-07-03 14:36:11 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-04-05 11:02:23 +07:00
async deleteById(@Path() customerId: string) {
const record = await prisma.customer.findFirst({ where: { id: customerId } });
if (!record) {
2024-06-14 05:58:14 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
2024-04-05 11:02:23 +07:00
}
if (record.status !== Status.CREATED) {
2024-06-14 05:58:14 +00:00
throw new HttpError(HttpStatus.FORBIDDEN, "Customer is in used.", "customerInUsed");
2024-04-05 11:02:23 +07:00
}
return await prisma.customer
.delete({ where: { id: customerId } })
.then(
async (data) => await deleteFolder(MINIO_BUCKET, `customer/${customerId}`).then(() => data),
);
2024-04-05 11:02:23 +07:00
}
@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),
);
}
2024-04-05 10:53:52 +07:00
}