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

289 lines
6.9 KiB
TypeScript
Raw Normal View History

2024-06-10 17:47:40 +07:00
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";
2024-06-12 16:37:56 +07:00
import minio, { presignedGetObjectIfExist } from "../../services/minio";
2024-06-10 17:47:40 +07:00
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";
2024-06-10 17:47:40 +07:00
name: string;
detail: string;
2024-06-13 15:47:11 +07:00
attributes?: {
[key: string]: any;
};
workId: string[];
2024-06-10 17:47:40 +07:00
};
type ServiceUpdate = {
name: string;
detail: string;
workId: string[];
2024-06-13 15:47:11 +07:00
attributes?: {
[key: string]: any;
};
2024-06-10 17:47:40 +07:00
};
function imageLocation(id: string) {
return `service/${id}/product-image`;
2024-06-10 17:47:40 +07:00
}
2024-06-11 13:35:54 +07:00
@Route("api/v1/service")
2024-06-10 17:47:40 +07:00
@Tags("Service")
@Security("keycloak")
export class ServiceController extends Controller {
2024-06-11 09:31:10 +07:00
@Get("stats")
2024-06-11 09:27:37 +07:00
async getServiceStats() {
return await prisma.service.count();
}
2024-06-10 17:47:40 +07:00
@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: {
workOnService: {
2024-06-13 15:53:39 +07:00
include: { work: true },
},
},
2024-06-10 17:47:40 +07:00
orderBy: { createdAt: "asc" },
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.service.count({ where }),
]);
return {
result: await Promise.all(
result.map(async (v) => ({
...v,
2024-06-12 16:37:56 +07:00
imageUrl: await presignedGetObjectIfExist(
MINIO_BUCKET,
imageLocation(v.id),
12 * 60 * 60,
),
2024-06-10 17:47:40 +07:00
})),
),
page,
pageSize,
total,
};
}
@Get("{serviceId}")
async getServiceById(@Path() serviceId: string) {
const record = await prisma.service.findFirst({
include: {
workOnService: {
orderBy: { order: "asc" },
include: {
work: {
include: {
productOnWork: {
include: {
product: true,
},
orderBy: { order: "asc" },
},
},
},
},
},
},
2024-06-10 17:47:40 +07:00
where: { id: serviceId },
});
if (!record)
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "data_not_found");
return Object.assign(record, {
2024-06-12 16:37:56 +07:00
imageUrl: await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(record.id), 60 * 60),
2024-06-10 17:47:40 +07:00
});
}
@Get("{serviceId}/work")
async getWorkOfService(
@Path() serviceId: string,
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
serviceOnWork: {
some: { serviceId },
},
} satisfies Prisma.WorkWhereInput;
2024-06-10 17:47:40 +07:00
const [result, total] = await prisma.$transaction([
prisma.work.findMany({
include: {
productOnWork: {
include: {
product: true,
},
},
},
where,
2024-06-10 17:47:40 +07:00
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.work.count({ where }),
2024-06-10 17:47:40 +07:00
]);
return { result, page, pageSize, total };
}
@Post()
async createService(@Request() req: RequestWithUser, @Body() body: ServiceCreate) {
const { workId, ...payload } = body;
const workList = await prisma.work.findMany({
where: { id: { in: workId } },
2024-06-10 17:47:40 +07:00
});
if (workList.length !== workList.length) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Some product not found.",
"missing_or_invalid_parameter",
);
}
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: {
workOnService: {
orderBy: { order: "asc" },
include: {
work: {
include: {
productOnWork: {
include: {
product: true,
},
orderBy: { order: "asc" },
},
},
},
},
},
},
data: {
...payload,
code: `${body.code.toLocaleUpperCase()}${last.value.toString().padStart(3, "0")}`,
workOnService: {
createMany: {
data: workId.map((v, i) => ({
order: i + 1,
workId: v,
})),
},
},
createdBy: req.user.name,
updateBy: req.user.name,
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
2024-06-10 17:47:40 +07:00
this.setStatus(HttpStatus.CREATED);
return Object.assign(record, {
2024-06-12 16:37:56 +07:00
imageUrl: await presignedGetObjectIfExist(
2024-06-10 17:47:40 +07:00
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.", "data_not_found");
}
const record = await prisma.service.update({
data: { ...body, updateBy: req.user.name },
where: { id: serviceId },
});
return Object.assign(record, {
2024-06-12 16:37:56 +07:00
imageUrl: await presignedGetObjectIfExist(
2024-06-10 17:47:40 +07:00
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
2024-06-12 16:37:56 +07:00
imageUploadUrl: await minio.presignedPutObject(
2024-06-10 17:47:40 +07:00
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.", "data_not_found");
}
if (record.status !== Status.CREATED) {
throw new HttpError(HttpStatus.FORBIDDEN, "Service is in used.", "data_in_used");
}
return await prisma.service.delete({ where: { id: serviceId } });
}
}