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

526 lines
15 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";
2024-06-10 11:12:43 +07:00
import minio, { 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;
export type CustomerCreate = {
status?: Status;
2024-06-17 17:58:30 +07:00
personName: string;
personNameEN?: string;
2024-04-09 13:58:04 +07:00
customerType: CustomerType;
2024-04-05 10:53:52 +07:00
customerName: string;
customerNameEN: string;
2024-04-24 10:02:37 +07:00
taxNo?: string | null;
2024-06-07 11:34:04 +07:00
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;
2024-06-07 13:54:02 +07:00
payDate: Date;
2024-06-07 14:02:31 +07:00
wageRate: number;
2024-06-07 11:34:04 +07:00
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
}[];
2024-04-05 10:53:52 +07:00
};
export type CustomerUpdate = {
status?: "ACTIVE" | "INACTIVE";
2024-06-19 14:10:31 +07:00
personName?: string;
2024-06-17 17:58:30 +07:00
personNameEN?: string;
customerType?: CustomerType;
2024-04-05 10:53:52 +07:00
customerName?: string;
customerNameEN?: string;
2024-04-24 10:02:37 +07:00
taxNo?: string | null;
2024-06-07 11:34:04 +07:00
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;
2024-06-07 13:54:02 +07:00
payDate: Date;
2024-06-07 14:02:31 +07:00
wageRate: number;
2024-06-07 11:34:04 +07:00
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
}[];
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")
2024-04-05 10:57:14 +07:00
@Security("keycloak")
2024-04-05 10:53:52 +07:00
export class CustomerController extends Controller {
2024-06-07 09:09:49 +07:00
@Get("type-stats")
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()
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: [
2024-06-17 09:26:01 +07:00
{ customerName: { contains: query }, customerType, ...filterStatus(status) },
{ customerNameEN: { contains: query }, customerType, ...filterStatus(status) },
2024-06-10 14:11:45 +07:00
],
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,
},
}
: undefined,
},
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: await Promise.all(
result.map(async (v) => ({
...v,
2024-06-10 11:12:43 +07:00
imageUrl: await presignedGetObjectIfExist(
MINIO_BUCKET,
imageLocation(v.id),
12 * 60 * 60,
),
2024-04-05 11:00:31 +07:00
})),
),
page,
pageSize,
total,
};
}
2024-04-05 11:00:44 +07:00
@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 },
});
2024-04-05 11:00:44 +07:00
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:06:01 +07:00
return Object.assign(record, {
2024-06-10 13:57:24 +07:00
imageUrl: await presignedGetObjectIfExist(
2024-04-05 11:06:01 +07:00
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
});
2024-04-05 11:00:44 +07:00
}
2024-04-05 10:53:52 +07:00
@Post()
async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) {
const { customerBranch, ...payload } = body;
const provinceId = body.customerBranch?.reduce<string[]>((acc, cur) => {
if (cur.provinceId && !acc.includes(cur.provinceId)) return acc.concat(cur.provinceId);
return acc;
}, []);
const districtId = body.customerBranch?.reduce<string[]>((acc, cur) => {
if (cur.districtId && !acc.includes(cur.districtId)) return acc.concat(cur.districtId);
return acc;
}, []);
const subDistrictId = body.customerBranch?.reduce<string[]>((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.",
2024-06-14 05:58:14 +00:00
"relationProvinceNotFound",
);
}
if (districtId && district.length !== districtId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some district cannot be found.",
2024-06-14 05:58:14 +00:00
"relationDistrictNotFound",
);
}
if (subDistrictId && subDistrict.length !== subDistrictId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some sub district cannot be found.",
2024-06-14 05:58:14 +00:00
"relationSubDistrictNotFound",
);
}
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,
2024-06-24 13:14:44 +07:00
statusOrder: +(payload.status === "INACTIVE"),
code: `${last.key.slice(9)}${last.value.toString().padStart(6, "0")}`,
branch: {
createMany: {
data:
customerBranch?.map((v, i) => ({
...v,
2024-06-07 13:54:02 +07:00
branchNo: i + 1,
code: `${last.key.slice(9)}${last.value.toString().padStart(6, "0")}-${(i + 1).toString().padStart(2, "0")}`,
2024-07-01 13:24:02 +07:00
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
})) || [],
},
},
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 Object.assign(record, {
2024-06-10 13:12:26 +07:00
imageUrl: await presignedGetObjectIfExist(
2024-04-05 10:53:52 +07:00
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
imageUploadUrl: await minio.presignedPutObject(
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
});
}
2024-04-05 11:02:23 +07:00
2024-04-05 11:18:01 +07:00
@Put("{customerId}")
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 provinceId = body.customerBranch?.reduce<string[]>((acc, cur) => {
if (cur.provinceId && !acc.includes(cur.provinceId)) return acc.concat(cur.provinceId);
return acc;
}, []);
const districtId = body.customerBranch?.reduce<string[]>((acc, cur) => {
if (cur.districtId && !acc.includes(cur.districtId)) return acc.concat(cur.districtId);
return acc;
}, []);
const subDistrictId = body.customerBranch?.reduce<string[]>((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.",
2024-06-14 05:58:14 +00:00
"relationProvinceNotFound",
);
}
if (districtId && district.length !== districtId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some district cannot be found.",
2024-06-14 05:58:14 +00:00
"relationDistrictNotFound",
);
}
if (subDistrictId && subDistrict.length !== subDistrictId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some sub district cannot be found.",
2024-06-14 05:58:14 +00:00
"relationSubDistrictNotFound",
);
}
const { customerBranch, ...payload } = body;
2024-06-07 11:14:34 +07:00
const relation = await prisma.customerBranch.findMany({
where: {
customerId,
2024-04-05 11:18:01 +07:00
},
});
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.",
2024-06-14 05:58:14 +00:00
"oneOrMoreBranchMissing",
);
}
2024-06-07 11:14:34 +07:00
const record = await prisma.customer
.update({
include: {
branch: {
include: {
province: true,
district: true,
subDistrict: true,
},
},
},
where: { id: customerId },
data: {
...payload,
2024-06-24 13:14:44 +07:00
statusOrder: +(payload.status === "INACTIVE"),
2024-06-07 11:14:34 +07:00
branch:
(customerBranch && {
deleteMany: {
id: {
notIn: customerBranch.map((v) => v.id).filter((v): v is string => !!v) || [],
},
status: Status.CREATED,
2024-06-07 11:14:34 +07:00
},
upsert: customerBranch.map((v, i) => ({
where: { id: v.id || "" },
create: {
...v,
2024-06-07 13:54:02 +07:00
branchNo: i + 1,
code: `${customer.code}-${(i + 1).toString().padStart(2, "0")}`,
2024-07-01 13:24:02 +07:00
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
2024-06-07 11:14:34 +07:00
id: undefined,
},
update: {
...v,
2024-06-07 13:54:02 +07:00
branchNo: i + 1,
code: `${customer.code}-${(i + 1).toString().padStart(2, "0")}`,
2024-07-01 13:24:02 +07:00
updatedByUserId: req.user.sub,
2024-06-07 11:14:34 +07:00
},
})),
}) ||
undefined,
2024-07-01 13:24:02 +07:00
updatedByUserId: req.user.sub,
2024-06-07 11:14:34 +07:00
},
})
.then((v) => {
if (customerBranch) {
relation
.filter((a) => !customerBranch.find((b) => b.id === a.id))
2024-06-07 11:14:34 +07:00
.forEach((deleted) => {
new Promise<string[]>((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;
});
2024-04-05 11:18:01 +07:00
return Object.assign(record, {
2024-06-10 11:12:43 +07:00
imageUrl: await presignedGetObjectIfExist(
2024-04-05 11:18:01 +07:00
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
imageUploadUrl: await minio.presignedPutObject(
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
});
}
2024-04-05 11:02:23 +07:00
@Delete("{customerId}")
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
}
2024-06-07 10:44:40 +07:00
return await prisma.customer.delete({ where: { id: customerId } }).then((v) => {
new Promise<string[]>((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;
});
2024-04-05 11:02:23 +07:00
}
2024-04-05 10:53:52 +07:00
}