hrms-api-kpi/src/controllers/KpiEvaluationController.ts
2024-04-19 16:19:09 +07:00

101 lines
2.9 KiB
TypeScript

import {
Controller,
Get,
Post,
Put,
Delete,
Route,
Security,
Tags,
Body,
Path,
Request,
Example,
SuccessResponse,
Response,
Query,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpError from "../interfaces/http-error";
import { Like, Not } from "typeorm";
import HttpStatusCode from "../interfaces/http-status";
import { KpiEvaluation, updateKpiEvaluation } from "../entities/kpiEvaluation";
@Route("api/v1/kpi/evaluation")
@Tags("kpiEvaluation")
@Security("bearerAuth")
@Response(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
@SuccessResponse(HttpStatusCode.OK, "สำเร็จ")
export class kpiEvaluationController extends Controller {
private kpiEvaluationRepository = AppDataSource.getRepository(KpiEvaluation);
/**
* API แก้ไขเกณฑ์การประเมิน
* @param id ไอดีของเกณฑ์การประเมิน
*/
@Put()
async updateKpiEvaluations(
@Body() requestBody: updateKpiEvaluation[],
@Request() request: { user: Record<string, any> },
) {
const updatedIds: string[] = [];
for (const item of requestBody) {
const kpiEvaluation = await this.kpiEvaluationRepository.findOne({
where: { id: item.id },
});
if (!kpiEvaluation) {
throw new HttpError(HttpStatusCode.NOT_FOUND, `ไม่พบข้อมูลเกณฑ์การประเมินนี้: ${item.id}`);
}
this.kpiEvaluationRepository.merge(kpiEvaluation, item);
kpiEvaluation.lastUpdateUserId = request.user.sub;
kpiEvaluation.lastUpdateFullName = request.user.name;
await this.kpiEvaluationRepository.save(kpiEvaluation);
updatedIds.push(item.id);
}
return new HttpSuccess();
}
/**
* API list เกณฑ์การประเมิน
* @param page
* @param pageSize
*/
@Get()
async listKpiEvaluation(
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query("keyword") keyword?: string,
) {
let whereClause: any = {};
if (keyword !== undefined && keyword !== "") {
whereClause = {
where: [{ description: Like(`%${keyword}%`) }],
};
whereClause.where.push({ level: Like(`%${keyword}%`) });
}
const [kpiEvaluation, total] = await this.kpiEvaluationRepository.findAndCount({
...whereClause,
...(keyword ? {} : { skip: (page - 1) * pageSize, take: pageSize }),
order:{
level: "DESC"}
});
const formatted = kpiEvaluation.map((item) => ({
id: item.id,
level: item.level,
description: item.description
}));
return new HttpSuccess({ data: formatted, total });
}
}