jws-backend/src/controllers/service/service-controller.ts
2024-06-14 17:57:58 +07:00

286 lines
6.8 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;
type ServiceCreate = {
code: "MOU" | "mou";
name: string;
detail: string;
attributes?: {
[key: string]: any;
};
work?: {
name: string;
productId: string[];
attributes?: { [key: string]: any };
}[];
};
type ServiceUpdate = {
name: string;
detail: string;
attributes?: {
[key: string]: any;
};
work?: {
name: string;
productId: string[];
attributes?: { [key: string]: any };
}[];
};
function imageLocation(id: string) {
return `service/${id}/service-image`;
}
@Route("api/v1/service")
@Tags("Service")
@Security("keycloak")
export class ServiceController extends Controller {
@Get("stats")
async getServiceStats() {
return await prisma.service.count();
}
@Get()
async getService(
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
OR: [{ name: { contains: query } }, { detail: { contains: query } }],
} satisfies Prisma.ServiceWhereInput;
const [result, total] = await prisma.$transaction([
prisma.service.findMany({
include: {
work: true,
},
orderBy: { 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}")
async getServiceById(@Path() serviceId: string) {
const record = await prisma.service.findFirst({
include: {
work: {
orderBy: { order: "asc" },
include: {
productOnWork: {
include: { product: true },
orderBy: { order: "asc" },
},
},
},
},
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")
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" },
},
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.work.count({ where }),
]);
return { result, page, pageSize, total };
}
@Post()
async createService(@Request() req: RequestWithUser, @Body() body: ServiceCreate) {
const { work, ...payload } = body;
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" },
},
},
},
},
data: {
...payload,
code: `${body.code.toLocaleUpperCase()}${last.value.toString().padStart(3, "0")}`,
work: {
createMany: {
data:
work?.map((v, i) => ({
...v,
order: i + 1,
})) || [],
},
},
createdBy: req.user.name,
updateBy: req.user.name,
},
});
},
{ 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}")
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, ...payload } = body;
const record = await prisma.service.update({
data: {
...payload,
work: {
deleteMany: {},
createMany: {
data:
work?.map((v, i) => ({
order: i + 1,
...v,
})) || [],
},
},
updateBy: req.user.name,
},
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}")
async deleteService(@Path() serviceId: string) {
const record = await prisma.service.findFirst({ where: { id: serviceId } });
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
}
if (record.status !== Status.CREATED) {
throw new HttpError(HttpStatus.FORBIDDEN, "Service is in used.", "serviceInUsed");
}
return await prisma.service.delete({ where: { id: serviceId } });
}
}