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

474 lines
14 KiB
TypeScript
Raw Normal View History

2024-04-09 15:13:44 +07:00
import { Prisma, Status, UserType } from "@prisma/client";
2024-04-02 09:28:36 +07:00
import {
Body,
Controller,
Delete,
Get,
2024-04-03 10:54:46 +07:00
Put,
2024-04-02 09:28:36 +07:00
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
2024-04-05 11:30:18 +07:00
import prisma from "../db";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import { RequestWithUser } from "../interfaces/user";
import minio from "../services/minio";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
}
const MINIO_BUCKET = process.env.MINIO_BUCKET;
type BranchCreate = {
status?: Status;
taxNo: string;
nameEN: string;
name: string;
addressEN: string;
address: string;
zipCode: string;
email: string;
2024-04-19 09:28:17 +07:00
contactName?: string | null;
contact?: string | string[] | null;
2024-04-18 13:21:37 +07:00
telephoneNo: string;
2024-04-19 09:28:17 +07:00
lineId?: string | null;
longitude: string;
latitude: string;
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
headOfficeId?: string | null;
};
type BranchUpdate = {
status?: "ACTIVE" | "INACTIVE";
taxNo?: string;
nameEN?: string;
name?: string;
addressEN?: string;
address?: string;
zipCode?: string;
email?: string;
telephoneNo?: string;
2024-04-17 13:42:11 +07:00
contactName?: string;
contact?: string | string[] | null;
lineId?: string;
longitude?: string;
latitude?: string;
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
headOfficeId?: string | null;
};
function lineImageLoc(id: string) {
return `branch/line-qr-${id}`;
}
2024-04-17 17:50:27 +07:00
function branchImageLoc(id: string) {
return `branch/branch-img-${id}`;
}
2024-06-06 09:42:02 +07:00
@Route("api/v1/branch")
2024-04-02 09:28:36 +07:00
@Tags("Branch")
@Security("keycloak")
export class BranchController extends Controller {
2024-04-10 17:27:00 +07:00
@Get("stats")
async getStats() {
const list = await prisma.branch.groupBy({
_count: true,
by: "isHeadOffice",
});
return list.reduce<Record<"hq" | "br", number>>(
(a, c) => {
a[c.isHeadOffice ? "hq" : "br"] = c._count;
return a;
},
{ hq: 0, br: 0 },
);
}
2024-04-09 15:13:44 +07:00
@Get("user-stats")
async getUserStat(@Query() userType?: UserType) {
2024-04-03 17:33:19 +07:00
const list = await prisma.branchUser.groupBy({
_count: true,
2024-04-09 15:13:44 +07:00
where: { user: { userType } },
by: "branchId",
2024-04-03 17:33:19 +07:00
});
const record = await prisma.branch.findMany({
select: {
id: true,
2024-04-23 13:48:08 +07:00
headOfficeId: true,
isHeadOffice: true,
2024-04-03 17:33:19 +07:00
nameEN: true,
name: true,
2024-04-03 17:33:19 +07:00
},
2024-04-23 13:48:08 +07:00
orderBy: [{ isHeadOffice: "desc" }, { createdAt: "asc" }],
2024-04-03 17:33:19 +07:00
});
2024-04-23 13:48:08 +07:00
const sort = record.reduce<(typeof record)[]>((acc, curr) => {
for (const i of acc) {
if (i[0].id === curr.headOfficeId) {
i.push(curr);
return acc;
}
}
acc.push([curr]);
return acc;
}, []);
return sort.flat().map((a) =>
2024-04-09 15:17:16 +07:00
Object.assign(a, {
count: list.find((b) => b.branchId === a.id)?._count ?? 0,
}),
);
2024-04-03 17:33:19 +07:00
}
2024-04-02 09:29:20 +07:00
@Get()
async getBranch(
@Query() zipCode?: string,
@Query() filter?: "head" | "sub",
@Query() headOfficeId?: string,
@Query() tree?: boolean,
2024-04-02 09:29:20 +07:00
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
AND: {
headOfficeId: headOfficeId ?? (filter === "head" || tree ? null : undefined),
NOT: { headOfficeId: filter === "sub" && !headOfficeId ? null : undefined },
},
2024-04-02 09:29:20 +07:00
OR: [
{ nameEN: { contains: query }, zipCode },
{ name: { contains: query }, zipCode },
2024-04-02 09:29:20 +07:00
{ email: { contains: query }, zipCode },
2024-04-18 16:14:25 +07:00
{ telephoneNo: { contains: query }, zipCode },
2024-04-02 09:29:20 +07:00
],
} satisfies Prisma.BranchWhereInput;
const [result, total] = await prisma.$transaction([
prisma.branch.findMany({
2024-04-09 08:51:22 +07:00
orderBy: { createdAt: "asc" },
2024-04-02 09:29:20 +07:00
include: {
province: true,
district: true,
subDistrict: true,
2024-04-17 13:59:30 +07:00
contact: true,
branch: tree && {
include: {
province: true,
district: true,
subDistrict: true,
},
},
2024-04-02 09:29:20 +07:00
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.branch.count({ where }),
]);
return { result, page, pageSize, total };
}
@Get("{branchId}")
async getBranchById(
@Path() branchId: string,
@Query() includeSubBranch?: boolean,
@Query() includeContact?: boolean,
) {
2024-04-02 15:32:17 +07:00
const record = await prisma.branch.findFirst({
2024-04-02 09:29:20 +07:00
include: {
province: true,
district: true,
subDistrict: true,
branch: includeSubBranch && {
include: {
province: true,
district: true,
subDistrict: true,
},
},
contact: includeContact,
2024-04-02 09:29:20 +07:00
},
where: { id: branchId },
});
2024-04-02 15:32:17 +07:00
if (!record) {
2024-06-14 05:44:03 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
2024-04-02 15:32:17 +07:00
}
2024-04-18 14:37:01 +07:00
return Object.assign(record, {
imageUrl: await minio.presignedGetObject(MINIO_BUCKET, branchImageLoc(record.id)),
qrCodeImageUrl: await minio.presignedGetObject(MINIO_BUCKET, lineImageLoc(record.id)),
});
2024-04-02 09:29:20 +07:00
}
2024-04-02 10:45:37 +07:00
2024-04-02 11:19:12 +07:00
@Post()
async createBranch(@Request() req: RequestWithUser, @Body() body: BranchCreate) {
2024-04-09 11:45:29 +07:00
const [province, district, subDistrict, head] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId || undefined } }),
prisma.district.findFirst({ where: { id: body.districtId || undefined } }),
prisma.subDistrict.findFirst({ where: { id: body.subDistrictId || undefined } }),
prisma.branch.findFirst({ where: { id: body.headOfficeId || undefined } }),
]);
if (body.provinceId && !province)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Province cannot be found.",
2024-06-14 05:44:03 +00:00
"relationProvinceNotFound",
2024-04-09 11:45:29 +07:00
);
if (body.districtId && !district)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"District cannot be found.",
2024-06-14 05:44:03 +00:00
"relationDistrictNotFound",
2024-04-09 11:45:29 +07:00
);
if (body.subDistrictId && !subDistrict)
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Sub-district cannot be found.",
2024-06-14 05:44:03 +00:00
"relationSubDistrictNotFound",
2024-04-09 11:45:29 +07:00
);
if (body.headOfficeId && !head)
throw new HttpError(
HttpStatus.BAD_REQUEST,
2024-06-14 05:44:03 +00:00
"Headquaters cannot be found.",
"relationHQNotFound",
2024-04-09 11:45:29 +07:00
);
2024-04-02 11:19:12 +07:00
2024-04-18 13:21:37 +07:00
const { provinceId, districtId, subDistrictId, headOfficeId, contact, ...rest } = body;
2024-04-02 11:19:12 +07:00
2024-04-09 11:45:29 +07:00
const year = new Date().getFullYear();
2024-04-22 17:05:08 +07:00
const record = await prisma.$transaction(
async (tx) => {
const last = await tx.runningNo.upsert({
where: {
key: !headOfficeId ? `HQ${year.toString().slice(2)}` : `BR${head?.code.slice(2, 5)}`,
},
create: {
key: !headOfficeId ? `HQ${year.toString().slice(2)}` : `BR${head?.code.slice(2, 5)}`,
value: 1,
},
update: { value: { increment: 1 } },
});
2024-04-09 11:45:29 +07:00
2024-04-22 17:05:08 +07:00
const code = !headOfficeId
? `HQ${year.toString().slice(2)}${last.value}`
: `BR${head?.code.slice(2, 5)}${last.value.toString().padStart(2, "0")}`;
2024-04-09 11:45:29 +07:00
2024-04-22 17:05:08 +07:00
return await tx.branch.create({
include: {
province: true,
district: true,
subDistrict: true,
},
data: {
...rest,
2024-06-24 13:14:44 +07:00
statusOrder: +(rest.status === "INACTIVE"),
2024-04-22 17:05:08 +07:00
code,
isHeadOffice: !headOfficeId,
province: { connect: provinceId ? { id: provinceId } : undefined },
district: { connect: districtId ? { id: districtId } : undefined },
subDistrict: { connect: subDistrictId ? { id: subDistrictId } : undefined },
headOffice: { connect: headOfficeId ? { id: headOfficeId } : undefined },
2024-07-01 13:24:02 +07:00
createdBy: { connect: { id: req.user.sub } },
updatedBy: { connect: { id: req.user.sub } },
2024-04-22 17:05:08 +07:00
},
});
},
2024-04-23 11:19:27 +07:00
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
2024-04-22 17:05:08 +07:00
);
if (headOfficeId) {
await prisma.branch.updateMany({
where: { id: headOfficeId, status: Status.CREATED },
data: { status: Status.ACTIVE },
});
}
this.setStatus(HttpStatus.CREATED);
2024-04-18 13:21:37 +07:00
if (record && contact) {
2024-04-17 13:42:11 +07:00
await prisma.branchContact.createMany({
data:
2024-04-18 13:21:37 +07:00
typeof contact === "string"
? [{ telephoneNo: contact, branchId: record.id }]
: contact.map((v) => ({ telephoneNo: v, branchId: record.id })),
2024-04-17 13:42:11 +07:00
});
}
return Object.assign(record, {
2024-04-17 13:42:11 +07:00
contact: await prisma.branchContact.findMany({ where: { branchId: record.id } }),
2024-04-17 17:50:27 +07:00
imageUrl: await minio.presignedGetObject(MINIO_BUCKET, branchImageLoc(record.id)),
imageUploadUrl: await minio.presignedPutObject(MINIO_BUCKET, branchImageLoc(record.id)),
qrCodeImageUrl: await minio.presignedGetObject(
MINIO_BUCKET,
lineImageLoc(record.id),
12 * 60 * 60,
),
qrCodeImageUploadUrl: await minio.presignedPutObject(
MINIO_BUCKET,
lineImageLoc(record.id),
12 * 60 * 60,
),
});
2024-04-02 11:19:12 +07:00
}
2024-04-03 10:54:46 +07:00
@Put("{branchId}")
2024-04-02 11:52:55 +07:00
async editBranch(
@Request() req: RequestWithUser,
@Body() body: BranchUpdate,
@Path() branchId: string,
) {
2024-04-10 16:21:56 +07:00
if (body.headOfficeId === branchId)
throw new HttpError(
HttpStatus.BAD_REQUEST,
2024-06-14 05:44:03 +00:00
"Cannot make this as headquaters and branch at the same time.",
"cantMakeHQAndBranchSameTime",
2024-04-10 16:21:56 +07:00
);
2024-04-02 11:52:55 +07:00
if (body.subDistrictId || body.districtId || body.provinceId || body.headOfficeId) {
const [province, district, subDistrict, branch] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId || undefined } }),
prisma.district.findFirst({ where: { id: body.districtId || undefined } }),
prisma.subDistrict.findFirst({ where: { id: body.subDistrictId || undefined } }),
prisma.branch.findFirst({ where: { id: body.headOfficeId || undefined } }),
]);
if (body.provinceId && !province)
2024-04-02 15:32:17 +07:00
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Province cannot be found.",
2024-06-14 05:44:03 +00:00
"relationProvinceNotFound",
2024-04-02 15:32:17 +07:00
);
2024-04-02 11:52:55 +07:00
if (body.districtId && !district)
2024-04-02 15:32:17 +07:00
throw new HttpError(
HttpStatus.BAD_REQUEST,
"District cannot be found.",
2024-06-14 05:44:03 +00:00
"relationDistrictNotFound",
2024-04-02 15:32:17 +07:00
);
2024-04-02 11:52:55 +07:00
if (body.subDistrictId && !subDistrict)
2024-04-02 15:32:17 +07:00
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Sub-district cannot be found.",
2024-06-14 05:44:03 +00:00
"relationSubDistrictNotFound",
2024-04-02 15:32:17 +07:00
);
2024-04-02 11:52:55 +07:00
if (body.headOfficeId && !branch)
2024-04-02 15:32:17 +07:00
throw new HttpError(
HttpStatus.BAD_REQUEST,
2024-06-14 05:44:03 +00:00
"Headquaters cannot be found.",
"relationHQNotFound",
2024-04-02 15:32:17 +07:00
);
2024-04-02 11:52:55 +07:00
}
2024-04-18 13:21:37 +07:00
const { provinceId, districtId, subDistrictId, headOfficeId, contact, ...rest } = body;
2024-04-02 11:52:55 +07:00
if (!(await prisma.branch.findUnique({ where: { id: branchId } }))) {
2024-06-14 05:44:03 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
}
2024-04-02 11:52:55 +07:00
const record = await prisma.branch.update({
include: { province: true, district: true, subDistrict: true },
data: {
...rest,
2024-06-24 13:14:44 +07:00
statusOrder: +(rest.status === "INACTIVE"),
isHeadOffice: headOfficeId !== undefined ? headOfficeId === null : undefined,
2024-04-02 11:52:55 +07:00
province: {
connect: provinceId ? { id: provinceId } : undefined,
disconnect: provinceId === null || undefined,
},
district: {
connect: districtId ? { id: districtId } : undefined,
disconnect: districtId === null || undefined,
},
subDistrict: {
connect: subDistrictId ? { id: subDistrictId } : undefined,
disconnect: subDistrictId === null || undefined,
},
headOffice: {
connect: headOfficeId ? { id: headOfficeId } : undefined,
disconnect: headOfficeId === null || undefined,
},
2024-07-01 13:24:02 +07:00
updatedBy: { connect: { id: req.user.sub } },
2024-04-02 11:52:55 +07:00
},
where: { id: branchId },
});
if (record && contact !== undefined) {
2024-04-17 13:46:16 +07:00
await prisma.branchContact.deleteMany({ where: { branchId } });
contact &&
(await prisma.branchContact.createMany({
data:
typeof contact === "string"
? [{ telephoneNo: contact, branchId }]
: contact.map((v) => ({ telephoneNo: v, branchId })),
}));
2024-04-17 13:46:16 +07:00
}
return Object.assign(record, {
2024-04-17 17:50:27 +07:00
imageUrl: await minio.presignedGetObject(MINIO_BUCKET, branchImageLoc(record.id)),
imageUploadUrl: await minio.presignedPutObject(MINIO_BUCKET, branchImageLoc(record.id)),
qrCodeImageUrl: await minio.presignedGetObject(
MINIO_BUCKET,
lineImageLoc(record.id),
12 * 60 * 60,
),
qrCodeImageUploadUrl: await minio.presignedPutObject(
MINIO_BUCKET,
lineImageLoc(record.id),
12 * 60 * 60,
),
});
2024-04-02 11:52:55 +07:00
}
2024-04-02 10:45:37 +07:00
@Delete("{branchId}")
async deleteBranch(@Path() branchId: string) {
const record = await prisma.branch.findFirst({
include: {
province: true,
district: true,
subDistrict: true,
},
where: { id: branchId },
});
2024-04-02 10:45:37 +07:00
if (!record) {
2024-06-14 05:44:03 +00:00
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
2024-04-02 10:45:37 +07:00
}
if (record.status !== Status.CREATED) {
2024-06-14 05:44:03 +00:00
throw new HttpError(HttpStatus.FORBIDDEN, "Branch is in used.", "branchInUsed");
2024-04-02 10:45:37 +07:00
}
await minio.removeObject(MINIO_BUCKET, lineImageLoc(branchId), {
forceDelete: true,
});
2024-04-17 17:50:27 +07:00
await minio.removeObject(MINIO_BUCKET, branchImageLoc(branchId), {
forceDelete: true,
});
return await prisma.branch.delete({
include: {
province: true,
district: true,
subDistrict: true,
},
where: { id: branchId },
});
2024-04-02 10:45:37 +07:00
}
2024-04-02 09:28:36 +07:00
}