refactor: customer create and update process

This commit is contained in:
Methapon Metanipat 2024-08-20 15:41:48 +07:00
parent b167a612b4
commit 5bb8da818c
6 changed files with 261 additions and 462 deletions

View file

@ -15,7 +15,7 @@ import {
} from "tsoa";
import { RequestWithUser } from "../interfaces/user";
import prisma from "../db";
import minio, { presignedGetObjectIfExist } from "../services/minio";
import minio, { deleteFolder, presignedGetObjectIfExist } from "../services/minio";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
@ -37,95 +37,31 @@ const MANAGE_ROLES = [
export type CustomerCreate = {
registeredBranchId?: string;
code: string;
status?: Status;
personName: string;
personNameEN?: string;
customerType: CustomerType;
customerName: string;
customerNameEN: string;
taxNo?: string | null;
customerBranch?: {
status?: Status;
legalPersonNo: string;
branchNo: number;
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;
}[];
namePrefix: string;
firstName: string;
firstNameEN?: string;
lastName: string;
lastNameEN?: string;
gender: string;
birthDate: Date;
};
export type CustomerUpdate = {
registeredBranchId?: string;
status?: "ACTIVE" | "INACTIVE";
personName?: string;
personNameEN?: string;
customerType?: CustomerType;
customerName?: string;
customerNameEN?: string;
taxNo?: string | null;
customerBranch?: {
id?: string;
status?: Status;
legalPersonNo: string;
branchNo: number;
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;
}[];
customerType: CustomerType;
namePrefix: string;
firstName: string;
firstNameEN?: string;
lastName: string;
lastNameEN?: string;
gender: string;
birthDate: Date;
};
function imageLocation(id: string) {
@ -167,16 +103,17 @@ export class CustomerController extends Controller {
) {
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: [
{ customerName: { contains: query }, customerType, ...filterStatus(status) },
{ customerNameEN: { contains: query }, customerType, ...filterStatus(status) },
{ namePrefix: { contains: query } },
{ firstName: { contains: query } },
{ firstNameEN: { contains: query } },
],
AND: { customerType, ...filterStatus(status) },
} satisfies Prisma.CustomerWhereInput;
const [result, total] = await prisma.$transaction([
@ -190,9 +127,7 @@ export class CustomerController extends Controller {
district: true,
subDistrict: true,
},
orderBy: {
branchNo: "asc",
},
orderBy: { createdAt: "asc" },
}
: undefined,
createdBy: true,
@ -206,21 +141,7 @@ export class CustomerController extends Controller {
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,
};
return { result, page, pageSize, total };
}
@Get("{customerId}")
@ -234,71 +155,27 @@ export class CustomerController extends Controller {
district: true,
subDistrict: true,
},
orderBy: { branchNo: "asc" },
orderBy: { createdAt: "asc" },
},
createdBy: true,
updatedBy: true,
},
where: { id: customerId },
});
if (!record)
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
return Object.assign(record, {
imageUrl: await presignedGetObjectIfExist(
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
});
}
return record;
}
@Post()
@Security("keycloak", MANAGE_ROLES)
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, branch] = await prisma.$transaction([
prisma.province.findMany({ where: { id: { in: provinceId } } }),
prisma.district.findMany({ where: { id: { in: districtId } } }),
prisma.subDistrict.findMany({ where: { id: { in: subDistrictId } } }),
const [branch] = await prisma.$transaction([
prisma.branch.findFirst({ where: { id: body.registeredBranchId } }),
]);
if (provinceId && province.length !== provinceId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some province cannot be found.",
"relationProvinceNotFound",
);
}
if (districtId && district.length !== districtId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some district cannot be found.",
"relationDistrictNotFound",
);
}
if (subDistrictId && subDistrict.length !== subDistrictId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some sub district cannot be found.",
"relationSubDistrictNotFound",
);
}
if (!!body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
@ -306,27 +183,24 @@ export class CustomerController extends Controller {
"relationBranchNotFound",
);
}
if (!body.registeredBranchId) {
body.registeredBranchId = undefined;
}
const record = await prisma.$transaction(
async (tx) => {
body.code = body.code.toLocaleUpperCase();
const exist = await tx.customer.findFirst({
where: { code: body.code },
await tx.branch.updateMany({
where: {
id: body.registeredBranchId,
status: "CREATED",
},
data: {
status: "INACTIVE",
statusOrder: 1,
},
});
if (exist) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Customer with same code already exists.",
"sameCustomerCodeExists",
);
}
return await prisma.customer.create({
return await tx.customer.create({
include: {
branch: {
include: {
@ -339,20 +213,8 @@ export class CustomerController extends Controller {
updatedBy: true,
},
data: {
...payload,
statusOrder: +(payload.status === "INACTIVE"),
code: `${body.code}000000`,
branch: {
createMany: {
data:
customerBranch?.map((v) => ({
...v,
code: body.code,
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
})) || [],
},
},
...body,
statusOrder: +(body.status === "INACTIVE"),
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
},
@ -363,18 +225,7 @@ export class CustomerController extends Controller {
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,
),
});
return record;
}
@Put("{customerId}")
@ -390,80 +241,25 @@ export class CustomerController extends Controller {
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 } } }),
const [branch] = await prisma.$transaction([
prisma.customer.findUnique({ where: { id: customerId } }),
prisma.branch.findFirst({ where: { id: body.registeredBranchId } }),
]);
if (provinceId && province.length !== provinceId?.length) {
if (!!body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some province cannot be found.",
"relationProvinceNotFound",
);
}
if (districtId && district.length !== districtId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some district cannot be found.",
"relationDistrictNotFound",
);
}
if (subDistrictId && subDistrict.length !== subDistrictId?.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some sub district cannot be found.",
"relationSubDistrictNotFound",
"Branch cannot be found.",
"relationBranchNotFound",
);
}
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.",
"oneOrMoreBranchMissing",
);
if (!body.registeredBranchId) {
body.registeredBranchId = undefined;
}
if (
customerBranch &&
relation.find((a) => customerBranch.find((b) => a.id !== b.id && a.branchNo === b.branchNo))
) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot have same number.",
"oneOrMoreBranchNoExist",
);
}
const record = await prisma.customer
.update({
const record = await prisma.$transaction(async (tx) => {
return await tx.customer.update({
include: {
branch: {
include: {
@ -477,74 +273,14 @@ export class CustomerController extends Controller {
},
where: { id: customerId },
data: {
...payload,
statusOrder: +(payload.status === "INACTIVE"),
branch:
(customerBranch && {
deleteMany: {
id: {
notIn: customerBranch.map((v) => v.id).filter((v): v is string => !!v) || [],
},
status: Status.CREATED,
},
upsert: customerBranch.map((v) => ({
where: { id: v.id || "" },
create: {
...v,
code: `${customer.code}-${v.branchNo.toString().padStart(2, "0")}`,
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
id: undefined,
},
update: {
...v,
code: undefined,
branchNo: undefined,
updatedByUserId: req.user.sub,
},
})),
}) ||
undefined,
...body,
statusOrder: +(body.status === "INACTIVE"),
updatedByUserId: req.user.sub,
},
})
.then((v) => {
if (customerBranch) {
relation
.filter((a) => !customerBranch.find((b) => b.id === a.id))
.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;
});
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,
),
});
return record;
}
@Delete("{customerId}")
@ -560,24 +296,11 @@ export class CustomerController extends Controller {
throw new HttpError(HttpStatus.FORBIDDEN, "Customer is in used.", "customerInUsed");
}
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;
});
return await prisma.customer
.delete({ where: { id: customerId } })
.then(
async (data) => await deleteFolder(MINIO_BUCKET, `customer/${customerId}`).then(() => data),
);
}
@Get("{customerId}/image")