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

344 lines
9.8 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 from "../services/minio";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { CustomerBranchCreate, CustomerBranchUpdate } from "./customer-branch-controller";
2024-04-05 10:53:52 +07:00
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
}
const MINIO_BUCKET = process.env.MINIO_BUCKET;
export type CustomerCreate = {
status?: Status;
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;
customerBranch?: Omit<CustomerBranchCreate, "customerId">[];
2024-04-05 10:53:52 +07:00
};
export type CustomerUpdate = {
status?: "ACTIVE" | "INACTIVE";
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;
customerBranch?: (Omit<CustomerBranchUpdate, "customerId"> & { id: string })[];
2024-04-05 10:53:52 +07:00
};
function imageLocation(id: string) {
return `customer/img-${id}`;
}
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-04-05 11:00:31 +07:00
@Get()
async list(
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
@Query() includeBranch: boolean = false,
2024-04-05 11:00:31 +07:00
) {
const where = {
OR: [{ customerName: { contains: query } }, { customerNameEN: { contains: query } }],
} satisfies Prisma.CustomerWhereInput;
const [result, total] = await prisma.$transaction([
prisma.customer.findMany({
include: {
branch: includeBranch
? {
include: {
province: true,
district: true,
subDistrict: true,
},
}
: undefined,
},
2024-04-09 08:51:22 +07:00
orderBy: { 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,
imageUrl: await minio.presignedGetObject(MINIO_BUCKET, imageLocation(v.id), 12 * 60 * 60),
})),
),
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)
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "data_not_found");
2024-04-05 11:06:01 +07:00
return Object.assign(record, {
imageUrl: await minio.presignedGetObject(
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.",
"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,
},
});
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, {
imageUrl: await minio.presignedGetObject(
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,
) {
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<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.",
"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;
2024-04-05 11:18:01 +07:00
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) || [] },
},
updateMany:
customerBranch.map((v) => ({
where: { id: v.id },
data: { ...v, updateBy: req.user.name },
})) || [],
}) ||
undefined,
2024-04-05 11:18:01 +07:00
updateBy: req.user.name,
},
});
return Object.assign(record, {
imageUrl: await minio.presignedGetObject(
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) {
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 } });
}
2024-04-05 10:53:52 +07:00
}