jws-backend/src/controllers/service/service-controller.ts
2024-09-04 14:01:59 +07:00

485 lines
12 KiB
TypeScript

import {
Body,
Controller,
Delete,
Get,
Put,
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
import { Prisma, Status } from "@prisma/client";
import prisma from "../../db";
import minio, { presignedGetObjectIfExist } from "../../services/minio";
import { RequestWithUser } from "../../interfaces/user";
import HttpError from "../../interfaces/http-error";
import HttpStatus from "../../interfaces/http-status";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
}
const MINIO_BUCKET = process.env.MINIO_BUCKET;
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"branch_admin",
"branch_manager",
"head_of_account",
"account",
];
type ServiceCreate = {
code: string;
name: string;
detail: string;
attributes?: {
[key: string]: any;
};
status?: Status;
work?: {
name: string;
productId: string[];
attributes?: { [key: string]: any };
}[];
productGroupId: string;
registeredBranchId?: string;
};
type ServiceUpdate = {
name?: string;
detail?: string;
attributes?: {
[key: string]: any;
};
status?: "ACTIVE" | "INACTIVE";
work?: {
name: string;
productId: string[];
attributes?: { [key: string]: any };
}[];
productGroupId?: string;
registeredBranchId?: string;
};
function imageLocation(id: string) {
return `service/${id}/service-image`;
}
function globalAllow(roles?: string[]) {
return ["system", "head_of_admin", "admin", "head_of_account"].some((v) => roles?.includes(v));
}
@Route("api/v1/service")
@Tags("Service")
export class ServiceController extends Controller {
@Get("stats")
@Security("keycloak")
async getServiceStats(@Query() productGroupId?: string) {
return await prisma.service.count({ where: { productGroupId } });
}
@Get()
@Security("keycloak")
async getService(
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
@Query() status?: Status,
@Query() productGroupId?: string,
@Query() registeredBranchId?: string,
@Query() fullDetail?: boolean,
) {
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: [
{ name: { contains: query }, productGroupId, ...filterStatus(status) },
{ detail: { contains: query }, productGroupId, ...filterStatus(status) },
],
AND: registeredBranchId
? {
OR: [{ registeredBranchId: registeredBranchId }, { registeredBranchId: null }],
}
: undefined,
} satisfies Prisma.ServiceWhereInput;
const [result, total] = await prisma.$transaction([
prisma.service.findMany({
include: {
work: fullDetail
? {
orderBy: { order: "asc" },
include: {
productOnWork: {
include: { product: true },
orderBy: { order: "asc" },
},
},
}
: true,
createdBy: true,
updatedBy: true,
},
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.service.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,
};
}
@Get("{serviceId}")
@Security("keycloak")
async getServiceById(@Path() serviceId: string) {
const record = await prisma.service.findFirst({
include: {
work: {
orderBy: { order: "asc" },
include: {
productOnWork: {
include: { product: true },
orderBy: { order: "asc" },
},
},
},
createdBy: true,
updatedBy: true,
},
where: { id: serviceId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
}
return Object.assign(record, {
imageUrl: await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(record.id), 60 * 60),
});
}
@Get("{serviceId}/work")
@Security("keycloak")
async getWorkOfService(
@Path() serviceId: string,
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
serviceId,
} satisfies Prisma.WorkWhereInput;
const [result, total] = await prisma.$transaction([
prisma.work.findMany({
include: {
productOnWork: {
include: {
product: true,
},
orderBy: { order: "asc" },
},
createdBy: true,
updatedBy: true,
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.work.count({ where }),
]);
return { result, page, pageSize, total };
}
@Get("{serviceId}/image")
async getServiceImageById(@Request() req: RequestWithUser, @Path() serviceId: string) {
const url = await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(serviceId), 60 * 60);
if (!url) {
throw new HttpError(HttpStatus.NOT_FOUND, "Image cannot be found", "imageNotFound");
}
return req.res?.redirect(url);
}
@Post()
@Security("keycloak", MANAGE_ROLES)
async createService(@Request() req: RequestWithUser, @Body() body: ServiceCreate) {
const { work, productGroupId, ...payload } = body;
const [productGroup, branch] = await prisma.$transaction([
prisma.productGroup.findFirst({
include: {
createdBy: true,
updatedBy: true,
},
where: { id: body.productGroupId },
}),
prisma.branch.findFirst({
include: { user: { where: { userId: req.user.sub } } },
where: { id: body.registeredBranchId },
}),
]);
if (!globalAllow(req.user.roles) && !branch?.user.find((v) => v.userId === req.user.sub)) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (!productGroup) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Product Type cannot be found.",
"relationproductGroupNotFound",
);
}
if (body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
const record = await prisma.$transaction(
async (tx) => {
const last = await tx.runningNo.upsert({
where: {
key: `SERVICE_${body.code.toLocaleUpperCase()}`,
},
create: {
key: `SERVICE_${body.code.toLocaleUpperCase()}`,
value: 1,
},
update: { value: { increment: 1 } },
});
return tx.service.create({
include: {
work: {
include: {
productOnWork: {
include: { product: true },
orderBy: { order: "asc" },
},
},
},
createdBy: true,
updatedBy: true,
},
data: {
...payload,
productGroupId,
statusOrder: +(body.status === "INACTIVE"),
code: `${body.code.toLocaleUpperCase()}${last.value.toString().padStart(3, "0")}`,
work: {
create: (work || []).map((w, wIdx) => ({
name: w.name,
order: wIdx + 1,
attributes: w.attributes,
productOnWork: {
create: w.productId.map((p, pIdx) => ({
productId: p,
order: pIdx + 1,
})),
},
})),
},
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
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,
),
});
}
@Put("{serviceId}")
@Security("keycloak", MANAGE_ROLES)
async editService(
@Request() req: RequestWithUser,
@Body() body: ServiceUpdate,
@Path() serviceId: string,
) {
if (!(await prisma.service.findUnique({ where: { id: serviceId } }))) {
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
}
const { work, productGroupId, ...payload } = body;
const [service, productGroup, branch] = await prisma.$transaction([
prisma.service.findUnique({
include: {
registeredBranch: {
where: {
user: { some: { userId: req.user.sub } },
},
},
},
where: { id: serviceId },
}),
prisma.productGroup.findFirst({
include: {
createdBy: true,
updatedBy: true,
},
where: { id: body.productGroupId },
}),
prisma.branch.findFirst({ where: { id: body.registeredBranchId } }),
]);
if (!service) {
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
}
if (!globalAllow(req.user.roles) && !service.registeredBranch) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (!productGroup) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Product Type cannot be found.",
"relationproductGroupNotFound",
);
}
if (body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
const record = await prisma.$transaction(async (tx) => {
return await tx.service.update({
include: {
createdBy: true,
updatedBy: true,
},
data: {
...payload,
statusOrder: +(payload.status === "INACTIVE"),
work: {
deleteMany: {},
create: (work || []).map((w, wIdx) => ({
name: w.name,
order: wIdx + 1,
attributes: w.attributes,
productOnWork: {
create: w.productId.map((p, pIdx) => ({
productId: p,
order: pIdx + 1,
})),
},
})),
},
updatedByUserId: req.user.sub,
},
where: { id: serviceId },
});
});
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,
),
});
}
@Delete("{serviceId}")
@Security("keycloak", MANAGE_ROLES)
async deleteService(@Request() req: RequestWithUser, @Path() serviceId: string) {
const record = await prisma.service.findFirst({
include: {
registeredBranch: {
where: {
user: { some: { userId: req.user.sub } },
},
},
},
where: { id: serviceId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
}
if (!globalAllow(req.user.roles) && !record.registeredBranch) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (record.status !== Status.CREATED) {
throw new HttpError(HttpStatus.FORBIDDEN, "Service is in used.", "serviceInUsed");
}
return await prisma.service.delete({
include: {
createdBy: true,
updatedBy: true,
},
where: { id: serviceId },
});
}
}