diff --git a/src/app.ts b/src/app.ts index 95d3219..99eb1fb 100644 --- a/src/app.ts +++ b/src/app.ts @@ -85,10 +85,7 @@ async function main() { console.log( `[APP] Application is running on: http://localhost:${APP_PORT}` ), - console.log(`[APP] Swagger on: http://localhost:${APP_PORT}/api-docs`), - console.log( - `[WS] WebSocket Server is running on ws://localhost:${APP_PORT}` - ) + console.log(`[APP] Swagger on: http://localhost:${APP_PORT}/api-docs`) ) ); } diff --git a/src/controllers/AppointController.ts b/src/controllers/AppointController.ts index 658f874..6bb8256 100644 --- a/src/controllers/AppointController.ts +++ b/src/controllers/AppointController.ts @@ -22,7 +22,12 @@ import HttpStatusCode from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; import permission from "../interfaces/permission"; import { RequestWithUser } from "../middlewares/user"; -import { Appoint, CreateAppoint, Person, UpdateAppoint } from "../entities/Appoint"; +import { + Appoint, + CreateAppoint, + Person, + UpdateAppoint, +} from "../entities/Appoint"; import { AppointDirector } from "../entities/AppointDirector"; import CallAPI from "../interfaces/call-api"; @@ -31,11 +36,12 @@ import CallAPI from "../interfaces/call-api"; @Security("bearerAuth") @Response( HttpStatusCode.INTERNAL_SERVER_ERROR, - "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง", + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง" ) export class AppointController extends Controller { private appointRepository = AppDataSource.getRepository(Appoint); - private appointDirectorRepository = AppDataSource.getRepository(AppointDirector); + private appointDirectorRepository = + AppDataSource.getRepository(AppointDirector); /** * API รายการแต่งตั้งคณะกรรมการฯ ทดลองงาน @@ -48,8 +54,21 @@ export class AppointController extends Controller { @Query() keyword: string = "", @Query("page") page: number = 1, @Query("pageSize") pageSize: number = 10, - @Request() request: RequestWithUser, + @Request() request: RequestWithUser ) { + try { + const appoint = await this.appointRepository.find({ + relations: ["personal", "directors"], + where: { createdUserId: request.user.sub }, + // where: { personal: conditions }, + }); + + return new HttpSuccess(appoint); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } // await new permission().PermissionList(request, "SYS_PROBATION") // const _data = await new permission().PermissionOrgList(request, "SYS_PROBATION") @@ -74,14 +93,6 @@ export class AppointController extends Controller { // if (_data.child4 != undefined && _data.child4 != null && _data.child4[0] != null) { // conditions.child4 = _data.child4 // } - - const appoint = await this.appointRepository.find({ - relations: ["personal", "directors"], - where: { createdUserId: request.user.sub }, - // where: { personal: conditions }, - }); - - return new HttpSuccess(appoint); } /** @@ -91,13 +102,22 @@ export class AppointController extends Controller { * */ @Get("list/{id}") - async GetListCommand(@Request() request: RequestWithUser, @Path() id: string) { - const appoint = await this.appointRepository.find({ - relations: ["directors"], - where: { profileId: id, status: "DONE" }, - }); + async GetListCommand( + @Request() request: RequestWithUser, + @Path() id: string + ) { + try { + const appoint = await this.appointRepository.find({ + relations: ["directors"], + where: { profileId: id, status: "DONE" }, + }); - return new HttpSuccess(appoint); + return new HttpSuccess(appoint); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -107,20 +127,31 @@ export class AppointController extends Controller { * */ @Post("") - async Create(@Request() request: RequestWithUser, @Body() requestBody: CreateAppoint) { - await new permission().PermissionCreate(request, "SYS_PROBATION"); + async Create( + @Request() request: RequestWithUser, + @Body() requestBody: CreateAppoint + ) { + try { + await new permission().PermissionCreate(request, "SYS_PROBATION"); - const data: any = { - topic: requestBody.topic, - profileId: requestBody.profileId, - createdUserId: request.user.sub, - createdFullName: request.user.name, - }; - const before = null; - const appoint = await this.appointRepository.save(data, { data: request }); - setLogDataDiff(request, { before, after: appoint }); + const data: any = { + topic: requestBody.topic, + profileId: requestBody.profileId, + createdUserId: request.user.sub, + createdFullName: request.user.name, + }; + const before = null; + const appoint = await this.appointRepository.save(data, { + data: request, + }); + setLogDataDiff(request, { before, after: appoint }); - return new HttpSuccess(appoint.id); + return new HttpSuccess(appoint.id); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -131,16 +162,27 @@ export class AppointController extends Controller { */ @Get("{id}") async GetById(@Request() request: RequestWithUser, @Path() id: string) { - let _workflow = await new permission().Workflow(request, id, "SYS_PROBATION"); - if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION"); + try { + let _workflow = await new permission().Workflow( + request, + id, + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); - const appoint = await this.appointRepository.findOne({ - select: ["id", "topic", "status", "profileId"], - where: { id }, - relations: ["directors"], - }); + const appoint = await this.appointRepository.findOne({ + select: ["id", "topic", "status", "profileId"], + where: { id }, + relations: ["directors"], + }); - return new HttpSuccess(appoint); + return new HttpSuccess(appoint); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -153,38 +195,47 @@ export class AppointController extends Controller { async Update( @Request() request: RequestWithUser, @Body() requestBody: UpdateAppoint, - @Path() id: string, + @Path() id: string ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION"); + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - const appoint: any = await this.appointRepository.findOne({ - where: { id }, - }); + const appoint: any = await this.appointRepository.findOne({ + where: { id }, + }); - if (!appoint) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการแต่งตั้งคณะกรรมการฯ"); + if (!appoint) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลการแต่งตั้งคณะกรรมการฯ" + ); + } + + const before = appoint; + + appoint.topic = requestBody.topic; + appoint.updateUserId = request.user.sub; + appoint.updateFullName = request.user.name; + await this.appointDirectorRepository.delete({ appointId: id }); + const directors: any = await requestBody.persons.map((x: Person) => ({ + ...x, + appointId: id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + })); + await this.appointDirectorRepository.save(directors); + + await this.appointRepository.save(appoint, { data: request }); + setLogDataDiff(request, { before, after: appoint }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const before = appoint; - - appoint.topic = requestBody.topic; - appoint.updateUserId = request.user.sub; - appoint.updateFullName = request.user.name; - await this.appointDirectorRepository.delete({ appointId: id }); - const directors: any = await requestBody.persons.map((x: Person) => ({ - ...x, - appointId: id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - })); - await this.appointDirectorRepository.save(directors); - - await this.appointRepository.save(appoint, { data: request }); - setLogDataDiff(request, { before, after: appoint }); - - return new HttpSuccess(); } /** @@ -194,15 +245,24 @@ export class AppointController extends Controller { * */ @Delete("{id}") - public async deleteRole(@Path() id: string, @Request() request: RequestWithUser) { - await new permission().PermissionDelete(request, "SYS_PROBATION"); + public async deleteRole( + @Path() id: string, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionDelete(request, "SYS_PROBATION"); - await this.appointDirectorRepository.delete({ appointId: id }); + await this.appointDirectorRepository.delete({ appointId: id }); - const result = await this.appointRepository.delete({ id }); - if (!result) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + const result = await this.appointRepository.delete({ id }); + if (!result) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - return new HttpSuccess(); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -212,28 +272,37 @@ export class AppointController extends Controller { * */ @Get("/committee/{profileId}") - async GetCheckById(@Request() request: RequestWithUser, @Path() profileId: string) { - await new permission().PermissionGet(request, "SYS_PROBATION"); + async GetCheckById( + @Request() request: RequestWithUser, + @Path() profileId: string + ) { + try { + await new permission().PermissionGet(request, "SYS_PROBATION"); - const directorId = await new CallAPI() - .GetData(request, "/org/profile/keycloak") - .catch((error) => { - console.error("Error calling API:", error); - }); + const directorId = await new CallAPI() + .GetData(request, "/org/profile/keycloak") + .catch((error) => { + console.error("Error calling API:", error); + }); - const appoint = await AppDataSource.getRepository(Appoint) - .createQueryBuilder("appoint") - .leftJoinAndSelect("appoint.directors", "directors") - .where( - "appoint.profileId = :profileId and directors.profileId = :directorId and directors.role = 'committee'", - { - directorId, - profileId, - }, - ) - .orderBy("appoint.createdAt", "DESC") - .getOne(); - const check = appoint ? true : false; - return new HttpSuccess(check); + const appoint = await AppDataSource.getRepository(Appoint) + .createQueryBuilder("appoint") + .leftJoinAndSelect("appoint.directors", "directors") + .where( + "appoint.profileId = :profileId and directors.profileId = :directorId and directors.role = 'committee'", + { + directorId, + profileId, + } + ) + .orderBy("appoint.createdAt", "DESC") + .getOne(); + const check = appoint ? true : false; + return new HttpSuccess(check); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } } diff --git a/src/controllers/AssignController.ts b/src/controllers/AssignController.ts index 9a34fa3..d2d9e26 100644 --- a/src/controllers/AssignController.ts +++ b/src/controllers/AssignController.ts @@ -91,160 +91,168 @@ export class AssignController extends Controller { @Request() request: RequestWithUser, @Body() requestBody: CreateAssign ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION"); - const person = await this.personalRepository.findOne({ - where: { - personal_id: requestBody.personalId, - }, - }); + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); + const person = await this.personalRepository.findOne({ + where: { + personal_id: requestBody.personalId, + }, + }); - if (!person) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + if (!person) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + const roundNo = await this.assignRepository.count({ + where: { + active: 1, + personal_id: requestBody.personalId, + }, + }); + + const data: any = { + ...requestBody, + round_no: roundNo + 1, + personal_id: requestBody.personalId, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + other4_desc: requestBody.other4_desc ?? "", + other5_no1_desc: requestBody.other5_no1_desc ?? "", + other_desc: requestBody.other_desc ?? "", + }; + const before = null; + const assign = await this.assignRepository.save(data, { data: request }); + setLogDataDiff(request, { before, after: data }); + + const jobs = await requestBody.assign_jobs.map( + (x: CreateAssignJob, index: number) => ({ + ...x, + id: index + 1, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignJobRepository.save(jobs, { data: request }); + setLogDataDiff(request, { before, after: jobs }); + + const knowledges = await requestBody.assign_knowledges.map( + (x: CreateAssignKnowledge, index: number) => ({ + knowledge_level: x.level, + knowledge_id: x.id, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignKnowledgeRepository.save(knowledges, { data: request }); + setLogDataDiff(request, { before, after: knowledges }); + + const laws = await requestBody.assign_law.map( + (x: CreateAssignLaw, index: number) => ({ + ordering: index + 1, + law_id: x.id, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignLawRepository.save(laws, { data: request }); + setLogDataDiff(request, { before, after: laws }); + + const skills = await requestBody.assign_skill.map( + (x: CreateAssignSkill, index: number) => ({ + skill_id: index + 1, + skill_level: x.level, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignSkillRepository.save(skills, { data: request }); + setLogDataDiff(request, { before, after: skills }); + + const competencise = await requestBody.assign_competency.map( + (x: CreateAssignCompetency, index: number) => ({ + competency_id: x.id, + competency_level: x.level, + competency_name: x.name, + competency_description: x.description, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignCompetencyRepository.save(competencise, { + data: request, + }); + setLogDataDiff(request, { before, after: competencise }); + + const competencyGroups = await requestBody.assign_competency_group.map( + (x: CreateAssignCompetencyGroup, index: number) => ({ + competency_group_id: x.id, + competency_group_level: x.level, + competency_group_name: x.name, + competency_group_description: x.description, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignCompetencyGroupRepository.save(competencyGroups, { + data: request, + }); + setLogDataDiff(request, { before, after: competencyGroups }); + + const outputs = await requestBody.assign_outputs.map( + (x: CreateAssignOutput, index: number) => ({ + ...x, + id: index + 1, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignOutputRepository.save(outputs, { data: request }); + setLogDataDiff(request, { before, after: outputs }); + + const directors = await requestBody.assign_director.map( + (x: CreateAssignDirector, index: number) => ({ + ...x, + assign_id: assign.id, + fullname: x.name, + ordering: index + 1, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignDirectorRepository.save(directors, { data: request }); + setLogDataDiff(request, { before, after: directors }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const roundNo = await this.assignRepository.count({ - where: { - active: 1, - personal_id: requestBody.personalId, - }, - }); - - const data: any = { - ...requestBody, - round_no: roundNo + 1, - personal_id: requestBody.personalId, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - other4_desc: requestBody.other4_desc ?? "", - other5_no1_desc: requestBody.other5_no1_desc ?? "", - other_desc: requestBody.other_desc ?? "", - }; - const before = null; - const assign = await this.assignRepository.save(data, { data: request }); - setLogDataDiff(request, { before, after: data }); - - const jobs = await requestBody.assign_jobs.map( - (x: CreateAssignJob, index: number) => ({ - ...x, - id: index + 1, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignJobRepository.save(jobs, { data: request }); - setLogDataDiff(request, { before, after: jobs }); - - const knowledges = await requestBody.assign_knowledges.map( - (x: CreateAssignKnowledge, index: number) => ({ - knowledge_level: x.level, - knowledge_id: x.id, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignKnowledgeRepository.save(knowledges, { data: request }); - setLogDataDiff(request, { before, after: knowledges }); - - const laws = await requestBody.assign_law.map( - (x: CreateAssignLaw, index: number) => ({ - ordering: index + 1, - law_id: x.id, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignLawRepository.save(laws, { data: request }); - setLogDataDiff(request, { before, after: laws }); - - const skills = await requestBody.assign_skill.map( - (x: CreateAssignSkill, index: number) => ({ - skill_id: index + 1, - skill_level: x.level, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignSkillRepository.save(skills, { data: request }); - setLogDataDiff(request, { before, after: skills }); - - const competencise = await requestBody.assign_competency.map( - (x: CreateAssignCompetency, index: number) => ({ - competency_id: x.id, - competency_level: x.level, - competency_name: x.name, - competency_description: x.description, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignCompetencyRepository.save(competencise, { data: request }); - setLogDataDiff(request, { before, after: competencise }); - - const competencyGroups = await requestBody.assign_competency_group.map( - (x: CreateAssignCompetencyGroup, index: number) => ({ - competency_group_id: x.id, - competency_group_level: x.level, - competency_group_name: x.name, - competency_group_description: x.description, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignCompetencyGroupRepository.save(competencyGroups, { - data: request, - }); - setLogDataDiff(request, { before, after: competencyGroups }); - - const outputs = await requestBody.assign_outputs.map( - (x: CreateAssignOutput, index: number) => ({ - ...x, - id: index + 1, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignOutputRepository.save(outputs, { data: request }); - setLogDataDiff(request, { before, after: outputs }); - - const directors = await requestBody.assign_director.map( - (x: CreateAssignDirector, index: number) => ({ - ...x, - assign_id: assign.id, - fullname: x.name, - ordering: index + 1, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignDirectorRepository.save(directors, { data: request }); - setLogDataDiff(request, { before, after: directors }); - - return new HttpSuccess(); } /** @@ -259,220 +267,229 @@ export class AssignController extends Controller { @Request() request: RequestWithUser, @Body() requestBody: CreateAssign ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION"); + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - const assign = await this.assignRepository.findOne({ - where: { id: assign_id }, - }); - let before = assign; + const assign = await this.assignRepository.findOne({ + where: { id: assign_id }, + }); + let before = assign; - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const person = await this.personalRepository.findOne({ + where: { + personal_id: requestBody.personalId, + }, + }); + + if (!person) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + const data: any = { + ...requestBody, + id: assign_id, + updateUserId: request.user.sub, + updateFullName: request.user.name, + other4_desc: requestBody.other4_desc ?? "", + other5_no1_desc: requestBody.other5_no1_desc ?? "", + other_desc: requestBody.other_desc ?? "", + }; + + await this.assignJobRepository.delete({ assign_id }); + const jobs = await requestBody.assign_jobs.map( + (x: CreateAssignJob, index: number) => ({ + ...x, + id: index + 1, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignJobRepository.save(jobs); + + await this.assignKnowledgeRepository.delete({ assign_id }); + const knowledges = await requestBody.assign_knowledges.map( + (x: CreateAssignKnowledge, index: number) => ({ + knowledge_level: x.level, + knowledge_id: x.id, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignKnowledgeRepository.save(knowledges); + + await this.assignLawRepository.delete({ assign_id }); + const laws = await requestBody.assign_law.map( + (x: CreateAssignLaw, index: number) => ({ + ordering: index + 1, + law_id: x.id, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignLawRepository.save(laws); + + await this.assignSkillRepository.delete({ assign_id }); + const skills = await requestBody.assign_skill.map( + (x: CreateAssignSkill, index: number) => ({ + skill_id: index + 1, + skill_level: x.level, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignSkillRepository.save(skills); + + await this.assignCompetencyRepository.delete({ assign_id }); + const competencise = await requestBody.assign_competency.map( + (x: CreateAssignCompetency, index: number) => ({ + competency_id: x.id, + competency_level: x.level, + competency_name: x.name, + competency_description: x.description, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignCompetencyRepository.save(competencise); + + await this.assignCompetencyGroupRepository.delete({ assign_id }); + const competencyGroups = await requestBody.assign_competency_group.map( + (x: CreateAssignCompetencyGroup, index: number) => ({ + competency_group_id: x.id, + competency_group_level: x.level, + competency_group_name: x.name, + competency_group_description: x.description, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignCompetencyGroupRepository.save(competencyGroups); + + await this.assignOutputRepository.delete({ assign_id }); + const outputs = await requestBody.assign_outputs.map( + (x: CreateAssignOutput, index: number) => ({ + ...x, + id: index + 1, + assign_id: assign.id, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignOutputRepository.save(outputs); + + await this.assignDirectorRepository.delete({ assign_id }); + const directors = await requestBody.assign_director.map( + (x: CreateAssignDirector, index: number) => ({ + ...x, + assign_id: assign.id, + fullname: x.name, + ordering: index + 1, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }) + ); + await this.assignDirectorRepository.save(directors); + + await this.assignRepository.save(data, { data: request }); + setLogDataDiff(request, { before, after: data }); + + // #noted cronjob + // แจ้งผู้ดูแลและผู้บังคับบัญชาเข้ามาบันทึกผลทุก 2 เดือน + const dateSaveForm = await findEndDate(2, requestBody.date_start); + requestBody.assign_director + .filter((x) => x.role == "mentor" || x.role == "commander") + .map(async (director) => { + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ 1 ${requestBody.fullname}`, + body: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ 1 ${requestBody.fullname}`, + receiverUserId: director.personal_id, + payload: "", + isSendMail: true, + isSendInbox: true, + receiveDate: dateSaveForm, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + }); + + // แจ้งผู้บังคับบัญชา และคณะกรรมการเข้ามาประเมินทุก 3 เดือน + const dateEvaluate = await findEndDate(3, requestBody.date_start); + requestBody.assign_director + .filter((x) => x.role == "commander" || x.role == "chairman") + .map(async (director) => { + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ 1 ${requestBody.fullname}`, + body: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ 1 ${requestBody.fullname}`, + receiverUserId: director.personal_id, + payload: "", + isSendMail: true, + isSendInbox: true, + receiveDate: dateEvaluate, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + }); + + // แจ้งประธาน 6 เดือน + const dateResult = await findEndDate(6, requestBody.date_start); + requestBody.assign_director + .filter((x) => x.role == "chairman") + .map(async (director) => { + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: `ถึงกำหนดรายงานการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ ${requestBody.fullname}`, + body: `ถึงกำหนดรายงานการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ ${requestBody.fullname}`, + receiverUserId: director.personal_id, + payload: "", + isSendMail: true, + isSendInbox: true, + // isSendNotification: true + receiveDate: dateResult, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const person = await this.personalRepository.findOne({ - where: { - personal_id: requestBody.personalId, - }, - }); - - if (!person) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); - } - - const data: any = { - ...requestBody, - id: assign_id, - updateUserId: request.user.sub, - updateFullName: request.user.name, - other4_desc: requestBody.other4_desc ?? "", - other5_no1_desc: requestBody.other5_no1_desc ?? "", - other_desc: requestBody.other_desc ?? "", - }; - - await this.assignJobRepository.delete({ assign_id }); - const jobs = await requestBody.assign_jobs.map( - (x: CreateAssignJob, index: number) => ({ - ...x, - id: index + 1, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignJobRepository.save(jobs); - - await this.assignKnowledgeRepository.delete({ assign_id }); - const knowledges = await requestBody.assign_knowledges.map( - (x: CreateAssignKnowledge, index: number) => ({ - knowledge_level: x.level, - knowledge_id: x.id, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignKnowledgeRepository.save(knowledges); - - await this.assignLawRepository.delete({ assign_id }); - const laws = await requestBody.assign_law.map( - (x: CreateAssignLaw, index: number) => ({ - ordering: index + 1, - law_id: x.id, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignLawRepository.save(laws); - - await this.assignSkillRepository.delete({ assign_id }); - const skills = await requestBody.assign_skill.map( - (x: CreateAssignSkill, index: number) => ({ - skill_id: index + 1, - skill_level: x.level, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignSkillRepository.save(skills); - - await this.assignCompetencyRepository.delete({ assign_id }); - const competencise = await requestBody.assign_competency.map( - (x: CreateAssignCompetency, index: number) => ({ - competency_id: x.id, - competency_level: x.level, - competency_name: x.name, - competency_description: x.description, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignCompetencyRepository.save(competencise); - - await this.assignCompetencyGroupRepository.delete({ assign_id }); - const competencyGroups = await requestBody.assign_competency_group.map( - (x: CreateAssignCompetencyGroup, index: number) => ({ - competency_group_id: x.id, - competency_group_level: x.level, - competency_group_name: x.name, - competency_group_description: x.description, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignCompetencyGroupRepository.save(competencyGroups); - - await this.assignOutputRepository.delete({ assign_id }); - const outputs = await requestBody.assign_outputs.map( - (x: CreateAssignOutput, index: number) => ({ - ...x, - id: index + 1, - assign_id: assign.id, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignOutputRepository.save(outputs); - - await this.assignDirectorRepository.delete({ assign_id }); - const directors = await requestBody.assign_director.map( - (x: CreateAssignDirector, index: number) => ({ - ...x, - assign_id: assign.id, - fullname: x.name, - ordering: index + 1, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }) - ); - await this.assignDirectorRepository.save(directors); - - await this.assignRepository.save(data, { data: request }); - setLogDataDiff(request, { before, after: data }); - - // #noted cronjob - // แจ้งผู้ดูแลและผู้บังคับบัญชาเข้ามาบันทึกผลทุก 2 เดือน - const dateSaveForm = await findEndDate(2, requestBody.date_start); - requestBody.assign_director - .filter((x) => x.role == "mentor" || x.role == "commander") - .map(async (director) => { - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ 1 ${requestBody.fullname}`, - body: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ 1 ${requestBody.fullname}`, - receiverUserId: director.personal_id, - payload: "", - isSendMail: true, - isSendInbox: true, - receiveDate: dateSaveForm, - }) - .catch((error) => { - console.error("Error calling API:", error); - }); - }); - - // แจ้งผู้บังคับบัญชา และคณะกรรมการเข้ามาประเมินทุก 3 เดือน - const dateEvaluate = await findEndDate(3, requestBody.date_start); - requestBody.assign_director - .filter((x) => x.role == "commander" || x.role == "chairman") - .map(async (director) => { - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ 1 ${requestBody.fullname}`, - body: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ 1 ${requestBody.fullname}`, - receiverUserId: director.personal_id, - payload: "", - isSendMail: true, - isSendInbox: true, - receiveDate: dateEvaluate, - }) - .catch((error) => { - console.error("Error calling API:", error); - }); - }); - - // แจ้งประธาน 6 เดือน - const dateResult = await findEndDate(6, requestBody.date_start); - requestBody.assign_director - .filter((x) => x.role == "chairman") - .map(async (director) => { - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: `ถึงกำหนดรายงานการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ ${requestBody.fullname}`, - body: `ถึงกำหนดรายงานการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ ${requestBody.fullname}`, - receiverUserId: director.personal_id, - payload: "", - isSendMail: true, - isSendInbox: true, - // isSendNotification: true - receiveDate: dateResult, - }) - .catch((error) => { - console.error("Error calling API:", error); - }); - }); - - return new HttpSuccess(); } /** @@ -486,60 +503,66 @@ export class AssignController extends Controller { @Request() request: RequestWithUser, @Query() personal_id: string ) { - let _workflow = await new permission().Workflow( - request, - personal_id, - "SYS_PROBATION" - ); - if (_workflow == false) - await new permission().PermissionGet(request, "SYS_PROBATION"); - const lists = await this.assignRepository.find({ - select: ["id", "round_no", "date_start", "date_finish"], - where: { personal_id }, - order: { round_no: "ASC" }, - }); + try { + let _workflow = await new permission().Workflow( + request, + personal_id, + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); + const lists = await this.assignRepository.find({ + select: ["id", "round_no", "date_start", "date_finish"], + where: { personal_id }, + order: { round_no: "ASC" }, + }); - let result: any = []; + let result: any = []; - await Promise.all( - lists.map(async (item) => { - const director = await this.assignDirectorRepository.find({ - where: { assign_id: item.id }, - order: { ordering: "ASC" }, - }); + await Promise.all( + lists.map(async (item) => { + const director = await this.assignDirectorRepository.find({ + where: { assign_id: item.id }, + order: { ordering: "ASC" }, + }); - let mentors = ""; - const mentorList = await director.filter((x) => x.role == "mentor"); - if (mentorList.length > 0) { - for (let index = 0; index < mentorList.length; index++) { - const e = await mentorList[index]; - mentors += e.fullname; - if (index < mentorList.length - 1) { - mentors += ", "; + let mentors = ""; + const mentorList = await director.filter((x) => x.role == "mentor"); + if (mentorList.length > 0) { + for (let index = 0; index < mentorList.length; index++) { + const e = await mentorList[index]; + mentors += e.fullname; + if (index < mentorList.length - 1) { + mentors += ", "; + } } } - } - const commanderData = await (director.find( - (x) => x.role == "commander" - ) ?? null); - const commander = commanderData ? commanderData.fullname : null; + const commanderData = await (director.find( + (x) => x.role == "commander" + ) ?? null); + const commander = commanderData ? commanderData.fullname : null; - const chairmanData = await (director.find( - (x) => x.role == "chairman" - ) ?? null); - const chairman = chairmanData ? chairmanData.fullname : null; + const chairmanData = await (director.find( + (x) => x.role == "chairman" + ) ?? null); + const chairman = chairmanData ? chairmanData.fullname : null; - await result.push({ - ...item, - mentors: mentors, - commander: commander, - chairman: chairman, - }); - }) - ); + await result.push({ + ...item, + mentors: mentors, + commander: commander, + chairman: chairman, + }); + }) + ); - return new HttpSuccess(result); + return new HttpSuccess(result); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -553,53 +576,59 @@ export class AssignController extends Controller { @Request() request: RequestWithUser, @Query() personal_id: string ) { - const lists = await this.assignRepository.find({ - select: ["id", "round_no", "date_start", "date_finish"], - where: { personal_id }, - order: { round_no: "ASC" }, - }); + try { + const lists = await this.assignRepository.find({ + select: ["id", "round_no", "date_start", "date_finish"], + where: { personal_id }, + order: { round_no: "ASC" }, + }); - let result: any = []; + let result: any = []; - await Promise.all( - lists.map(async (item) => { - const director = await this.assignDirectorRepository.find({ - where: { assign_id: item.id }, - order: { ordering: "ASC" }, - }); + await Promise.all( + lists.map(async (item) => { + const director = await this.assignDirectorRepository.find({ + where: { assign_id: item.id }, + order: { ordering: "ASC" }, + }); - let mentors = ""; - const mentorList = await director.filter((x) => x.role == "mentor"); - if (mentorList.length > 0) { - for (let index = 0; index < mentorList.length; index++) { - const e = await mentorList[index]; - mentors += e.fullname; - if (index < mentorList.length - 1) { - mentors += ", "; + let mentors = ""; + const mentorList = await director.filter((x) => x.role == "mentor"); + if (mentorList.length > 0) { + for (let index = 0; index < mentorList.length; index++) { + const e = await mentorList[index]; + mentors += e.fullname; + if (index < mentorList.length - 1) { + mentors += ", "; + } } } - } - const commanderData = await (director.find( - (x) => x.role == "commander" - ) ?? null); - const commander = commanderData ? commanderData.fullname : null; + const commanderData = await (director.find( + (x) => x.role == "commander" + ) ?? null); + const commander = commanderData ? commanderData.fullname : null; - const chairmanData = await (director.find( - (x) => x.role == "chairman" - ) ?? null); - const chairman = chairmanData ? chairmanData.fullname : null; + const chairmanData = await (director.find( + (x) => x.role == "chairman" + ) ?? null); + const chairman = chairmanData ? chairmanData.fullname : null; - await result.push({ - ...item, - mentors: mentors, - commander: commander, - chairman: chairman, - }); - }) - ); + await result.push({ + ...item, + mentors: mentors, + commander: commander, + chairman: chairman, + }); + }) + ); - return new HttpSuccess(result); + return new HttpSuccess(result); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -614,259 +643,268 @@ export class AssignController extends Controller { @Query() isReport: boolean = false, @Request() request: RequestWithUser ) { - let _workflow = await new permission().Workflow( - request, - assign_id, - "SYS_PROBATION" - ); - if (_workflow == false) - await new permission().PermissionGet(request, "SYS_PROBATION"); + try { + let _workflow = await new permission().Workflow( + request, + assign_id, + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); - const assign = await this.assignRepository.findOne({ - select: [ - "id", - "personal_id", - "appointId", - "round_no", - "date_start", - "date_finish", - "other_desc", - "other4_desc", - "other5_no1_desc", - "experimenter_dated", - "active", - "createdAt", - "updatedAt", - "reportPersonId", - ], - where: { id: assign_id }, - }); - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - - const profileData = await this.personalRepository.findOne({ - select: [ - "personal_id", - "prefixName", - "firstName", - "lastName", - "positionName", - "positionLevelName", - "positionLineName", - "orgRootName", - "organization", - ], - where: { - personal_id: assign.personal_id, - }, - }); - - if (!profileData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); - } - - const splitOc = await profileData.organization.split(" "); - const splitOcAmount = await splitOc.length; - const profile = { - ...profileData, - name: `${profileData.prefixName}${profileData.firstName} ${profileData.lastName}`, - Position: profileData.positionName, - Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", - OrganizationOrganization: - splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", - Oc: profileData.orgRootName, - PositionAndLevel: - profileData.positionName + profileData.positionLevelName, - }; - - const jobs = await this.assignJobRepository.find({ - select: ["id", "activity_desc", "goal_desc"], - where: { assign_id }, - }); - - const knowledgeData = await this.assignKnowledgeRepository.find({ - relations: ["knowledge"], - where: { assign_id }, - }); - const knowledges = await knowledgeData.map((x) => ({ - id: x.knowledge_id, - level: x.knowledge_level, - title: x.knowledge.title, - description: - x.knowledge_level == 1 - ? x.knowledge.level1 - : x.knowledge_level == 2 - ? x.knowledge.level2 - : x.knowledge_level == 3 - ? x.knowledge.level3 - : x.knowledge_level == 4 - ? x.knowledge.level4 - : x.knowledge_level == 5 - ? x.knowledge.level5 - : "", - })); - - const lawData = await this.lawsRepository.find({ - where: { active: 1 }, - }); - - const laws = await Promise.all( - lawData.map(async (x) => { - const assignLaw = await this.assignLawRepository.countBy({ - assign_id: assign_id, - law_id: x.id, - }); - - let description = await x.description; - if (isReport) { - const descriptionSplit = await x.description.split(" "); - description = await x.description.replace(descriptionSplit[0], ""); - } - - return { - id: x.id, - selected: assignLaw > 0 ? 1 : 0, - description: description, - status_select: x.status_select, - }; - }) - ); - - const skillsData = await this.assignSkillRepository.find({ - relations: ["skill"], - where: { assign_id }, - }); - - const skills = await skillsData.map((x) => ({ - id: x.skill_id, - level: x.skill_level, - title: x.skill.title, - description: - x.skill_level == 1 - ? x.skill.level1 - : x.skill_level == 2 - ? x.skill.level2 - : x.skill_level == 3 - ? x.skill.level3 - : x.skill_level == 4 - ? x.skill.level4 - : x.skill_level == 5 - ? x.skill.level5 - : "", - })); - - const competencyData = await this.assignCompetencyRepository.find({ - select: [ - "competency_id", - "competency_level", - "competency_name", - "competency_description", - ], - where: { assign_id }, - order: { createdAt: "ASC" }, - }); - - const competencys = await competencyData.map((x) => ({ - id: x.competency_id, - level: x.competency_level, - name: x.competency_name, - description: x.competency_description, - })); - - const competencyGroupData = await this.assignCompetencyGroupRepository.find( - { + const assign = await this.assignRepository.findOne({ select: [ - "competency_group_id", - "competency_group_level", - "competency_group_name", - "competency_group_description", + "id", + "personal_id", + "appointId", + "round_no", + "date_start", + "date_finish", + "other_desc", + "other4_desc", + "other5_no1_desc", + "experimenter_dated", + "active", + "createdAt", + "updatedAt", + "reportPersonId", + ], + where: { id: assign_id }, + }); + + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const profileData = await this.personalRepository.findOne({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "positionLineName", + "orgRootName", + "organization", + ], + where: { + personal_id: assign.personal_id, + }, + }); + + if (!profileData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + const splitOc = await profileData.organization.split(" "); + const splitOcAmount = await splitOc.length; + const profile = { + ...profileData, + name: `${profileData.prefixName}${profileData.firstName} ${profileData.lastName}`, + Position: profileData.positionName, + Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", + OrganizationOrganization: + splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", + Oc: profileData.orgRootName, + PositionAndLevel: + profileData.positionName + profileData.positionLevelName, + }; + + const jobs = await this.assignJobRepository.find({ + select: ["id", "activity_desc", "goal_desc"], + where: { assign_id }, + }); + + const knowledgeData = await this.assignKnowledgeRepository.find({ + relations: ["knowledge"], + where: { assign_id }, + }); + const knowledges = await knowledgeData.map((x) => ({ + id: x.knowledge_id, + level: x.knowledge_level, + title: x.knowledge.title, + description: + x.knowledge_level == 1 + ? x.knowledge.level1 + : x.knowledge_level == 2 + ? x.knowledge.level2 + : x.knowledge_level == 3 + ? x.knowledge.level3 + : x.knowledge_level == 4 + ? x.knowledge.level4 + : x.knowledge_level == 5 + ? x.knowledge.level5 + : "", + })); + + const lawData = await this.lawsRepository.find({ + where: { active: 1 }, + }); + + const laws = await Promise.all( + lawData.map(async (x) => { + const assignLaw = await this.assignLawRepository.countBy({ + assign_id: assign_id, + law_id: x.id, + }); + + let description = await x.description; + if (isReport) { + const descriptionSplit = await x.description.split(" "); + description = await x.description.replace(descriptionSplit[0], ""); + } + + return { + id: x.id, + selected: assignLaw > 0 ? 1 : 0, + description: description, + status_select: x.status_select, + }; + }) + ); + + const skillsData = await this.assignSkillRepository.find({ + relations: ["skill"], + where: { assign_id }, + }); + + const skills = await skillsData.map((x) => ({ + id: x.skill_id, + level: x.skill_level, + title: x.skill.title, + description: + x.skill_level == 1 + ? x.skill.level1 + : x.skill_level == 2 + ? x.skill.level2 + : x.skill_level == 3 + ? x.skill.level3 + : x.skill_level == 4 + ? x.skill.level4 + : x.skill_level == 5 + ? x.skill.level5 + : "", + })); + + const competencyData = await this.assignCompetencyRepository.find({ + select: [ + "competency_id", + "competency_level", + "competency_name", + "competency_description", ], where: { assign_id }, order: { createdAt: "ASC" }, - } - ); - const competency_groups = await competencyGroupData.map((x) => ({ - id: x.competency_group_id, - level: x.competency_group_level, - name: x.competency_group_name, - description: x.competency_group_description, - })); + }); - const outputs = await this.assignOutputRepository.find({ - select: ["id", "output_desc", "indicator_desc"], - where: { assign_id }, - }); + const competencys = await competencyData.map((x) => ({ + id: x.competency_id, + level: x.competency_level, + name: x.competency_name, + description: x.competency_description, + })); - const director = await this.assignDirectorRepository.find({ - where: { assign_id }, - order: { ordering: "ASC" }, - }); - - let mentors = []; - const mentorList = await director.filter((x) => x.role == "mentor"); - if (mentorList.length > 0) { - for (let index = 0; index < mentorList.length; index++) { - const e = await mentorList[index]; - mentors.push({ - ...e, - name: e.fullname, - label: - e.fullname + - " " + - (e.position ? `(${e.position}${e.posLevel})` : ""), - Position: e.position + e.posLevel, // report + const competencyGroupData = + await this.assignCompetencyGroupRepository.find({ + select: [ + "competency_group_id", + "competency_group_level", + "competency_group_name", + "competency_group_description", + ], + where: { assign_id }, + order: { createdAt: "ASC" }, }); + const competency_groups = await competencyGroupData.map((x) => ({ + id: x.competency_group_id, + level: x.competency_group_level, + name: x.competency_group_name, + description: x.competency_group_description, + })); + + const outputs = await this.assignOutputRepository.find({ + select: ["id", "output_desc", "indicator_desc"], + where: { assign_id }, + }); + + const director = await this.assignDirectorRepository.find({ + where: { assign_id }, + order: { ordering: "ASC" }, + }); + + let mentors = []; + const mentorList = await director.filter((x) => x.role == "mentor"); + if (mentorList.length > 0) { + for (let index = 0; index < mentorList.length; index++) { + const e = await mentorList[index]; + mentors.push({ + ...e, + name: e.fullname, + label: + e.fullname + + " " + + (e.position ? `(${e.position}${e.posLevel})` : ""), + Position: e.position + e.posLevel, // report + }); + } } + + const commanderData = await (director.find( + (x) => x.role == "commander" + ) ?? null); + const commander = await (commanderData + ? { + ...commanderData, + name: commanderData.fullname, + label: + commanderData.fullname + + " " + + (commanderData.position + ? `(${commanderData.position}${commanderData.posLevel})` + : ""), + Position: commanderData.position + commanderData.posLevel, // report + } + : null); + + const chairmanData = await (director.find((x) => x.role == "chairman") ?? + null); + const chairman = await (chairmanData + ? { + ...chairmanData, + name: chairmanData.fullname, + label: + chairmanData.fullname + + " " + + (chairmanData.position + ? `(${chairmanData.position}${chairmanData.posLevel})` + : ""), + Position: chairmanData.position + chairmanData.posLevel, // report + } + : null); + + return new HttpSuccess({ + assign, + profile, + jobs, + knowledges, + laws, + skills, + competencys, + competency_groups, + outputs, + mentors, + commander, + chairman, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const commanderData = await (director.find((x) => x.role == "commander") ?? - null); - const commander = await (commanderData - ? { - ...commanderData, - name: commanderData.fullname, - label: - commanderData.fullname + - " " + - (commanderData.position - ? `(${commanderData.position}${commanderData.posLevel})` - : ""), - Position: commanderData.position + commanderData.posLevel, // report - } - : null); - - const chairmanData = await (director.find((x) => x.role == "chairman") ?? - null); - const chairman = await (chairmanData - ? { - ...chairmanData, - name: chairmanData.fullname, - label: - chairmanData.fullname + - " " + - (chairmanData.position - ? `(${chairmanData.position}${chairmanData.posLevel})` - : ""), - Position: chairmanData.position + chairmanData.posLevel, // report - } - : null); - - return new HttpSuccess({ - assign, - profile, - jobs, - knowledges, - laws, - skills, - competencys, - competency_groups, - outputs, - mentors, - commander, - chairman, - }); } /** @@ -881,250 +919,259 @@ export class AssignController extends Controller { @Query() isReport: boolean = false, @Request() request: RequestWithUser ) { - const assign = await this.assignRepository.findOne({ - select: [ - "id", - "personal_id", - "appointId", - "round_no", - "date_start", - "date_finish", - "other_desc", - "other4_desc", - "other5_no1_desc", - "experimenter_dated", - "active", - "createdAt", - "updatedAt", - "reportPersonId", - ], - where: { id: assign_id }, - }); - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - - const profileData = await this.personalRepository.findOne({ - select: [ - "personal_id", - "prefixName", - "firstName", - "lastName", - "positionName", - "positionLevelName", - "positionLineName", - "orgRootName", - "organization", - ], - where: { - personal_id: assign.personal_id, - }, - }); - - if (!profileData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); - } - - const splitOc = await profileData.organization.split(" "); - const splitOcAmount = await splitOc.length; - const profile = { - ...profileData, - name: `${profileData.prefixName}${profileData.firstName} ${profileData.lastName}`, - Position: profileData.positionName, - Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", - OrganizationOrganization: - splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", - Oc: profileData.orgRootName, - PositionAndLevel: - profileData.positionName + profileData.positionLevelName, - }; - - const jobs = await this.assignJobRepository.find({ - select: ["id", "activity_desc", "goal_desc"], - where: { assign_id }, - }); - - const knowledgeData = await this.assignKnowledgeRepository.find({ - relations: ["knowledge"], - where: { assign_id }, - }); - const knowledges = await knowledgeData.map((x) => ({ - id: x.knowledge_id, - level: x.knowledge_level, - title: x.knowledge.title, - description: - x.knowledge_level == 1 - ? x.knowledge.level1 - : x.knowledge_level == 2 - ? x.knowledge.level2 - : x.knowledge_level == 3 - ? x.knowledge.level3 - : x.knowledge_level == 4 - ? x.knowledge.level4 - : x.knowledge_level == 5 - ? x.knowledge.level5 - : "", - })); - - const lawData = await this.lawsRepository.find({ - where: { active: 1 }, - }); - - const laws = await Promise.all( - lawData.map(async (x) => { - const assignLaw = await this.assignLawRepository.countBy({ - assign_id: assign_id, - law_id: x.id, - }); - - let description = await x.description; - if (isReport) { - const descriptionSplit = await x.description.split(" "); - description = await x.description.replace(descriptionSplit[0], ""); - } - - return { - id: x.id, - selected: assignLaw > 0 ? 1 : 0, - description: description, - status_select: x.status_select, - }; - }) - ); - - const skillsData = await this.assignSkillRepository.find({ - relations: ["skill"], - where: { assign_id }, - }); - - const skills = await skillsData.map((x) => ({ - id: x.skill_id, - level: x.skill_level, - title: x.skill.title, - description: - x.skill_level == 1 - ? x.skill.level1 - : x.skill_level == 2 - ? x.skill.level2 - : x.skill_level == 3 - ? x.skill.level3 - : x.skill_level == 4 - ? x.skill.level4 - : x.skill_level == 5 - ? x.skill.level5 - : "", - })); - - const competencyData = await this.assignCompetencyRepository.find({ - select: [ - "competency_id", - "competency_level", - "competency_name", - "competency_description", - ], - where: { assign_id }, - order: { createdAt: "ASC" }, - }); - - const competencys = await competencyData.map((x) => ({ - id: x.competency_id, - level: x.competency_level, - name: x.competency_name, - description: x.competency_description, - })); - - const competencyGroupData = await this.assignCompetencyGroupRepository.find( - { + try { + const assign = await this.assignRepository.findOne({ select: [ - "competency_group_id", - "competency_group_level", - "competency_group_name", - "competency_group_description", + "id", + "personal_id", + "appointId", + "round_no", + "date_start", + "date_finish", + "other_desc", + "other4_desc", + "other5_no1_desc", + "experimenter_dated", + "active", + "createdAt", + "updatedAt", + "reportPersonId", + ], + where: { id: assign_id }, + }); + + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const profileData = await this.personalRepository.findOne({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "positionLineName", + "orgRootName", + "organization", + ], + where: { + personal_id: assign.personal_id, + }, + }); + + if (!profileData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + const splitOc = await profileData.organization.split(" "); + const splitOcAmount = await splitOc.length; + const profile = { + ...profileData, + name: `${profileData.prefixName}${profileData.firstName} ${profileData.lastName}`, + Position: profileData.positionName, + Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", + OrganizationOrganization: + splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", + Oc: profileData.orgRootName, + PositionAndLevel: + profileData.positionName + profileData.positionLevelName, + }; + + const jobs = await this.assignJobRepository.find({ + select: ["id", "activity_desc", "goal_desc"], + where: { assign_id }, + }); + + const knowledgeData = await this.assignKnowledgeRepository.find({ + relations: ["knowledge"], + where: { assign_id }, + }); + const knowledges = await knowledgeData.map((x) => ({ + id: x.knowledge_id, + level: x.knowledge_level, + title: x.knowledge.title, + description: + x.knowledge_level == 1 + ? x.knowledge.level1 + : x.knowledge_level == 2 + ? x.knowledge.level2 + : x.knowledge_level == 3 + ? x.knowledge.level3 + : x.knowledge_level == 4 + ? x.knowledge.level4 + : x.knowledge_level == 5 + ? x.knowledge.level5 + : "", + })); + + const lawData = await this.lawsRepository.find({ + where: { active: 1 }, + }); + + const laws = await Promise.all( + lawData.map(async (x) => { + const assignLaw = await this.assignLawRepository.countBy({ + assign_id: assign_id, + law_id: x.id, + }); + + let description = await x.description; + if (isReport) { + const descriptionSplit = await x.description.split(" "); + description = await x.description.replace(descriptionSplit[0], ""); + } + + return { + id: x.id, + selected: assignLaw > 0 ? 1 : 0, + description: description, + status_select: x.status_select, + }; + }) + ); + + const skillsData = await this.assignSkillRepository.find({ + relations: ["skill"], + where: { assign_id }, + }); + + const skills = await skillsData.map((x) => ({ + id: x.skill_id, + level: x.skill_level, + title: x.skill.title, + description: + x.skill_level == 1 + ? x.skill.level1 + : x.skill_level == 2 + ? x.skill.level2 + : x.skill_level == 3 + ? x.skill.level3 + : x.skill_level == 4 + ? x.skill.level4 + : x.skill_level == 5 + ? x.skill.level5 + : "", + })); + + const competencyData = await this.assignCompetencyRepository.find({ + select: [ + "competency_id", + "competency_level", + "competency_name", + "competency_description", ], where: { assign_id }, order: { createdAt: "ASC" }, - } - ); - const competency_groups = await competencyGroupData.map((x) => ({ - id: x.competency_group_id, - level: x.competency_group_level, - name: x.competency_group_name, - description: x.competency_group_description, - })); + }); - const outputs = await this.assignOutputRepository.find({ - select: ["id", "output_desc", "indicator_desc"], - where: { assign_id }, - }); + const competencys = await competencyData.map((x) => ({ + id: x.competency_id, + level: x.competency_level, + name: x.competency_name, + description: x.competency_description, + })); - const director = await this.assignDirectorRepository.find({ - where: { assign_id }, - order: { ordering: "ASC" }, - }); - - let mentors = []; - const mentorList = await director.filter((x) => x.role == "mentor"); - if (mentorList.length > 0) { - for (let index = 0; index < mentorList.length; index++) { - const e = await mentorList[index]; - mentors.push({ - ...e, - name: e.fullname, - label: - e.fullname + - " " + - (e.position ? `(${e.position}${e.posLevel})` : ""), - Position: e.position + e.posLevel, // report + const competencyGroupData = + await this.assignCompetencyGroupRepository.find({ + select: [ + "competency_group_id", + "competency_group_level", + "competency_group_name", + "competency_group_description", + ], + where: { assign_id }, + order: { createdAt: "ASC" }, }); + const competency_groups = await competencyGroupData.map((x) => ({ + id: x.competency_group_id, + level: x.competency_group_level, + name: x.competency_group_name, + description: x.competency_group_description, + })); + + const outputs = await this.assignOutputRepository.find({ + select: ["id", "output_desc", "indicator_desc"], + where: { assign_id }, + }); + + const director = await this.assignDirectorRepository.find({ + where: { assign_id }, + order: { ordering: "ASC" }, + }); + + let mentors = []; + const mentorList = await director.filter((x) => x.role == "mentor"); + if (mentorList.length > 0) { + for (let index = 0; index < mentorList.length; index++) { + const e = await mentorList[index]; + mentors.push({ + ...e, + name: e.fullname, + label: + e.fullname + + " " + + (e.position ? `(${e.position}${e.posLevel})` : ""), + Position: e.position + e.posLevel, // report + }); + } } + + const commanderData = await (director.find( + (x) => x.role == "commander" + ) ?? null); + const commander = await (commanderData + ? { + ...commanderData, + name: commanderData.fullname, + label: + commanderData.fullname + + " " + + (commanderData.position + ? `(${commanderData.position}${commanderData.posLevel})` + : ""), + Position: commanderData.position + commanderData.posLevel, // report + } + : null); + + const chairmanData = await (director.find((x) => x.role == "chairman") ?? + null); + const chairman = await (chairmanData + ? { + ...chairmanData, + name: chairmanData.fullname, + label: + chairmanData.fullname + + " " + + (chairmanData.position + ? `(${chairmanData.position}${chairmanData.posLevel})` + : ""), + Position: chairmanData.position + chairmanData.posLevel, // report + } + : null); + + return new HttpSuccess({ + assign, + profile, + jobs, + knowledges, + laws, + skills, + competencys, + competency_groups, + outputs, + mentors, + commander, + chairman, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const commanderData = await (director.find((x) => x.role == "commander") ?? - null); - const commander = await (commanderData - ? { - ...commanderData, - name: commanderData.fullname, - label: - commanderData.fullname + - " " + - (commanderData.position - ? `(${commanderData.position}${commanderData.posLevel})` - : ""), - Position: commanderData.position + commanderData.posLevel, // report - } - : null); - - const chairmanData = await (director.find((x) => x.role == "chairman") ?? - null); - const chairman = await (chairmanData - ? { - ...chairmanData, - name: chairmanData.fullname, - label: - chairmanData.fullname + - " " + - (chairmanData.position - ? `(${chairmanData.position}${chairmanData.posLevel})` - : ""), - Position: chairmanData.position + chairmanData.posLevel, // report - } - : null); - - return new HttpSuccess({ - assign, - profile, - jobs, - knowledges, - laws, - skills, - competencys, - competency_groups, - outputs, - mentors, - commander, - chairman, - }); } } diff --git a/src/controllers/AssignPermissionsController.ts b/src/controllers/AssignPermissionsController.ts index c749f5f..ef848ef 100644 --- a/src/controllers/AssignPermissionsController.ts +++ b/src/controllers/AssignPermissionsController.ts @@ -2,6 +2,8 @@ import { Controller, Route, Security, Tags, Request, Get, Path } from "tsoa"; import { RequestWithUser } from "../middlewares/user"; import { AppDataSource } from "../database/data-source"; import HttpSuccess from "../interfaces/http-success"; +import HttpError from "../interfaces/http-error"; +import HttpStatusCode from "../interfaces/http-status"; import CallAPI from "../interfaces/call-api"; import { AssignDirector } from "../entities/AssignDirector"; @@ -15,55 +17,65 @@ export class AssignPermissionsController extends Controller { private assignRepository = AppDataSource.getRepository(Assign); @Get("{id}") - async GetAssignPermissions(@Request() request: RequestWithUser, @Path() id: string) { - const director = await this.assignDirector.find({ - where: { assign_id: id }, - }); - - const personalId = await new CallAPI() - .GetData(request, "/org/profile/keycloak") - .catch((error) => { - console.error("Error calling API:", error); + async GetAssignPermissions( + @Request() request: RequestWithUser, + @Path() id: string + ) { + try { + const director = await this.assignDirector.find({ + where: { assign_id: id }, }); - const role = await director.find((e: any) => e.personal_id === personalId)?.role; + const personalId = await new CallAPI() + .GetData(request, "/org/profile/keycloak") + .catch((error) => { + console.error("Error calling API:", error); + }); - const reportPersonId = await this.assignRepository.findOneBy({ - id, - reportPersonId: personalId, - }); + const role = await director.find((e: any) => e.personal_id === personalId) + ?.role; - const response = { - tab1: { - isEdit: role === "commander", - isView: true, - }, - tab2: { - isEdit: role === "mentor", - isView: true, - }, - tab3: { - isEdit: role === "commander", - isView: role === "commander" || role === "chairman", - }, - tab4: { - isEdit: role === "commander", - isView: role === "commander" || role === "chairman", - }, - tab5: { - isEdit: Boolean(reportPersonId), - isView: true, - }, - tab6: { - isEdit: true, - isView: true, - }, - tab7: { - isEdit: false, - isView: true, - }, - }; + const reportPersonId = await this.assignRepository.findOneBy({ + id, + reportPersonId: personalId, + }); - return new HttpSuccess(response); + const response = { + tab1: { + isEdit: role === "commander", + isView: true, + }, + tab2: { + isEdit: role === "mentor", + isView: true, + }, + tab3: { + isEdit: role === "commander", + isView: role === "commander" || role === "chairman", + }, + tab4: { + isEdit: role === "commander", + isView: role === "commander" || role === "chairman", + }, + tab5: { + isEdit: Boolean(reportPersonId), + isView: true, + }, + tab6: { + isEdit: true, + isView: true, + }, + tab7: { + isEdit: false, + isView: true, + }, + }; + + return new HttpSuccess(response); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } } diff --git a/src/controllers/CalculateController.ts b/src/controllers/CalculateController.ts index 27ce24b..2edf5d2 100644 --- a/src/controllers/CalculateController.ts +++ b/src/controllers/CalculateController.ts @@ -1,32 +1,53 @@ -import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Post, Body } from "tsoa" -import HttpSuccess from "../interfaces/http-success" -import HttpStatusCode from "../interfaces/http-status" -import { RequestWithUser } from "../middlewares/user" -import { findEndDate } from "../interfaces/utils" +import { + Controller, + Route, + Security, + Tags, + Request, + SuccessResponse, + Response, + Get, + Post, + Body, +} from "tsoa"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatusCode from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { findEndDate } from "../interfaces/utils"; @Route("api/v1/probation/calculate") @Tags("ฟอร์มมอบหมายงาน") @Security("bearerAuth") -@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") +@Response( + HttpStatusCode.INTERNAL_SERVER_ERROR, + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง" +) export class CalculateController extends Controller { - /** - * API คำนวนวันสิ้นสุดตามวันที่เริ่มและระยะเวลาเดือนตามที่ส่งค่ามา - * - * @summary คำนวนวันสิ้นสุดตามวันที่เริ่มและระยะเวลาเดือนตามที่ส่งค่ามา - * - */ - @Post("assign-finish") - async AssignFinish( - @Body() - requestBody: { - month: number - start_date: Date - }, - @Request() request: RequestWithUser - ) { - const { month, start_date } = requestBody - const finish_date = findEndDate(month, start_date) + /** + * API คำนวนวันสิ้นสุดตามวันที่เริ่มและระยะเวลาเดือนตามที่ส่งค่ามา + * + * @summary คำนวนวันสิ้นสุดตามวันที่เริ่มและระยะเวลาเดือนตามที่ส่งค่ามา + * + */ + @Post("assign-finish") + async AssignFinish( + @Body() + requestBody: { + month: number; + start_date: Date; + }, + @Request() request: RequestWithUser + ) { + try { + const { month, start_date } = requestBody; + const finish_date = findEndDate(month, start_date); - return new HttpSuccess({ finish_date }) - } + return new HttpSuccess({ finish_date }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } } diff --git a/src/controllers/DataOptionsController.ts b/src/controllers/DataOptionsController.ts index 19ad7fe..44b9ff1 100644 --- a/src/controllers/DataOptionsController.ts +++ b/src/controllers/DataOptionsController.ts @@ -1,356 +1,432 @@ -import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Query } from "tsoa" -import { AppDataSource } from "../database/data-source" -import HttpSuccess from "../interfaces/http-success" -import HttpStatusCode from "../interfaces/http-status" -import HttpError from "../interfaces/http-error" -import { RequestWithUser } from "../middlewares/user" -import { Knowledge, TypeKnowledge } from "../entities/Knowledge" -import { Skill, TypeSkill } from "../entities/Skill" -import { MapKnowledgeSkill } from "../entities/MapKnowledgeSkill" -import { Personal } from "../entities/Personal" -import { Law } from "../entities/Law" -import { Assign } from "../entities/Assign" -import permission from "../interfaces/permission" +import { + Controller, + Route, + Security, + Tags, + Request, + SuccessResponse, + Response, + Get, + Query, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatusCode from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { Knowledge, TypeKnowledge } from "../entities/Knowledge"; +import { Skill, TypeSkill } from "../entities/Skill"; +import { MapKnowledgeSkill } from "../entities/MapKnowledgeSkill"; +import { Personal } from "../entities/Personal"; +import { Law } from "../entities/Law"; +import { Assign } from "../entities/Assign"; +import permission from "../interfaces/permission"; @Route("api/v1/probation/data-options") @Tags("Data Options") @Security("bearerAuth") -@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") +@Response( + HttpStatusCode.INTERNAL_SERVER_ERROR, + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง" +) export class DataOptionController extends Controller { - private personalRepository = AppDataSource.getRepository(Personal) - private knowledgeRepository = AppDataSource.getRepository(Knowledge) - private mapKnowledgeSkillRepository = AppDataSource.getRepository(MapKnowledgeSkill) - private skillRepository = AppDataSource.getRepository(Skill) - private lawRepository = AppDataSource.getRepository(Law) - private assignRepository = AppDataSource.getRepository(Assign) + private personalRepository = AppDataSource.getRepository(Personal); + private knowledgeRepository = AppDataSource.getRepository(Knowledge); + private mapKnowledgeSkillRepository = + AppDataSource.getRepository(MapKnowledgeSkill); + private skillRepository = AppDataSource.getRepository(Skill); + private lawRepository = AppDataSource.getRepository(Law); + private assignRepository = AppDataSource.getRepository(Assign); - /** - * API list รายการความรู้ - * - * @summary options ความรู้ - * - */ - @Get("knowledge") - async GetKnowledge(@Query() personal_id: string) { - const person = await this.personalRepository.findOne({ - where: { personal_id }, - }) + /** + * API list รายการความรู้ + * + * @summary options ความรู้ + * + */ + @Get("knowledge") + async GetKnowledge(@Query() personal_id: string) { + try { + const person = await this.personalRepository.findOne({ + where: { personal_id }, + }); - if (!person) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล") - } + if (!person) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } - let result = await this.mapKnowledgeSkillRepository.findOne({ - where: { - positionName: person.positionName, - positionLevelName: person.positionLevelName, - active: 1, - }, - }) + let result = await this.mapKnowledgeSkillRepository.findOne({ + where: { + positionName: person.positionName, + positionLevelName: person.positionLevelName, + active: 1, + }, + }); - if (!result) { - // ถ้าตำแหน่งไม่ตรงหาจากระดับตำแหน่งแทนเพื่อให้ฟอร์มสามารถกรอกต่อได้ - result = await this.mapKnowledgeSkillRepository.findOne({ - where: { - positionLevelName: person.positionLevelName, - active: 1, - }, - }) - } + if (!result) { + // ถ้าตำแหน่งไม่ตรงหาจากระดับตำแหน่งแทนเพื่อให้ฟอร์มสามารถกรอกต่อได้ + result = await this.mapKnowledgeSkillRepository.findOne({ + where: { + positionLevelName: person.positionLevelName, + active: 1, + }, + }); + } - if (!result) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลความรู้ที่ตรงกับตำแหน่ง") - } + if (!result) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลความรู้ที่ตรงกับตำแหน่ง" + ); + } - const knowledges = await this.knowledgeRepository.find({ - where: { type: TypeKnowledge.PERFORMANCE, active: 1 }, - }) + const knowledges = await this.knowledgeRepository.find({ + where: { type: TypeKnowledge.PERFORMANCE, active: 1 }, + }); - const knowledge = knowledges.map(knowledge => ({ - id: knowledge.id, - title: knowledge.title, - description: - result.knowlage_performance_level == 1 - ? knowledge.level1 - : result.knowlage_performance_level == 2 - ? knowledge.level2 - : result.knowlage_performance_level == 3 - ? knowledge.level3 - : result.knowlage_performance_level == 4 - ? knowledge.level4 - : knowledge.level5, - level: result.knowlage_performance_level, - })) + const knowledge = knowledges.map((knowledge) => ({ + id: knowledge.id, + title: knowledge.title, + description: + result.knowlage_performance_level == 1 + ? knowledge.level1 + : result.knowlage_performance_level == 2 + ? knowledge.level2 + : result.knowlage_performance_level == 3 + ? knowledge.level3 + : result.knowlage_performance_level == 4 + ? knowledge.level4 + : knowledge.level5, + level: result.knowlage_performance_level, + })); + return new HttpSuccess(knowledge); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - return new HttpSuccess(knowledge) - } + /** + * API ข้อมูลทักษะ + * + * @summary options ทักษะ + * + */ + @Get("skill") + async GetSkill(@Query() personal_id: string) { + try { + const person = await this.personalRepository.findOne({ + where: { personal_id }, + }); - /** - * API ข้อมูลทักษะ - * - * @summary options ทักษะ - * - */ - @Get("skill") - async GetSkill(@Query() personal_id: string) { - const person = await this.personalRepository.findOne({ - where: { personal_id }, - }) + if (!person) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } - if (!person) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } + let result = await this.mapKnowledgeSkillRepository.findOne({ + select: [ + "skill_computer_level", + "skill_english_level", + "skill_information_level", + "skill_resourse_level", + ], + where: { + positionName: person.positionName, + positionLevelName: person.positionLevelName, + active: 1, + }, + }); - let result = await this.mapKnowledgeSkillRepository.findOne({ - select: ["skill_computer_level", "skill_english_level", "skill_information_level", "skill_resourse_level"], - where: { - positionName: person.positionName, - positionLevelName: person.positionLevelName, - active: 1, - }, - }) + if (!result) { + // ถ้าตำแหน่งไม่ตรงหาจากระดับตำแหน่งแทนเพื่อให้ฟอร์มสามารถกรอกต่อได้ + result = await this.mapKnowledgeSkillRepository.findOne({ + select: [ + "skill_computer_level", + "skill_english_level", + "skill_information_level", + "skill_resourse_level", + ], + where: { + positionLevelName: person.positionLevelName, + active: 1, + }, + }); + } - if (!result) { - // ถ้าตำแหน่งไม่ตรงหาจากระดับตำแหน่งแทนเพื่อให้ฟอร์มสามารถกรอกต่อได้ - result = await this.mapKnowledgeSkillRepository.findOne({ - select: ["skill_computer_level", "skill_english_level", "skill_information_level", "skill_resourse_level"], - where: { - positionLevelName: person.positionLevelName, - active: 1, - }, - }) - } + if (!result) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลทักษะที่ตรงกับตำแหน่ง" + ); + } - if (!result) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทักษะที่ตรงกับตำแหน่ง") - } + const computerData = await this.skillRepository.findOne({ + where: { type: TypeSkill.COMPUTER, active: 1 }, + }); - const computerData = await this.skillRepository.findOne({ - where: { type: TypeSkill.COMPUTER, active: 1 }, - }) + if (!computerData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลทักษะคอมพิวเตอร์" + ); + } + const computer = await { + id: computerData.id, + title: computerData.title, + level_description: + result.skill_computer_level == 1 + ? computerData.level1 + : result.skill_computer_level == 2 + ? computerData.level2 + : result.skill_computer_level == 3 + ? computerData.level3 + : result.skill_computer_level == 4 + ? computerData.level4 + : computerData.level5, + level: result.skill_computer_level, + }; - if (!computerData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทักษะคอมพิวเตอร์") - } - const computer = await { - id: computerData.id, - title: computerData.title, - level_description: - result.skill_computer_level == 1 - ? computerData.level1 - : result.skill_computer_level == 2 - ? computerData.level2 - : result.skill_computer_level == 3 - ? computerData.level3 - : result.skill_computer_level == 4 - ? computerData.level4 - : computerData.level5, - level: result.skill_computer_level, - } + const englishData = await this.skillRepository.findOne({ + where: { type: TypeSkill.ENG, active: 1 }, + }); - const englishData = await this.skillRepository.findOne({ - where: { type: TypeSkill.ENG, active: 1 }, - }) + if (!englishData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลทักษะภาษาอังกฤษ" + ); + } - if (!englishData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทักษะภาษาอังกฤษ") - } + const english = await { + id: englishData.id, + title: englishData.title, + level_description: + result.skill_english_level == 1 + ? englishData.level1 + : result.skill_english_level == 2 + ? englishData.level2 + : result.skill_english_level == 3 + ? englishData.level3 + : result.skill_english_level == 4 + ? englishData.level4 + : englishData.level5, + level: result.skill_english_level, + }; - const english = await { - id: englishData.id, - title: englishData.title, - level_description: - result.skill_english_level == 1 - ? englishData.level1 - : result.skill_english_level == 2 - ? englishData.level2 - : result.skill_english_level == 3 - ? englishData.level3 - : result.skill_english_level == 4 - ? englishData.level4 - : englishData.level5, - level: result.skill_english_level, - } + const informationData = await this.skillRepository.findOne({ + where: { type: TypeSkill.INFORMATION, active: 1 }, + }); - const informationData = await this.skillRepository.findOne({ - where: { type: TypeSkill.INFORMATION, active: 1 }, - }) + if (!informationData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } - if (!informationData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } + const information = await { + id: informationData.id, + title: informationData.title, + level_description: + result.skill_information_level == 1 + ? informationData.level1 + : result.skill_information_level == 2 + ? informationData.level2 + : result.skill_information_level == 3 + ? informationData.level3 + : result.skill_information_level == 4 + ? informationData.level4 + : informationData.level5, + level: result.skill_information_level, + }; - const information = await { - id: informationData.id, - title: informationData.title, - level_description: - result.skill_information_level == 1 - ? informationData.level1 - : result.skill_information_level == 2 - ? informationData.level2 - : result.skill_information_level == 3 - ? informationData.level3 - : result.skill_information_level == 4 - ? informationData.level4 - : informationData.level5, - level: result.skill_information_level, - } + const resourseData = await this.skillRepository.findOne({ + where: { type: TypeSkill.RESOURSE, active: 1 }, + }); + if (!resourseData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } - const resourseData = await this.skillRepository.findOne({ - where: { type: TypeSkill.RESOURSE, active: 1 }, - }) - if (!resourseData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } + const resourse = await { + id: resourseData.id, + title: resourseData.title, + level_description: + result.skill_resourse_level == 1 + ? resourseData.level1 + : result.skill_resourse_level == 2 + ? resourseData.level2 + : result.skill_resourse_level == 3 + ? resourseData.level3 + : result.skill_resourse_level == 4 + ? resourseData.level4 + : resourseData.level5, + level: result.skill_resourse_level, + }; - const resourse = await { - id: resourseData.id, - title: resourseData.title, - level_description: - result.skill_resourse_level == 1 - ? resourseData.level1 - : result.skill_resourse_level == 2 - ? resourseData.level2 - : result.skill_resourse_level == 3 - ? resourseData.level3 - : result.skill_resourse_level == 4 - ? resourseData.level4 - : resourseData.level5, - level: result.skill_resourse_level, - } + return new HttpSuccess({ + computer, + english, + information, + resourse, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - return new HttpSuccess({ - computer, - english, - information, - resourse, - }) - } + /** + * API list รายการกฎหมาย + * + * @summary options กฎหมาย + * + */ + @Get("law") + async GetLaw(@Query() personal_id: string) { + try { + const results = await this.lawRepository.find({ + select: ["id", "parent_id", "description", "status_select"], + where: { + active: 1, + }, + }); - /** - * API list รายการกฎหมาย - * - * @summary options กฎหมาย - * - */ - @Get("law") - async GetLaw(@Query() personal_id: string) { - const results = await this.lawRepository.find({ - select: ["id", "parent_id", "description", "status_select"], - where: { - active: 1, - }, - }) + if (!results) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } - if (!results) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } + const result = await results.map((v) => ({ + ...v, + checked: 0, + })); - const result = await results.map(v => ({ - ...v, - checked: 0, - })) + return new HttpSuccess(result); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - return new HttpSuccess(result) - } + /** + * API ดึงข้อมูลจำนวนครั้งแบบมอบหมายงานและข้อมูลผู้ทดลอง + * + * @summary จำนวนครั้งแบบมอบหมายงานและข้อมูลผู้ทดลอง + * + */ + @Get("new-assign") + async NewAssign( + @Query() personal_id: string, + @Request() request: RequestWithUser + ) { + try { + let _workflow = await new permission().Workflow( + request, + personal_id, + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); - /** - * API ดึงข้อมูลจำนวนครั้งแบบมอบหมายงานและข้อมูลผู้ทดลอง - * - * @summary จำนวนครั้งแบบมอบหมายงานและข้อมูลผู้ทดลอง - * - */ - @Get("new-assign") - async NewAssign(@Query() personal_id: string, @Request() request: RequestWithUser) { - let _workflow = await new permission().Workflow(request, personal_id, "SYS_PROBATION") - if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION") + const person = await this.personalRepository.findOne({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "posNo", + "positionName", + "positionLevelName", + "positionLineName", + "isProbation", + "orgRootName", + "organization", + "createdAt", + "updatedAt", + ], + where: { personal_id }, + }); - const person = await this.personalRepository.findOne({ - select: [ - "personal_id", - "prefixName", - "firstName", - "lastName", - "posNo", - "positionName", - "positionLevelName", - "positionLineName", - "isProbation", - "orgRootName", - "organization", - "createdAt", - "updatedAt", - ], - where: { personal_id }, - }) + if (!person) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } - if (!person) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } + const assign = await this.assignRepository.count({ + where: { + personal_id, + }, + }); - const assign = await this.assignRepository.count({ - where: { - personal_id, - }, - }) + const responsePerson = { + id: person.personal_id, + ...person, + }; - const responsePerson = { - id: person.personal_id, - ...person, - } + return new HttpSuccess({ + person: responsePerson, + assign_no: assign + 1, + assign_month: 6, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } + /** + * API ดึงข้อมูลจำนวนครั้งแบบมอบหมายงานและข้อมูลผู้ทดลอง (USER) + * + * @summary จำนวนครั้งแบบมอบหมายงานและข้อมูลผู้ทดลอง (USER) + * + */ + @Get("new-assign-user") + async NewAssignUser( + @Query() personal_id: string, + @Request() request: RequestWithUser + ) { + try { + const person = await this.personalRepository.findOne({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "posNo", + "positionName", + "positionLevelName", + "positionLineName", + "isProbation", + "orgRootName", + "organization", + "createdAt", + "updatedAt", + ], + where: { personal_id }, + }); - return new HttpSuccess({ - person: responsePerson, - assign_no: assign + 1, - assign_month: 6, - }) - } - /** - * API ดึงข้อมูลจำนวนครั้งแบบมอบหมายงานและข้อมูลผู้ทดลอง (USER) - * - * @summary จำนวนครั้งแบบมอบหมายงานและข้อมูลผู้ทดลอง (USER) - * - */ - @Get("new-assign-user") - async NewAssignUser(@Query() personal_id: string, @Request() request: RequestWithUser) { - const person = await this.personalRepository.findOne({ - select: [ - "personal_id", - "prefixName", - "firstName", - "lastName", - "posNo", - "positionName", - "positionLevelName", - "positionLineName", - "isProbation", - "orgRootName", - "organization", - "createdAt", - "updatedAt", - ], - where: { personal_id }, - }) + if (!person) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } - if (!person) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } + const assign = await this.assignRepository.count({ + where: { + personal_id, + }, + }); - const assign = await this.assignRepository.count({ - where: { - personal_id, - }, - }) + const responsePerson = { + id: person.personal_id, + ...person, + }; - const responsePerson = { - id: person.personal_id, - ...person, - } - - return new HttpSuccess({ - person: responsePerson, - assign_no: assign + 1, - assign_month: 6, - }) - } + return new HttpSuccess({ + person: responsePerson, + assign_no: assign + 1, + assign_month: 6, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } } diff --git a/src/controllers/EvaluateChairmanController.ts b/src/controllers/EvaluateChairmanController.ts index 6634c69..2e2a208 100644 --- a/src/controllers/EvaluateChairmanController.ts +++ b/src/controllers/EvaluateChairmanController.ts @@ -53,145 +53,154 @@ export class EvaluateChairmanController extends Controller { @Query() assign_id: string, @Request() request: RequestWithUser ) { - let _workflow = await new permission().Workflow( - request, - assign_id, - "SYS_PROBATION" - ); - if (_workflow == false) - await new permission().PermissionGet(request, "SYS_PROBATION"); - - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { + try { + let _workflow = await new permission().Workflow( + request, assign_id, - role: "chairman", - }, - }); - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); - } - const director_id = director.personal_id; - - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }); - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - - const profile = await (assign.profile - ? { - ...assign.profile, - id: assign.profile.personal_id, - name: - assign.profile.prefixName + - assign.profile.firstName + - " " + - assign.profile.lastName, - Oc: assign.profile.organization, - } - : null); - - const evaluate_amount = await this.evaluateChairmanRepository.count({ - where: { - assign_id, - director_id, - }, - }); - const evaluate_no = await (evaluate_amount + 1); - const start_date = - evaluate_amount == 0 - ? assign.date_start - : findEndDate(evaluate_amount * 3, assign.date_start); - - const directorData = await this.assignDirectorRepository.find({ - where: { assign_id }, - order: { ordering: "ASC" }, - }); - - if (!directorData) { - throw new HttpError( - HttpStatusCode.NOT_FOUND, - "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน" + "SYS_PROBATION" ); - } + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); - let mentors = []; - const mentorList = await directorData.filter((x) => x.role == "mentor"); - if (mentorList.length > 0) { - for (let index = 0; index < mentorList.length; index++) { - const e = await mentorList[index]; - - mentors.push({ - personal_id: e.personal_id, - dated: e.dated, - name: e.fullname, - label: - e.fullname + - " " + - (e.position ? `(${e.position}${e.posLevel})` : ""), - position: e.position, - posType: e.posType, - posLevel: e.posLevel, - }); + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "chairman", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); } + const director_id = director.personal_id; + + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const profile = await (assign.profile + ? { + ...assign.profile, + id: assign.profile.personal_id, + name: + assign.profile.prefixName + + assign.profile.firstName + + " " + + assign.profile.lastName, + Oc: assign.profile.organization, + } + : null); + + const evaluate_amount = await this.evaluateChairmanRepository.count({ + where: { + assign_id, + director_id, + }, + }); + const evaluate_no = await (evaluate_amount + 1); + const start_date = + evaluate_amount == 0 + ? assign.date_start + : findEndDate(evaluate_amount * 3, assign.date_start); + + const directorData = await this.assignDirectorRepository.find({ + where: { assign_id }, + order: { ordering: "ASC" }, + }); + + if (!directorData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน" + ); + } + + let mentors = []; + const mentorList = await directorData.filter((x) => x.role == "mentor"); + if (mentorList.length > 0) { + for (let index = 0; index < mentorList.length; index++) { + const e = await mentorList[index]; + + mentors.push({ + personal_id: e.personal_id, + dated: e.dated, + name: e.fullname, + label: + e.fullname + + " " + + (e.position ? `(${e.position}${e.posLevel})` : ""), + position: e.position, + posType: e.posType, + posLevel: e.posLevel, + }); + } + } + + const commanderData = await (directorData.find( + (x) => x.role == "commander" + ) ?? null); + + const commander = + commanderData != null + ? { + personal_id: commanderData.personal_id, + dated: commanderData.dated, + name: commanderData.fullname, + label: + commanderData.fullname + + " " + + (commanderData.position + ? `(${commanderData.position}${commanderData.posLevel})` + : ""), + position: commanderData.position, + posType: commanderData.posType, + posLevel: commanderData.posLevel, + } + : null; + + const chairmanData = await (directorData.find( + (x) => x.role == "chairman" + ) ?? null); + const chairman = + chairmanData != null + ? { + personal_id: chairmanData.personal_id, + dated: chairmanData.dated, + name: chairmanData.fullname, + label: + chairmanData.fullname + + " " + + (chairmanData.position + ? `(${chairmanData.position}${chairmanData.posLevel})` + : ""), + position: chairmanData.position, + posType: chairmanData.posType, + posLevel: chairmanData.posLevel, + } + : null; + + return new HttpSuccess({ + person: profile ? profile : null, + assign, + evaluate_no: evaluate_no, + start_date: start_date, + end_date: findEndDate(3, start_date), + commander, + mentors, + chairman, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const commanderData = await (directorData.find( - (x) => x.role == "commander" - ) ?? null); - - const commander = - commanderData != null - ? { - personal_id: commanderData.personal_id, - dated: commanderData.dated, - name: commanderData.fullname, - label: - commanderData.fullname + - " " + - (commanderData.position - ? `(${commanderData.position}${commanderData.posLevel})` - : ""), - position: commanderData.position, - posType: commanderData.posType, - posLevel: commanderData.posLevel, - } - : null; - - const chairmanData = await (directorData.find( - (x) => x.role == "chairman" - ) ?? null); - const chairman = - chairmanData != null - ? { - personal_id: chairmanData.personal_id, - dated: chairmanData.dated, - name: chairmanData.fullname, - label: - chairmanData.fullname + - " " + - (chairmanData.position - ? `(${chairmanData.position}${chairmanData.posLevel})` - : ""), - position: chairmanData.position, - posType: chairmanData.posType, - posLevel: chairmanData.posLevel, - } - : null; - - return new HttpSuccess({ - person: profile ? profile : null, - assign, - evaluate_no: evaluate_no, - start_date: start_date, - end_date: findEndDate(3, start_date), - commander, - mentors, - chairman, - }); } /** @@ -206,157 +215,166 @@ export class EvaluateChairmanController extends Controller { @Query() assign_id: string, @Query() evaluate_no?: string ) { - await new permission().PermissionGet(request, "SYS_PROBATION"); - // ต้องปรับเป็น id ของคนที่ access เข้ามา - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "chairman", - }, - }); - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); - } - const director_id = director.personal_id; - let evaluate: any = null; - if (evaluate_no) { - evaluate = await this.evaluateChairmanRepository.findOne({ + try { + await new permission().PermissionGet(request, "SYS_PROBATION"); + // ต้องปรับเป็น id ของคนที่ access เข้ามา + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], where: { - director_id, assign_id, - no: evaluate_no, + role: "chairman", }, }); - } else { - evaluate = await this.evaluateChairmanRepository.find({ - where: { - director_id, - assign_id, - }, - }); - - if (evaluate) - evaluate = await evaluate.map((element: EvaluateChairman) => ({ - ...element, - no: Number(element.no), - })); - } - - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบประเมิน"); - } - - const assign = await this.assignRepository.findOne({ - where: { id: assign_id }, - }); - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - - const experimenteeData = await this.personalRepository.find({ - select: [ - "personal_id", - "prefixName", - "firstName", - "lastName", - "positionName", - "positionLevelName", - "organization", - ], - where: { personal_id: assign.personal_id }, - }); - - const experimentee = await experimenteeData.map((element) => ({ - ...element, - name: element.prefixName + element.firstName + " " + element.lastName, - Oc: element.organization, - })); - - const directorData = await this.assignDirectorRepository.find({ - where: { assign_id }, - order: { ordering: "ASC" }, - }); - - if (!directorData) { - throw new HttpError( - HttpStatusCode.NOT_FOUND, - "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน" - ); - } - - let mentors = []; - const mentorList = await directorData.filter((x) => x.role == "mentor"); - if (mentorList.length > 0) { - for (let index = 0; index < mentorList.length; index++) { - const e = await mentorList[index]; - - mentors.push({ - personal_id: e.personal_id, - dated: e.dated, - name: e.fullname, - label: - e.fullname + - " " + - (e.position ? `(${e.position}${e.posLevel})` : ""), - position: e.position, - posType: e.posType, - posLevel: e.posLevel, - }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); } + const director_id = director.personal_id; + let evaluate: any = null; + if (evaluate_no) { + evaluate = await this.evaluateChairmanRepository.findOne({ + where: { + director_id, + assign_id, + no: evaluate_no, + }, + }); + } else { + evaluate = await this.evaluateChairmanRepository.find({ + where: { + director_id, + assign_id, + }, + }); + + if (evaluate) + evaluate = await evaluate.map((element: EvaluateChairman) => ({ + ...element, + no: Number(element.no), + })); + } + + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบประเมิน"); + } + + const assign = await this.assignRepository.findOne({ + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const experimenteeData = await this.personalRepository.find({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "organization", + ], + where: { personal_id: assign.personal_id }, + }); + + const experimentee = await experimenteeData.map((element) => ({ + ...element, + name: element.prefixName + element.firstName + " " + element.lastName, + Oc: element.organization, + })); + + const directorData = await this.assignDirectorRepository.find({ + where: { assign_id }, + order: { ordering: "ASC" }, + }); + + if (!directorData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน" + ); + } + + let mentors = []; + const mentorList = await directorData.filter((x) => x.role == "mentor"); + if (mentorList.length > 0) { + for (let index = 0; index < mentorList.length; index++) { + const e = await mentorList[index]; + + mentors.push({ + personal_id: e.personal_id, + dated: e.dated, + name: e.fullname, + label: + e.fullname + + " " + + (e.position ? `(${e.position}${e.posLevel})` : ""), + position: e.position, + posType: e.posType, + posLevel: e.posLevel, + }); + } + } + + const commanderData = await (directorData.find( + (x) => x.role == "commander" + ) ?? null); + + const commander = + commanderData != null + ? { + personal_id: commanderData.personal_id, + dated: commanderData.dated, + name: commanderData.fullname, + label: + commanderData.fullname + + " " + + (commanderData.position + ? `(${commanderData.position}${commanderData.posLevel})` + : ""), + position: commanderData.position, + posType: commanderData.posType, + posLevel: commanderData.posLevel, + } + : null; + + const chairmanData = await (directorData.find( + (x) => x.role == "chairman" + ) ?? null); + const chairman = + chairmanData != null + ? { + personal_id: chairmanData.personal_id, + dated: chairmanData.dated, + name: chairmanData.fullname, + label: + chairmanData.fullname + + " " + + (chairmanData.position + ? `(${chairmanData.position}${chairmanData.posLevel})` + : ""), + position: chairmanData.position, + posType: chairmanData.posType, + posLevel: chairmanData.posLevel, + } + : null; + + return new HttpSuccess({ + experimentee: experimentee, + mentors: mentors, + commander: commander, + chairman: chairman, + assign, + evaluate, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const commanderData = await (directorData.find( - (x) => x.role == "commander" - ) ?? null); - - const commander = - commanderData != null - ? { - personal_id: commanderData.personal_id, - dated: commanderData.dated, - name: commanderData.fullname, - label: - commanderData.fullname + - " " + - (commanderData.position - ? `(${commanderData.position}${commanderData.posLevel})` - : ""), - position: commanderData.position, - posType: commanderData.posType, - posLevel: commanderData.posLevel, - } - : null; - - const chairmanData = await (directorData.find( - (x) => x.role == "chairman" - ) ?? null); - const chairman = - chairmanData != null - ? { - personal_id: chairmanData.personal_id, - dated: chairmanData.dated, - name: chairmanData.fullname, - label: - chairmanData.fullname + - " " + - (chairmanData.position - ? `(${chairmanData.position}${chairmanData.posLevel})` - : ""), - position: chairmanData.position, - posType: chairmanData.posType, - posLevel: chairmanData.posLevel, - } - : null; - - return new HttpSuccess({ - experimentee: experimentee, - mentors: mentors, - commander: commander, - chairman: chairman, - assign, - evaluate, - }); } /** @@ -371,81 +389,90 @@ export class EvaluateChairmanController extends Controller { @Body() requestBody: CreateEvaluateChairman, @Request() request: RequestWithUser ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION"); + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "chairman", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + + const director_id = director.personal_id; + + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const postData: any = await { assign_id, - role: "chairman", - }, - }); - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); - } + ...requestBody, + director_id, + no: requestBody.evaluate_no, + date_start: requestBody.start_date, + personal_id: assign.personal_id, - const director_id = director.personal_id; - - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }); - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - - const postData: any = await { - assign_id, - ...requestBody, - director_id, - no: requestBody.evaluate_no, - date_start: requestBody.start_date, - personal_id: assign.personal_id, - - achievement_other_desc: requestBody.achievement_other - ? requestBody.achievement_other.text - : "", - achievement_other_level: requestBody.achievement_other - ? Number(requestBody.achievement_other.level) - : 0, - behavior_other_desc: requestBody.behavior_orther.text, - behavior_other_level: - requestBody.behavior_orther.text != "" - ? Number(requestBody.behavior_orther.level) + achievement_other_desc: requestBody.achievement_other + ? requestBody.achievement_other.text + : "", + achievement_other_level: requestBody.achievement_other + ? Number(requestBody.achievement_other.level) : 0, + behavior_other_desc: requestBody.behavior_orther.text, + behavior_other_level: + requestBody.behavior_orther.text != "" + ? Number(requestBody.behavior_orther.level) + : 0, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }; + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; - await this.evaluateChairmanRepository.save(postData, { - data: request, - }); - setLogDataDiff(request, { before: null, after: postData }); + await this.evaluateChairmanRepository.save(postData, { + data: request, + }); + setLogDataDiff(request, { before: null, after: postData }); - if (Number(requestBody.evaluate_no) < 2) { - // #noted cronjob - // แจ้งประธานเข้ามาบันทึกผลทุก 3 เดือน 2 ครั้ง - var dateSend = await findEndDate(3, requestBody.start_date); - const nextNo = await (Number(requestBody.evaluate_no) + 1); - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, - body: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการ (สำหรับคณะกรรมการ) ครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, - receiverUserId: director_id, - payload: "", - isSendMail: true, - isSendInbox: true, - receiveDate: dateSend, - }) - .catch((error) => { - console.error("Error calling API:", error); - }); + if (Number(requestBody.evaluate_no) < 2) { + // #noted cronjob + // แจ้งประธานเข้ามาบันทึกผลทุก 3 เดือน 2 ครั้ง + var dateSend = await findEndDate(3, requestBody.start_date); + const nextNo = await (Number(requestBody.evaluate_no) + 1); + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, + body: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการ (สำหรับคณะกรรมการ) ครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, + receiverUserId: director_id, + payload: "", + isSendMail: true, + isSendInbox: true, + receiveDate: dateSend, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + } + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - return new HttpSuccess(); } /** @@ -461,83 +488,90 @@ export class EvaluateChairmanController extends Controller { @Body() requestBody: CreateEvaluateChairman, @Request() request: RequestWithUser ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION"); + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - let evaluate = await this.evaluateChairmanRepository.findOne({ - where: { id: evaluate_id }, - }); + let evaluate = await this.evaluateChairmanRepository.findOne({ + where: { id: evaluate_id }, + }); - const before = evaluate; + const before = evaluate; - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน"); + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน"); + } + + evaluate.chairman_dated = requestBody.chairman_dated; + evaluate.director1_dated = requestBody.director1_dated; + evaluate.director2_dated = requestBody.director2_dated; + evaluate.knowledge_level = requestBody.knowledge_level; + evaluate.apply_level = requestBody.apply_level; + evaluate.success_level = requestBody.success_level; + evaluate.achievement_other_desc = requestBody.achievement_other + ? requestBody.achievement_other.text + : ""; + evaluate.achievement_other_level = + requestBody.achievement_other.text != "" + ? Number(requestBody.achievement_other.level) + : 0; + + evaluate.conduct1_level = requestBody.conduct1_level; + evaluate.conduct2_level = requestBody.conduct2_level; + evaluate.conduct3_level = requestBody.conduct3_level; + evaluate.conduct4_level = requestBody.conduct4_level; + evaluate.moral1_level = requestBody.moral1_level; + evaluate.moral2_level = requestBody.moral2_level; + evaluate.moral3_level = requestBody.moral3_level; + evaluate.discipline1_level = requestBody.discipline1_level; + evaluate.discipline2_level = requestBody.discipline2_level; + evaluate.discipline3_level = requestBody.discipline3_level; + evaluate.discipline4_level = requestBody.discipline4_level; + evaluate.discipline5_level = requestBody.discipline5_level; + evaluate.behavior_other_desc = requestBody.behavior_orther.text; + evaluate.behavior_other_level = + requestBody.behavior_orther.text != "" + ? Number(requestBody.behavior_orther.level) + : 0; + evaluate.develop_orientation_score = + requestBody.develop_orientation_score; + evaluate.develop_self_learning_score = + requestBody.develop_self_learning_score; + evaluate.develop_training_seminar_score = + requestBody.develop_training_seminar_score; + evaluate.develop_other_training_score = + requestBody.develop_other_training_score; + evaluate.develop_orientation_percent = + requestBody.develop_orientation_percent; + evaluate.develop_self_learning_percent = + requestBody.develop_self_learning_percent; + evaluate.develop_training_seminar_percent = + requestBody.develop_training_seminar_percent; + evaluate.develop_other_training_percent = + requestBody.develop_other_training_percent; + evaluate.develop_result = requestBody.develop_result; + evaluate.achievement_score = requestBody.achievement_score; + evaluate.achievement_score_total = requestBody.achievement_score_total; + evaluate.achievement_percent = requestBody.achievement_percent; + evaluate.achievement_result = requestBody.achievement_result; + evaluate.behavior_score = requestBody.behavior_score; + evaluate.behavior_score_total = requestBody.behavior_score_total; + evaluate.behavior_percent = requestBody.behavior_percent; + evaluate.behavior_result = requestBody.behavior_result; + evaluate.sum_score = requestBody.sum_score; + evaluate.sum_percent = requestBody.sum_percent; + evaluate.evaluate_result = requestBody.evaluate_result; + + evaluate.updateUserId = request.user.sub; + evaluate.updateFullName = request.user.name; + + await this.evaluateChairmanRepository.save(evaluate, { data: request }); + setLogDataDiff(request, { before, after: evaluate }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - evaluate.chairman_dated = requestBody.chairman_dated; - evaluate.director1_dated = requestBody.director1_dated; - evaluate.director2_dated = requestBody.director2_dated; - evaluate.knowledge_level = requestBody.knowledge_level; - evaluate.apply_level = requestBody.apply_level; - evaluate.success_level = requestBody.success_level; - evaluate.achievement_other_desc = requestBody.achievement_other - ? requestBody.achievement_other.text - : ""; - evaluate.achievement_other_level = - requestBody.achievement_other.text != "" - ? Number(requestBody.achievement_other.level) - : 0; - - evaluate.conduct1_level = requestBody.conduct1_level; - evaluate.conduct2_level = requestBody.conduct2_level; - evaluate.conduct3_level = requestBody.conduct3_level; - evaluate.conduct4_level = requestBody.conduct4_level; - evaluate.moral1_level = requestBody.moral1_level; - evaluate.moral2_level = requestBody.moral2_level; - evaluate.moral3_level = requestBody.moral3_level; - evaluate.discipline1_level = requestBody.discipline1_level; - evaluate.discipline2_level = requestBody.discipline2_level; - evaluate.discipline3_level = requestBody.discipline3_level; - evaluate.discipline4_level = requestBody.discipline4_level; - evaluate.discipline5_level = requestBody.discipline5_level; - evaluate.behavior_other_desc = requestBody.behavior_orther.text; - evaluate.behavior_other_level = - requestBody.behavior_orther.text != "" - ? Number(requestBody.behavior_orther.level) - : 0; - evaluate.develop_orientation_score = requestBody.develop_orientation_score; - evaluate.develop_self_learning_score = - requestBody.develop_self_learning_score; - evaluate.develop_training_seminar_score = - requestBody.develop_training_seminar_score; - evaluate.develop_other_training_score = - requestBody.develop_other_training_score; - evaluate.develop_orientation_percent = - requestBody.develop_orientation_percent; - evaluate.develop_self_learning_percent = - requestBody.develop_self_learning_percent; - evaluate.develop_training_seminar_percent = - requestBody.develop_training_seminar_percent; - evaluate.develop_other_training_percent = - requestBody.develop_other_training_percent; - evaluate.develop_result = requestBody.develop_result; - evaluate.achievement_score = requestBody.achievement_score; - evaluate.achievement_score_total = requestBody.achievement_score_total; - evaluate.achievement_percent = requestBody.achievement_percent; - evaluate.achievement_result = requestBody.achievement_result; - evaluate.behavior_score = requestBody.behavior_score; - evaluate.behavior_score_total = requestBody.behavior_score_total; - evaluate.behavior_percent = requestBody.behavior_percent; - evaluate.behavior_result = requestBody.behavior_result; - evaluate.sum_score = requestBody.sum_score; - evaluate.sum_percent = requestBody.sum_percent; - evaluate.evaluate_result = requestBody.evaluate_result; - - evaluate.updateUserId = request.user.sub; - evaluate.updateFullName = request.user.name; - - await this.evaluateChairmanRepository.save(evaluate, { data: request }); - setLogDataDiff(request, { before, after: evaluate }); - - return new HttpSuccess(); } } diff --git a/src/controllers/EvaluateController.ts b/src/controllers/EvaluateController.ts index 26c675b..63fba47 100644 --- a/src/controllers/EvaluateController.ts +++ b/src/controllers/EvaluateController.ts @@ -1,349 +1,466 @@ -import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Post, Body, Query, Put } from "tsoa" -import HttpSuccess from "../interfaces/http-success" -import HttpStatusCode from "../interfaces/http-status" -import { RequestWithUser } from "../middlewares/user" -import { findEndDate, setLogDataDiff } from "../interfaces/utils" -import { AppDataSource } from "../database/data-source" -import { AssignDirector } from "../entities/AssignDirector" -import HttpError from "../interfaces/http-error" -import { Assign } from "../entities/Assign" -import { CreateEvaluateCommander, EvaluateCommander } from "../entities/EvaluateCommander" -import { Personal } from "../entities/Personal" -import CallAPI from "../interfaces/call-api" -import permission from "../interfaces/permission" +import { + Controller, + Route, + Security, + Tags, + Request, + SuccessResponse, + Response, + Get, + Post, + Body, + Query, + Put, +} from "tsoa"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatusCode from "../interfaces/http-status"; +import { RequestWithUser } from "../middlewares/user"; +import { findEndDate, setLogDataDiff } from "../interfaces/utils"; +import { AppDataSource } from "../database/data-source"; +import { AssignDirector } from "../entities/AssignDirector"; +import HttpError from "../interfaces/http-error"; +import { Assign } from "../entities/Assign"; +import { + CreateEvaluateCommander, + EvaluateCommander, +} from "../entities/EvaluateCommander"; +import { Personal } from "../entities/Personal"; +import CallAPI from "../interfaces/call-api"; +import permission from "../interfaces/permission"; @Route("api/v1/probation/evaluate") @Tags("แบบประเมินผล (ผู้บังคับบัญชา)") @Security("bearerAuth") -@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") +@Response( + HttpStatusCode.INTERNAL_SERVER_ERROR, + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง" +) export class EvaluateController extends Controller { - private assignDirectorRepository = AppDataSource.getRepository(AssignDirector) - private assignRepository = AppDataSource.getRepository(Assign) - private evaluateCommanderRepository = AppDataSource.getRepository(EvaluateCommander) - private personalRepository = AppDataSource.getRepository(Personal) + private assignDirectorRepository = + AppDataSource.getRepository(AssignDirector); + private assignRepository = AppDataSource.getRepository(Assign); + private evaluateCommanderRepository = + AppDataSource.getRepository(EvaluateCommander); + private personalRepository = AppDataSource.getRepository(Personal); - /** - * API ข้อมูลตอนกดสร้างแบบประเมินผล (ผู้บังคับบัญชา) - * - * @summary ข้อมูลตอนกดสร้างแบบประเมินผล (ผู้บังคับบัญชา) - * - */ - @Get("create") - async CreateEvaluate(@Query() assign_id: string, @Request() request: RequestWithUser) { - let _workflow = await new permission().Workflow(request, assign_id, "SYS_PROBATION") - if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION") + /** + * API ข้อมูลตอนกดสร้างแบบประเมินผล (ผู้บังคับบัญชา) + * + * @summary ข้อมูลตอนกดสร้างแบบประเมินผล (ผู้บังคับบัญชา) + * + */ + @Get("create") + async CreateEvaluate( + @Query() assign_id: string, + @Request() request: RequestWithUser + ) { + try { + let _workflow = await new permission().Workflow( + request, + assign_id, + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "commander", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } - const director_id = director.personal_id + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "commander", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + const director_id = director.personal_id; - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }) - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } - const profile = await (assign.profile - ? { - ...assign.profile, - id: assign.profile.personal_id, - name: assign.profile.prefixName + assign.profile.firstName + " " + assign.profile.lastName, - Oc: assign.profile.organization, - } - : null) + const profile = await (assign.profile + ? { + ...assign.profile, + id: assign.profile.personal_id, + name: + assign.profile.prefixName + + assign.profile.firstName + + " " + + assign.profile.lastName, + Oc: assign.profile.organization, + } + : null); - const evaluate_amount = await this.evaluateCommanderRepository.count({ - where: { - assign_id, - director_id, - }, - }) - const evaluate_no = await (evaluate_amount + 1) - const start_date = evaluate_amount == 0 ? assign.date_start : findEndDate(evaluate_amount * 3, assign.date_start) + const evaluate_amount = await this.evaluateCommanderRepository.count({ + where: { + assign_id, + director_id, + }, + }); + const evaluate_no = await (evaluate_amount + 1); + const start_date = + evaluate_amount == 0 + ? assign.date_start + : findEndDate(evaluate_amount * 3, assign.date_start); - const commanderData = await this.assignDirectorRepository.findOne({ - select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], - where: { personal_id: director_id }, - }) - if (!commanderData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้บังคับบัญชา") - } - const commander = await { - ...commanderData, - name: commanderData.fullname, - label: `${commanderData.fullname} (${commanderData.position}${commanderData.posLevel})`, - } + const commanderData = await this.assignDirectorRepository.findOne({ + select: [ + "personal_id", + "dated", + "fullname", + "position", + "posType", + "posLevel", + ], + where: { personal_id: director_id }, + }); + if (!commanderData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลผู้บังคับบัญชา" + ); + } + const commander = await { + ...commanderData, + name: commanderData.fullname, + label: `${commanderData.fullname} (${commanderData.position}${commanderData.posLevel})`, + }; - return new HttpSuccess({ - person: profile, - assign, - evaluate_no: evaluate_no, - start_date: start_date, - end_date: findEndDate(3, start_date), - director: commander, - }) - } + return new HttpSuccess({ + person: profile, + assign, + evaluate_no: evaluate_no, + start_date: start_date, + end_date: findEndDate(3, start_date), + director: commander, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - /** - * API ข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) - * - * @summary ข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) - * - */ - @Get("") - async GetEvaluate(@Request() request: RequestWithUser, @Query() assign_id: string, @Query() evaluate_no?: string) { - await new permission().PermissionGet(request, "SYS_PROBATION") + /** + * API ข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) + * + * @summary ข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) + * + */ + @Get("") + async GetEvaluate( + @Request() request: RequestWithUser, + @Query() assign_id: string, + @Query() evaluate_no?: string + ) { + try { + await new permission().PermissionGet(request, "SYS_PROBATION"); - // ต้องปรับเป็น id ของคนที่ access เข้ามา - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "commander", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } - const director_id = director.personal_id - let evaluate: any = null - if (evaluate_no) { - evaluate = await this.evaluateCommanderRepository.findOne({ - where: { - director_id, - assign_id, - no: evaluate_no, - }, - }) - } else { - evaluate = await this.evaluateCommanderRepository.find({ - where: { - director_id, - assign_id, - }, - }) + // ต้องปรับเป็น id ของคนที่ access เข้ามา + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "commander", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + const director_id = director.personal_id; + let evaluate: any = null; + if (evaluate_no) { + evaluate = await this.evaluateCommanderRepository.findOne({ + where: { + director_id, + assign_id, + no: evaluate_no, + }, + }); + } else { + evaluate = await this.evaluateCommanderRepository.find({ + where: { + director_id, + assign_id, + }, + }); - if (evaluate) - evaluate = await evaluate.map((element: EvaluateCommander) => ({ - ...element, - no: Number(element.no), - })) - } + if (evaluate) + evaluate = await evaluate.map((element: EvaluateCommander) => ({ + ...element, + no: Number(element.no), + })); + } - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบประเมิน") - } + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบประเมิน"); + } - const assign = await this.assignRepository.findOne({ - where: { id: assign_id }, - }) - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } + const assign = await this.assignRepository.findOne({ + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } - // const profile = await (assign.profile - // ? { - // ...assign.profile, - // id: assign.profile.personal_id, - // name: - // assign.profile.prefixName + - // assign.profile.firstName + - // " " + - // assign.profile.lastName, - // Oc: assign.profile.organization, - // } - // : null); + // const profile = await (assign.profile + // ? { + // ...assign.profile, + // id: assign.profile.personal_id, + // name: + // assign.profile.prefixName + + // assign.profile.firstName + + // " " + + // assign.profile.lastName, + // Oc: assign.profile.organization, + // } + // : null); - // const evaluate_amount = await this.evaluateCommanderRepository.count({ - // where: { - // assign_id, - // director_id, - // }, - // }); - // const evaluate_no = await (evaluate_amount + 1); - // const start_date = - // evaluate_amount == 0 - // ? assign.date_start - // : findEndDate(evaluate_amount * 3, assign.date_start); + // const evaluate_amount = await this.evaluateCommanderRepository.count({ + // where: { + // assign_id, + // director_id, + // }, + // }); + // const evaluate_no = await (evaluate_amount + 1); + // const start_date = + // evaluate_amount == 0 + // ? assign.date_start + // : findEndDate(evaluate_amount * 3, assign.date_start); - const directorData = await this.assignDirectorRepository.find({ - select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], - where: { personal_id: director_id }, - }) + const directorData = await this.assignDirectorRepository.find({ + select: [ + "personal_id", + "dated", + "fullname", + "position", + "posType", + "posLevel", + ], + where: { personal_id: director_id }, + }); - const directors = await directorData.map(element => ({ - ...element, - name: element.fullname, - label: `${element.fullname} (${element.position}${element.posLevel})`, - })) + const directors = await directorData.map((element) => ({ + ...element, + name: element.fullname, + label: `${element.fullname} (${element.position}${element.posLevel})`, + })); - const experimenteeData = await this.personalRepository.find({ - select: ["personal_id", "prefixName", "firstName", "lastName", "positionName", "positionLevelName", "organization"], - where: { personal_id: assign.personal_id }, - }) + const experimenteeData = await this.personalRepository.find({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "organization", + ], + where: { personal_id: assign.personal_id }, + }); - const experimentee = await experimenteeData.map(element => ({ - ...element, - name: element.prefixName + element.firstName + " " + element.lastName, - Oc: element.organization, - })) + const experimentee = await experimenteeData.map((element) => ({ + ...element, + name: element.prefixName + element.firstName + " " + element.lastName, + Oc: element.organization, + })); - return new HttpSuccess({ - experimentee: experimentee, - director: directors ? directors : null, - assign, - evaluate, - }) - } + return new HttpSuccess({ + experimentee: experimentee, + director: directors ? directors : null, + assign, + evaluate, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - /** - * API บันทึกข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) - * - * @summary บันทึกข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) - * - */ - @Post("") - async PostData(@Query() assign_id: string, @Body() requestBody: CreateEvaluateCommander, @Request() request: RequestWithUser) { - await new permission().PermissionUpdate(request, "SYS_PROBATION") + /** + * API บันทึกข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) + * + * @summary บันทึกข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) + * + */ + @Post("") + async PostData( + @Query() assign_id: string, + @Body() requestBody: CreateEvaluateCommander, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "commander", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "commander", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } - const director_id = director.personal_id + const director_id = director.personal_id; - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }) - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } - const postData: any = await { - assign_id, - ...requestBody, - director_id, - no: requestBody.evaluate_no, - date_start: requestBody.start_date, - personal_id: assign.personal_id, + const postData: any = await { + assign_id, + ...requestBody, + director_id, + no: requestBody.evaluate_no, + date_start: requestBody.start_date, + personal_id: assign.personal_id, - achievement_other_desc: requestBody.achievement_other ? requestBody.achievement_other.text : "", - achievement_other_level: requestBody.achievement_other ? Number(requestBody.achievement_other.level) : 0, - behavior_other_desc: requestBody.behavior_orther.text, - behavior_other_level: requestBody.behavior_orther.text != "" ? Number(requestBody.behavior_orther.level) : 0, + achievement_other_desc: requestBody.achievement_other + ? requestBody.achievement_other.text + : "", + achievement_other_level: requestBody.achievement_other + ? Number(requestBody.achievement_other.level) + : 0, + behavior_other_desc: requestBody.behavior_orther.text, + behavior_other_level: + requestBody.behavior_orther.text != "" + ? Number(requestBody.behavior_orther.level) + : 0, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - } + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; - await this.evaluateCommanderRepository.save(postData, { - data: request, - }) - setLogDataDiff(request, { before: null, after: postData }) + await this.evaluateCommanderRepository.save(postData, { + data: request, + }); + setLogDataDiff(request, { before: null, after: postData }); - if (Number(requestBody.evaluate_no) < 2) { - // #noted cronjob - // แจ้งผู้บังคับบัญชาเข้ามาบันทึกผลทุก 3 เดือน 2 ครั้ง - var dateSend = await findEndDate(3, requestBody.start_date) - const nextNo = await (Number(requestBody.evaluate_no) + 1) - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, - body: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการ (สำหรับผู้บังคับบัญชา) ครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, - receiverUserId: director_id, - payload: "", - isSendMail: true, - isSendInbox: true, - receiveDate: dateSend, - }) - .catch(error => { - console.error("Error calling API:", error) - }) - } + if (Number(requestBody.evaluate_no) < 2) { + // #noted cronjob + // แจ้งผู้บังคับบัญชาเข้ามาบันทึกผลทุก 3 เดือน 2 ครั้ง + var dateSend = await findEndDate(3, requestBody.start_date); + const nextNo = await (Number(requestBody.evaluate_no) + 1); + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, + body: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการ (สำหรับผู้บังคับบัญชา) ครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, + receiverUserId: director_id, + payload: "", + isSendMail: true, + isSendInbox: true, + receiveDate: dateSend, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + } - return new HttpSuccess() - } + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - /** - * API แก้ไขข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) - * - * @summary แก้ไขข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) - * - */ - @Put("") - async UpdateData( - // @Query() assign_id: string, - @Query() evaluate_id: string, - @Body() requestBody: CreateEvaluateCommander, - @Request() request: RequestWithUser - ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION") + /** + * API แก้ไขข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) + * + * @summary แก้ไขข้อมูลแบบประเมินผล (ผู้บังคับบัญชา) + * + */ + @Put("") + async UpdateData( + // @Query() assign_id: string, + @Query() evaluate_id: string, + @Body() requestBody: CreateEvaluateCommander, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - let evaluate = await this.evaluateCommanderRepository.findOne({ - where: { id: evaluate_id }, - }) + let evaluate = await this.evaluateCommanderRepository.findOne({ + where: { id: evaluate_id }, + }); - const before = evaluate + const before = evaluate; - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน") - } + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน"); + } - evaluate.commander_dated = requestBody.commander_dated - evaluate.knowledge_level = requestBody.knowledge_level - evaluate.skill_level = requestBody.skill_level - evaluate.competency_level = requestBody.competency_level - evaluate.learn_level = requestBody.learn_level - evaluate.apply_level = requestBody.apply_level - evaluate.success_level = requestBody.success_level - evaluate.achievement_other_desc = requestBody.achievement_other ? requestBody.achievement_other.text : "" - evaluate.achievement_other_level = requestBody.achievement_other.text != "" ? Number(requestBody.achievement_other.level) : 0 + evaluate.commander_dated = requestBody.commander_dated; + evaluate.knowledge_level = requestBody.knowledge_level; + evaluate.skill_level = requestBody.skill_level; + evaluate.competency_level = requestBody.competency_level; + evaluate.learn_level = requestBody.learn_level; + evaluate.apply_level = requestBody.apply_level; + evaluate.success_level = requestBody.success_level; + evaluate.achievement_other_desc = requestBody.achievement_other + ? requestBody.achievement_other.text + : ""; + evaluate.achievement_other_level = + requestBody.achievement_other.text != "" + ? Number(requestBody.achievement_other.level) + : 0; - evaluate.conduct1_level = requestBody.conduct1_level - evaluate.conduct2_level = requestBody.conduct2_level - evaluate.conduct3_level = requestBody.conduct3_level - evaluate.conduct4_level = requestBody.conduct4_level - evaluate.moral1_level = requestBody.moral1_level - evaluate.moral2_level = requestBody.moral2_level - evaluate.moral3_level = requestBody.moral3_level - evaluate.discipline1_level = requestBody.discipline1_level - evaluate.discipline2_level = requestBody.discipline2_level - evaluate.discipline3_level = requestBody.discipline3_level - evaluate.discipline4_level = requestBody.discipline4_level - evaluate.discipline5_level = requestBody.discipline5_level - evaluate.behavior_other_desc = requestBody.behavior_orther.text - evaluate.behavior_other_level = requestBody.behavior_orther.text != "" ? Number(requestBody.behavior_orther.level) : 0 - evaluate.behavior_strength_desc = requestBody.behavior_strength_desc - evaluate.behavior_improve_desc = requestBody.behavior_improve_desc - evaluate.orientation = requestBody.orientation - evaluate.self_learning = requestBody.self_learning - evaluate.training_seminar = requestBody.training_seminar - evaluate.other_training = requestBody.other_training - evaluate.updateUserId = request.user.sub - evaluate.updateFullName = request.user.name + evaluate.conduct1_level = requestBody.conduct1_level; + evaluate.conduct2_level = requestBody.conduct2_level; + evaluate.conduct3_level = requestBody.conduct3_level; + evaluate.conduct4_level = requestBody.conduct4_level; + evaluate.moral1_level = requestBody.moral1_level; + evaluate.moral2_level = requestBody.moral2_level; + evaluate.moral3_level = requestBody.moral3_level; + evaluate.discipline1_level = requestBody.discipline1_level; + evaluate.discipline2_level = requestBody.discipline2_level; + evaluate.discipline3_level = requestBody.discipline3_level; + evaluate.discipline4_level = requestBody.discipline4_level; + evaluate.discipline5_level = requestBody.discipline5_level; + evaluate.behavior_other_desc = requestBody.behavior_orther.text; + evaluate.behavior_other_level = + requestBody.behavior_orther.text != "" + ? Number(requestBody.behavior_orther.level) + : 0; + evaluate.behavior_strength_desc = requestBody.behavior_strength_desc; + evaluate.behavior_improve_desc = requestBody.behavior_improve_desc; + evaluate.orientation = requestBody.orientation; + evaluate.self_learning = requestBody.self_learning; + evaluate.training_seminar = requestBody.training_seminar; + evaluate.other_training = requestBody.other_training; + evaluate.updateUserId = request.user.sub; + evaluate.updateFullName = request.user.name; - await this.evaluateCommanderRepository.save(evaluate, { data: request }) - setLogDataDiff(request, { before, after: evaluate }) + await this.evaluateCommanderRepository.save(evaluate, { data: request }); + setLogDataDiff(request, { before, after: evaluate }); - return new HttpSuccess() - } + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } } diff --git a/src/controllers/EvaluateRecordController.ts b/src/controllers/EvaluateRecordController.ts index 9a79338..7b3cce0 100644 --- a/src/controllers/EvaluateRecordController.ts +++ b/src/controllers/EvaluateRecordController.ts @@ -1,1062 +1,1357 @@ -import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Post, Body, Query, Put } from "tsoa" -import HttpSuccess from "../interfaces/http-success" -import HttpStatusCode from "../interfaces/http-status" -import { RequestWithUser } from "../middlewares/user" -import { findEndDate, setLogDataDiff } from "../interfaces/utils" -import { AppDataSource } from "../database/data-source" -import { AssignDirector } from "../entities/AssignDirector" -import HttpError from "../interfaces/http-error" -import { Assign } from "../entities/Assign" -import { Personal } from "../entities/Personal" -import { AssignOutput } from "../entities/AssignOutput" -import { CreateEvaluateAssessor, EvaluateAssessor } from "../entities/EvaluateAssessor" -import { CreateEvaluateAchievement, EvaluateAchievement } from "../entities/EvaluateAchievement" -import CallAPI from "../interfaces/call-api" -import permission from "../interfaces/permission" +import { + Controller, + Route, + Security, + Tags, + Request, + SuccessResponse, + Response, + Get, + Post, + Body, + Query, + Put, +} from "tsoa"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatusCode from "../interfaces/http-status"; +import { RequestWithUser } from "../middlewares/user"; +import { findEndDate, setLogDataDiff } from "../interfaces/utils"; +import { AppDataSource } from "../database/data-source"; +import { AssignDirector } from "../entities/AssignDirector"; +import HttpError from "../interfaces/http-error"; +import { Assign } from "../entities/Assign"; +import { Personal } from "../entities/Personal"; +import { AssignOutput } from "../entities/AssignOutput"; +import { + CreateEvaluateAssessor, + EvaluateAssessor, +} from "../entities/EvaluateAssessor"; +import { + CreateEvaluateAchievement, + EvaluateAchievement, +} from "../entities/EvaluateAchievement"; +import CallAPI from "../interfaces/call-api"; +import permission from "../interfaces/permission"; @Route("api/v1/probation/evaluate-record") @Tags("แบบบันทึกผล") @Security("bearerAuth") -@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") +@Response( + HttpStatusCode.INTERNAL_SERVER_ERROR, + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง" +) export class EvaluateRecordController extends Controller { - private assignDirectorRepository = AppDataSource.getRepository(AssignDirector) - private assignRepository = AppDataSource.getRepository(Assign) - private personalRepository = AppDataSource.getRepository(Personal) - private assignOutputRepository = AppDataSource.getRepository(AssignOutput) - private evaluateAssessorRepository = AppDataSource.getRepository(EvaluateAssessor) - private evaluateAchievementRepository = AppDataSource.getRepository(EvaluateAchievement) - - /** - * API ดึงข้อมูลตอนกดสร้างแบบบันทึกผล - * - * @summary get ข้อมูลตอนกดสร้างแบบบันทึกผล - * - */ - @Get("create") - async GetCreate(@Query() assign_id: string, @Request() request: RequestWithUser) { - let _workflow = await new permission().Workflow(request, assign_id, "SYS_PROBATION") - if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION") - - const directorData = await this.assignDirectorRepository.findOne({ - select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], - where: { - assign_id, - role: "mentor", - }, - }) - - if (!directorData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } - - const director = await { - ...directorData, - name: directorData.fullname, - label: `${directorData.fullname} (${directorData.position}, ${directorData.posType}: ${directorData.posLevel})`, - } - - const director_id = director.personal_id - - const assign = await this.assignRepository.findOne({ - where: { - id: assign_id, - }, - }) - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } - - const profileData = await this.personalRepository.findOne({ - select: ["personal_id", "prefixName", "firstName", "lastName", "positionName", "positionLevelName", "organization"], - where: { - personal_id: assign.personal_id, - }, - }) - if (!profileData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล") - } - - const profile = await { - id: profileData.personal_id, - name: profileData.prefixName + profileData.firstName + " " + profileData.lastName, - positionName: profileData.positionName, - positionLevelName: profileData.positionLevelName, - Oc: profileData.organization, - } - - const output = await this.assignOutputRepository.find({ - select: ["id", "output_desc"], - where: { - assign_id, - }, - order: { id: "ASC" }, - }) - - const evaluate_amount = await this.evaluateAssessorRepository.count({ - where: { - assign_id, - director_id, - }, - }) - - const evaluate_no = await (evaluate_amount + 1) - const start_date = await (evaluate_amount == 0 ? assign.date_start : findEndDate(evaluate_amount * 2, assign.date_start)) - - var commanderData = await this.assignDirectorRepository.findOne({ - select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], - where: { personal_id: director_id }, - }) - - if (!commanderData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้บังคับบัญชา") - } - - const commander = await { - ...commanderData, - name: commanderData.fullname, - label: `${commanderData.fullname} (${commanderData.position}${commanderData.posLevel})`, - } - - return new HttpSuccess({ - person: profile, - assign, - assign_output: output, - evaluate_no, - start_date, - end_date: findEndDate(2, start_date), - director: commander, - }) - } - - /** - * API ข้อมูลแบบบันทึกผล(ผู้ดูแล) - * - * @summary ข้อมูลแบบบันทึกผล(ผู้ดูแล) - * - */ - @Get("") - async GetData(@Request() request: RequestWithUser, @Query() assign_id: string, @Query() evaluate_no?: string) { - await new permission().PermissionGet(request, "SYS_PROBATION") - - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "mentor", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } - - const director_id = director.personal_id - - let evaluate: any = null - let evaluateData: any = [] - if (evaluate_no) { - evaluate = await this.evaluateAssessorRepository.findOne({ - where: { - director_id, - assign_id, - no: evaluate_no, - }, - }) - - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบประเมิน") - } - - const achievementData = await this.evaluateAchievementRepository.find({ - select: ["output_desc", "evaluate_expect_level", "output_desc", "evaluate_output_level"], - where: { - evaluate_id: evaluate.id, - }, - order: { output_id: "ASC" }, - }) - if (!achievementData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } - - const achievements = await achievementData.map(achievement => { - return { - ...achievement, - evaluate_expect_desc: achievement.output_desc, - evaluate_output_desc: achievement.output_desc, - } - }) - - evaluateData = await { - id: evaluate.id, - director_id: evaluate.director_id, - assign_id, - no: Number(evaluate.no), - date_start: evaluate.date_start, - date_finish: evaluate.date_finish, - assessor_dated: evaluate.assessor_dated, - knowledge_level: evaluate.knowledge_level, - skill_level: evaluate.skill_level, - competency_level: evaluate.competency_level, - learn_level: evaluate.learn_level, - apply_level: evaluate.apply_level, - achievement_other_desc: evaluate.achievement_other_desc, - achievement_other_level: evaluate.achievement_other_level, - achievement_strength_desc: evaluate.achievement_strength_desc, - achievement_improve_desc: evaluate.achievement_improve_desc, - conduct1_level: evaluate.conduct1_level, - conduct2_level: evaluate.conduct2_level, - conduct3_level: evaluate.conduct3_level, - conduct4_level: evaluate.conduct4_level, - moral1_level: evaluate.moral1_level, - moral2_level: evaluate.moral2_level, - moral3_level: evaluate.moral3_level, - discipline1_level: evaluate.discipline1_level, - discipline2_level: evaluate.discipline2_level, - discipline3_level: evaluate.discipline3_level, - discipline4_level: evaluate.discipline4_level, - discipline5_level: evaluate.discipline5_level, - behavior_other_desc: evaluate.behavior_other_desc, - behavior_other_level: evaluate.behavior_other_level, - behavior_strength_desc: evaluate.behavior_strength_desc, - behavior_improve_desc: evaluate.behavior_improve_desc, - orientation: evaluate.orientation, - self_learning: evaluate.self_learning, - training_seminar: evaluate.training_seminar, - other_training: evaluate.other_training, - createdAt: evaluate.createdAt, - updatedAt: evaluate.updatedAt, - achievements: achievements, - } - } else { - evaluate = await this.evaluateAssessorRepository.find({ - where: { - director_id: director_id, - assign_id, - }, - order: { no: "ASC" }, - }) - - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } - - await Promise.all( - evaluate.map(async (element: any, index: number) => { - const achievementData = await this.evaluateAchievementRepository.find({ - select: ["output_desc", "evaluate_expect_level", "output_desc", "evaluate_output_level"], - where: { - evaluate_id: element.id, - }, - order: { output_id: "ASC" }, - }) - - const achievements = await achievementData.map(achievement => { - return { - ...achievement, - evaluate_expect_desc: achievement.output_desc, - evaluate_output_desc: achievement.output_desc, - } - }) - - evaluateData[index] = await { - id: element.id, - director_id: element.director_id, - assign_id, - no: Number(element.no), - date_start: element.date_start, - date_finish: element.date_finish, - assessor_dated: element.assessor_dated, - knowledge_level: element.knowledge_level, - skill_level: element.skill_level, - competency_level: element.competency_level, - learn_level: element.learn_level, - apply_level: element.apply_level, - achievement_other_desc: element.achievement_other_desc, - achievement_other_level: element.achievement_other_level, - achievement_strength_desc: element.achievement_strength_desc, - achievement_improve_desc: element.achievement_improve_desc, - conduct1_level: element.conduct1_level, - conduct2_level: element.conduct2_level, - conduct3_level: element.conduct3_level, - conduct4_level: element.conduct4_level, - moral1_level: element.moral1_level, - moral2_level: element.moral2_level, - moral3_level: element.moral3_level, - discipline1_level: element.discipline1_level, - discipline2_level: element.discipline2_level, - discipline3_level: element.discipline3_level, - discipline4_level: element.discipline4_level, - discipline5_level: element.discipline5_level, - behavior_other_desc: element.behavior_other_desc, - behavior_other_level: element.behavior_other_level, - behavior_strength_desc: element.behavior_strength_desc, - behavior_improve_desc: element.behavior_improve_desc, - orientation: element.orientation, - self_learning: element.self_learning, - training_seminar: element.training_seminar, - other_training: element.other_training, - createdAt: element.createdAt, - updatedAt: element.updatedAt, - achievements: achievements, - } - }) - ) - } - - const assign = await this.assignRepository.findOne({ - where: { - id: assign_id, - }, - }) - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } - - const experimenteeData = await this.personalRepository.find({ - select: ["personal_id", "prefixName", "firstName", "lastName", "positionName", "positionLevelName", "organization"], - where: { personal_id: assign.personal_id }, - }) - - const experimentee = await experimenteeData.map(element => ({ - ...element, - name: element.prefixName + element.firstName + " " + element.lastName, - Oc: element.organization, - })) - - const directorData = await this.assignDirectorRepository.find({ - select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], - where: { personal_id: director_id }, - }) - - const directors = await directorData.map(element => ({ - ...element, - name: element.fullname, - label: `${element.fullname} (${element.position}${element.posLevel})`, - })) - - return new HttpSuccess({ - experimentee: experimentee ? experimentee : null, - director: directors ? directors : null, - assign, - evaluate: evaluateData, - }) - } - - /** - * API เพิ่มแบบบันทึกผล(ผู้ดูแล) - * - * @summary เพิ่มแบบบันทึกผล(ผู้ดูแล) - * - */ - @Post("") - async PostData(@Query() assign_id: string, @Body() requestBody: CreateEvaluateAssessor, @Request() request: RequestWithUser) { - await new permission().PermissionUpdate(request, "SYS_PROBATION") - - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "mentor", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } - - const director_id = director.personal_id - - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }) - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } - - const postData: any = await { - assign_id, - ...requestBody, - director_id, - no: requestBody.evaluate_no, - date_start: requestBody.start_date, - personal_id: assign.personal_id, - - achievement_other_desc: requestBody.achievement_other ? requestBody.achievement_other.text : "", - achievement_other_level: requestBody.achievement_other ? Number(requestBody.achievement_other.level) : 0, - behavior_other_desc: requestBody.behavio_orther.text, - behavior_other_level: requestBody.behavio_orther.text != "" ? Number(requestBody.behavio_orther.level) : 0, - behavior_strength_desc: requestBody.behavior_strength_desc, - behavior_improve_desc: requestBody.behavior_improve_desc, - orientation: requestBody.orientation, - self_learning: requestBody.self_learning, - training_seminar: requestBody.training_seminar, - other_training: requestBody.other_training, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - } - - const evaluateAssessor = await this.evaluateAssessorRepository.save(postData, { - data: request, - }) - - if (evaluateAssessor) { - await Promise.all( - requestBody.evaluate_expenct_level.map(async (expenct, index) => { - const evaluateAchievement: CreateEvaluateAchievement = await { - evaluate_id: evaluateAssessor.id, - assign_id, - output_id: expenct.id.toString(), - - assessor_id: director_id, - evaluate_expect_level: Number(expenct.level), - output_desc: requestBody.evaluate_ouptut[index].text, - evaluate_output_level: Number(requestBody.evaluate_ouptut[index].level), - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - } - await this.evaluateAchievementRepository.save(evaluateAchievement, { - data: request, - }) - }) - ) - } - - setLogDataDiff(request, { before: null, after: postData }) - - if (Number(requestBody.evaluate_no) < 3) { - // #noted cronjob - // แจ้งผู้ดูแลและผู้บังคับบัญชาเข้ามาบันทึกผลทุก 2 เดือน 3 ครั้ง - const dateSaveForm = await findEndDate(2, requestBody.start_date) - const nextNo = await (Number(requestBody.evaluate_no) + 1) - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, - body: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, - receiverUserId: director_id, - payload: "", - isSendMail: true, - isSendInbox: true, - receiveDate: dateSaveForm, - }) - .catch(error => { - console.error("Error calling API:", error) - }) - } - - return new HttpSuccess() - } - - /** - * API แก้ไขข้อมูลแบบบันทึกผล(ผู้ดูแล) - * - * @summary แก้ไขข้อมูลแบบบันทึกผล(ผู้ดูแล) - * - */ - @Put("") - async UpdateData(@Query() assign_id: string, @Query() evaluate_id: string, @Body() requestBody: CreateEvaluateAssessor, @Request() request: RequestWithUser) { - await new permission().PermissionUpdate(request, "SYS_PROBATION") - - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "mentor", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } - - const director_id = director.personal_id - - let evaluate = await this.evaluateAssessorRepository.findOne({ - where: { id: evaluate_id }, - }) - - const before = evaluate - - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน") - } - - evaluate.assessor_dated = requestBody.assessor_dated - evaluate.knowledge_level = requestBody.knowledge_level - evaluate.skill_level = requestBody.skill_level - evaluate.competency_level = requestBody.competency_level - evaluate.learn_level = requestBody.learn_level - evaluate.apply_level = requestBody.apply_level - evaluate.achievement_other_desc = requestBody.achievement_other ? requestBody.achievement_other.text : "" - evaluate.achievement_other_level = requestBody.achievement_other.text != "" ? Number(requestBody.achievement_other.level) : 0 - - evaluate.achievement_strength_desc = requestBody.achievement_strength_desc - evaluate.achievement_improve_desc = requestBody.achievement_improve_desc - evaluate.conduct1_level = requestBody.conduct1_level - evaluate.conduct2_level = requestBody.conduct2_level - evaluate.conduct3_level = requestBody.conduct3_level - evaluate.conduct4_level = requestBody.conduct4_level - evaluate.moral1_level = requestBody.moral1_level - evaluate.moral2_level = requestBody.moral2_level - evaluate.moral3_level = requestBody.moral3_level - evaluate.discipline1_level = requestBody.discipline1_level - evaluate.discipline2_level = requestBody.discipline2_level - evaluate.discipline3_level = requestBody.discipline3_level - evaluate.discipline4_level = requestBody.discipline4_level - evaluate.discipline5_level = requestBody.discipline5_level - evaluate.behavior_other_desc = requestBody.behavio_orther.text - evaluate.behavior_other_level = requestBody.behavio_orther.text != "" ? Number(requestBody.behavio_orther.level) : 0 - evaluate.behavior_strength_desc = requestBody.behavior_strength_desc - evaluate.behavior_improve_desc = requestBody.behavior_improve_desc - evaluate.orientation = requestBody.orientation - evaluate.self_learning = requestBody.self_learning - evaluate.training_seminar = requestBody.training_seminar - evaluate.other_training = requestBody.other_training - evaluate.updateUserId = request.user.sub - evaluate.updateFullName = request.user.name - - const evaluateAssessor = await this.evaluateAssessorRepository.save(evaluate, { - data: request, - }) - - if (evaluateAssessor) { - await this.evaluateAchievementRepository.delete({ - evaluate_id, - }) - await Promise.all( - requestBody.evaluate_expenct_level.map(async (expenct, index) => { - const evaluateAchievement: CreateEvaluateAchievement = await { - evaluate_id: evaluateAssessor.id, - assign_id, - output_id: expenct.id.toString(), - assessor_id: director_id, - evaluate_expect_level: Number(expenct.level), - output_desc: requestBody.evaluate_ouptut[index].text, - evaluate_output_level: Number(requestBody.evaluate_ouptut[index].level), - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - } - await this.evaluateAchievementRepository.save(evaluateAchievement, { - data: request, - }) - }) - ) - } - - setLogDataDiff(request, { before, after: evaluate }) - - return new HttpSuccess() - } - - /** - * API ดึงข้อมูลตอนกดสร้างแบบบันทึกผล (ผู้บังคัญบัญชา) - * - * @summary get ข้อมูลตอนกดสร้างแบบบันทึกผล (ผู้บังคัญบัญชา) - * - */ - @Get("create/commander") - async GetCreateCommander(@Query() assign_id: string, @Request() request: RequestWithUser) { - let _workflow = await new permission().Workflow(request, assign_id, "SYS_PROBATION") - if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION") - - const directorData = await this.assignDirectorRepository.findOne({ - select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], - where: { - assign_id, - role: "commander", - }, - }) - - if (!directorData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } - - const director = await { - ...directorData, - name: directorData.fullname, - label: `${directorData.fullname} (${directorData.position}${directorData.posLevel})`, - } - - const director_id = director.personal_id - - const assign = await this.assignRepository.findOne({ - where: { - id: assign_id, - }, - }) - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } - - const profileData = await this.personalRepository.findOne({ - select: ["personal_id", "prefixName", "firstName", "lastName", "positionName", "positionLevelName", "organization"], - where: { - personal_id: assign.personal_id, - }, - }) - if (!profileData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล") - } - - const profile = await { - id: profileData.personal_id, - name: profileData.prefixName + profileData.firstName + " " + profileData.lastName, - positionName: profileData.positionName, - positionLevelName: profileData.positionLevelName, - Oc: profileData.organization, - } - - const output = await this.assignOutputRepository.find({ - select: ["id", "output_desc"], - where: { - assign_id, - }, - order: { id: "ASC" }, - }) - - const evaluate_amount = await this.evaluateAssessorRepository.count({ - where: { - assign_id, - director_id, - }, - }) - - const evaluate_no = await (evaluate_amount + 1) - const start_date = await (evaluate_amount == 0 ? assign.date_start : findEndDate(evaluate_amount * 2, assign.date_start)) - - return new HttpSuccess({ - person: profile, - assign, - assign_output: output, - evaluate_no, - start_date, - end_date: findEndDate(2, start_date), - director, - }) - } - - /** - * API ข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) - * - * @summary ข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) - * - */ - @Get("commander") - async GetDataCommander(@Request() request: RequestWithUser, @Query() assign_id: string, @Query() evaluate_no?: string) { - await new permission().PermissionGet(request, "SYS_PROBATION") - - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "commander", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } - - const director_id = director.personal_id - - let evaluate: any = null - let evaluateData: any = [] - if (evaluate_no) { - evaluate = await this.evaluateAssessorRepository.findOne({ - where: { - director_id, - assign_id, - no: evaluate_no, - }, - }) - - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบประเมิน") - } - - const achievementData = await this.evaluateAchievementRepository.find({ - select: ["output_desc", "evaluate_expect_level", "output_desc", "evaluate_output_level"], - where: { - evaluate_id: evaluate.id, - }, - order: { output_id: "ASC" }, - }) - if (!achievementData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } - - const achievements = await achievementData.map(achievement => { - return { - ...achievement, - evaluate_expect_desc: achievement.output_desc, - evaluate_output_desc: achievement.output_desc, - } - }) - - evaluateData = await { - id: evaluate.id, - director_id: evaluate.director_id, - assign_id, - no: Number(evaluate.no), - date_start: evaluate.date_start, - date_finish: evaluate.date_finish, - assessor_dated: evaluate.assessor_dated, - knowledge_level: evaluate.knowledge_level, - skill_level: evaluate.skill_level, - competency_level: evaluate.competency_level, - learn_level: evaluate.learn_level, - apply_level: evaluate.apply_level, - achievement_other_desc: evaluate.achievement_other_desc, - achievement_other_level: evaluate.achievement_other_level, - achievement_strength_desc: evaluate.achievement_strength_desc, - achievement_improve_desc: evaluate.achievement_improve_desc, - conduct1_level: evaluate.conduct1_level, - conduct2_level: evaluate.conduct2_level, - conduct3_level: evaluate.conduct3_level, - conduct4_level: evaluate.conduct4_level, - moral1_level: evaluate.moral1_level, - moral2_level: evaluate.moral2_level, - moral3_level: evaluate.moral3_level, - discipline1_level: evaluate.discipline1_level, - discipline2_level: evaluate.discipline2_level, - discipline3_level: evaluate.discipline3_level, - discipline4_level: evaluate.discipline4_level, - discipline5_level: evaluate.discipline5_level, - behavior_other_desc: evaluate.behavior_other_desc, - behavior_other_level: evaluate.behavior_other_level, - behavior_strength_desc: evaluate.behavior_strength_desc, - behavior_improve_desc: evaluate.behavior_improve_desc, - orientation: evaluate.orientation, - self_learning: evaluate.self_learning, - training_seminar: evaluate.training_seminar, - other_training: evaluate.other_training, - createdAt: evaluate.createdAt, - updatedAt: evaluate.updatedAt, - achievements: achievements, - } - } else { - evaluate = await this.evaluateAssessorRepository.find({ - where: { - director_id: director_id, - assign_id, - }, - order: { no: "ASC" }, - }) - - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") - } - - await Promise.all( - evaluate.map(async (element: any, index: number) => { - const achievementData = await this.evaluateAchievementRepository.find({ - select: ["output_desc", "evaluate_expect_level", "output_desc", "evaluate_output_level"], - where: { - evaluate_id: element.id, - }, - order: { output_id: "ASC" }, - }) - - const achievements = await achievementData.map(achievement => { - return { - ...achievement, - evaluate_expect_desc: achievement.output_desc, - evaluate_output_desc: achievement.output_desc, - } - }) - - evaluateData[index] = await { - id: element.id, - director_id: element.director_id, - assign_id, - no: Number(element.no), - date_start: element.date_start, - date_finish: element.date_finish, - assessor_dated: element.assessor_dated, - knowledge_level: element.knowledge_level, - skill_level: element.skill_level, - competency_level: element.competency_level, - learn_level: element.learn_level, - apply_level: element.apply_level, - achievement_other_desc: element.achievement_other_desc, - achievement_other_level: element.achievement_other_level, - achievement_strength_desc: element.achievement_strength_desc, - achievement_improve_desc: element.achievement_improve_desc, - conduct1_level: element.conduct1_level, - conduct2_level: element.conduct2_level, - conduct3_level: element.conduct3_level, - conduct4_level: element.conduct4_level, - moral1_level: element.moral1_level, - moral2_level: element.moral2_level, - moral3_level: element.moral3_level, - discipline1_level: element.discipline1_level, - discipline2_level: element.discipline2_level, - discipline3_level: element.discipline3_level, - discipline4_level: element.discipline4_level, - discipline5_level: element.discipline5_level, - behavior_other_desc: element.behavior_other_desc, - behavior_other_level: element.behavior_other_level, - behavior_strength_desc: element.behavior_strength_desc, - behavior_improve_desc: element.behavior_improve_desc, - orientation: element.orientation, - self_learning: element.self_learning, - training_seminar: element.training_seminar, - other_training: element.other_training, - createdAt: element.createdAt, - updatedAt: element.updatedAt, - achievements: achievements, - } - }) - ) - } - - const assign = await this.assignRepository.findOne({ - where: { - id: assign_id, - }, - }) - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } - - const experimenteeData = await this.personalRepository.find({ - select: ["personal_id", "prefixName", "firstName", "lastName", "positionName", "positionLevelName", "organization"], - where: { personal_id: assign.personal_id }, - }) - - const experimentee = await experimenteeData.map(element => ({ - ...element, - name: element.prefixName + element.firstName + " " + element.lastName, - Oc: element.organization, - })) - - const directorData = await this.assignDirectorRepository.find({ - select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], - where: { personal_id: director_id }, - }) - - const directors = await directorData.map(element => ({ - ...element, - name: element.fullname, - label: `${element.fullname} (${element.position}${element.posLevel})`, - })) - - return new HttpSuccess({ - experimentee: experimentee ? experimentee : null, - person: directors ? directors : null, - assign, - evaluate: evaluateData, - }) - } - - /** - * API บันทึกข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) - * - * @summary บันทึกข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) - * - */ - @Post("commander") - async PostDataCommander(@Query() assign_id: string, @Body() requestBody: CreateEvaluateAssessor, @Request() request: RequestWithUser) { - await new permission().PermissionUpdate(request, "SYS_PROBATION") - - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "commander", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } - - const director_id = director.personal_id - - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }) - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") - } - - const postData: any = await { - assign_id, - ...requestBody, - director_id, - no: requestBody.evaluate_no, - date_start: requestBody.start_date, - personal_id: assign.personal_id, - - achievement_other_desc: requestBody.achievement_other ? requestBody.achievement_other.text : "", - achievement_other_level: requestBody.achievement_other ? Number(requestBody.achievement_other.level) : 0, - behavior_other_desc: requestBody.behavio_orther.text, - behavior_other_level: requestBody.behavio_orther.text != "" ? Number(requestBody.behavio_orther.level) : 0, - behavior_strength_desc: requestBody.behavior_strength_desc, - behavior_improve_desc: requestBody.behavior_improve_desc, - orientation: requestBody.orientation, - self_learning: requestBody.self_learning, - training_seminar: requestBody.training_seminar, - other_training: requestBody.other_training, - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - } - - const evaluateAssessor = await this.evaluateAssessorRepository.save(postData, { - data: request, - }) - if (evaluateAssessor) { - await Promise.all( - requestBody.evaluate_expenct_level.map(async (expenct, index) => { - const evaluateAchievement: CreateEvaluateAchievement = await { - evaluate_id: evaluateAssessor.id, - assign_id, - output_id: expenct.id.toString(), - assessor_id: director_id, - evaluate_expect_level: Number(expenct.level), - output_desc: requestBody.evaluate_ouptut[index].text, - evaluate_output_level: Number(requestBody.evaluate_ouptut[index].level), - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - } - await this.evaluateAchievementRepository.save(evaluateAchievement, { - data: request, - }) - }) - ) - } - - setLogDataDiff(request, { before: null, after: postData }) - - if (Number(requestBody.evaluate_no) < 3) { - // #noted cronjob - // แจ้งผู้ดูแลและผู้บังคับบัญชาเข้ามาบันทึกผลทุก 2 เดือน 3 ครั้ง - const dateSaveForm = await findEndDate(2, requestBody.start_date) - const nextNo = await (Number(requestBody.evaluate_no) + 1) - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, - body: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, - receiverUserId: director_id, - payload: "", - isSendMail: true, - isSendInbox: true, - receiveDate: dateSaveForm, - }) - .catch(error => { - console.error("Error calling API:", error) - }) - } - - return new HttpSuccess() - } - - /** - * API แก้ไขข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) - * @summary แก้ไขข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) - * - */ - @Put("commander") - async UpdateDataCommander(@Query() assign_id: string, @Query() evaluate_id: string, @Body() requestBody: CreateEvaluateAssessor, @Request() request: RequestWithUser) { - await new permission().PermissionUpdate(request, "SYS_PROBATION") - - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "commander", - }, - }) - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") - } - - const director_id = director.personal_id - - let evaluate = await this.evaluateAssessorRepository.findOne({ - where: { id: evaluate_id }, - }) - - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน") - } - const before = evaluate - - evaluate.assessor_dated = requestBody.assessor_dated - evaluate.knowledge_level = requestBody.knowledge_level - evaluate.skill_level = requestBody.skill_level - evaluate.competency_level = requestBody.competency_level - evaluate.learn_level = requestBody.learn_level - evaluate.apply_level = requestBody.apply_level - evaluate.achievement_other_desc = requestBody.achievement_other ? requestBody.achievement_other.text : "" - evaluate.achievement_other_level = requestBody.achievement_other.text != "" ? Number(requestBody.achievement_other.level) : 0 - - evaluate.achievement_strength_desc = requestBody.achievement_strength_desc - evaluate.achievement_improve_desc = requestBody.achievement_improve_desc - evaluate.conduct1_level = requestBody.conduct1_level - evaluate.conduct2_level = requestBody.conduct2_level - evaluate.conduct3_level = requestBody.conduct3_level - evaluate.conduct4_level = requestBody.conduct4_level - evaluate.moral1_level = requestBody.moral1_level - evaluate.moral2_level = requestBody.moral2_level - evaluate.moral3_level = requestBody.moral3_level - evaluate.discipline1_level = requestBody.discipline1_level - evaluate.discipline2_level = requestBody.discipline2_level - evaluate.discipline3_level = requestBody.discipline3_level - evaluate.discipline4_level = requestBody.discipline4_level - evaluate.discipline5_level = requestBody.discipline5_level - evaluate.behavior_other_desc = requestBody.behavio_orther.text - evaluate.behavior_other_level = requestBody.behavio_orther.text != "" ? Number(requestBody.behavio_orther.level) : 0 - evaluate.behavior_strength_desc = requestBody.behavior_strength_desc - evaluate.behavior_improve_desc = requestBody.behavior_improve_desc - evaluate.orientation = requestBody.orientation - evaluate.self_learning = requestBody.self_learning - evaluate.training_seminar = requestBody.training_seminar - evaluate.other_training = requestBody.other_training - evaluate.updateUserId = request.user.sub - evaluate.updateFullName = request.user.name - - const evaluateAssessor = await this.evaluateAssessorRepository.save(evaluate, { - data: request, - }) - - if (evaluateAssessor) { - await this.evaluateAchievementRepository.delete({ - evaluate_id, - }) - await Promise.all( - requestBody.evaluate_expenct_level.map(async (expenct, index) => { - const evaluateAchievement: CreateEvaluateAchievement = await { - evaluate_id: evaluateAssessor.id, - assign_id, - output_id: expenct.id.toString(), - assessor_id: director_id, - evaluate_expect_level: Number(expenct.level), - output_desc: requestBody.evaluate_ouptut[index].text, - evaluate_output_level: Number(requestBody.evaluate_ouptut[index].level), - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - } - await this.evaluateAchievementRepository.save(evaluateAchievement, { - data: request, - }) - }) - ) - } - - setLogDataDiff(request, { before, after: evaluate }) - - return new HttpSuccess() - } + private assignDirectorRepository = + AppDataSource.getRepository(AssignDirector); + private assignRepository = AppDataSource.getRepository(Assign); + private personalRepository = AppDataSource.getRepository(Personal); + private assignOutputRepository = AppDataSource.getRepository(AssignOutput); + private evaluateAssessorRepository = + AppDataSource.getRepository(EvaluateAssessor); + private evaluateAchievementRepository = + AppDataSource.getRepository(EvaluateAchievement); + + /** + * API ดึงข้อมูลตอนกดสร้างแบบบันทึกผล + * + * @summary get ข้อมูลตอนกดสร้างแบบบันทึกผล + * + */ + @Get("create") + async GetCreate( + @Query() assign_id: string, + @Request() request: RequestWithUser + ) { + try { + let _workflow = await new permission().Workflow( + request, + assign_id, + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); + + const directorData = await this.assignDirectorRepository.findOne({ + select: [ + "personal_id", + "dated", + "fullname", + "position", + "posType", + "posLevel", + ], + where: { + assign_id, + role: "mentor", + }, + }); + + if (!directorData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const director = await { + ...directorData, + name: directorData.fullname, + label: `${directorData.fullname} (${directorData.position}, ${directorData.posType}: ${directorData.posLevel})`, + }; + + const director_id = director.personal_id; + + const assign = await this.assignRepository.findOne({ + where: { + id: assign_id, + }, + }); + + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const profileData = await this.personalRepository.findOne({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "organization", + ], + where: { + personal_id: assign.personal_id, + }, + }); + if (!profileData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + const profile = await { + id: profileData.personal_id, + name: + profileData.prefixName + + profileData.firstName + + " " + + profileData.lastName, + positionName: profileData.positionName, + positionLevelName: profileData.positionLevelName, + Oc: profileData.organization, + }; + + const output = await this.assignOutputRepository.find({ + select: ["id", "output_desc"], + where: { + assign_id, + }, + order: { id: "ASC" }, + }); + + const evaluate_amount = await this.evaluateAssessorRepository.count({ + where: { + assign_id, + director_id, + }, + }); + + const evaluate_no = await (evaluate_amount + 1); + const start_date = await (evaluate_amount == 0 + ? assign.date_start + : findEndDate(evaluate_amount * 2, assign.date_start)); + + var commanderData = await this.assignDirectorRepository.findOne({ + select: [ + "personal_id", + "dated", + "fullname", + "position", + "posType", + "posLevel", + ], + where: { personal_id: director_id }, + }); + + if (!commanderData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลผู้บังคับบัญชา" + ); + } + + const commander = await { + ...commanderData, + name: commanderData.fullname, + label: `${commanderData.fullname} (${commanderData.position}${commanderData.posLevel})`, + }; + + return new HttpSuccess({ + person: profile, + assign, + assign_output: output, + evaluate_no, + start_date, + end_date: findEndDate(2, start_date), + director: commander, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } + + /** + * API ข้อมูลแบบบันทึกผล(ผู้ดูแล) + * + * @summary ข้อมูลแบบบันทึกผล(ผู้ดูแล) + * + */ + @Get("") + async GetData( + @Request() request: RequestWithUser, + @Query() assign_id: string, + @Query() evaluate_no?: string + ) { + try { + await new permission().PermissionGet(request, "SYS_PROBATION"); + + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "mentor", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + + const director_id = director.personal_id; + + let evaluate: any = null; + let evaluateData: any = []; + if (evaluate_no) { + evaluate = await this.evaluateAssessorRepository.findOne({ + where: { + director_id, + assign_id, + no: evaluate_no, + }, + }); + + if (!evaluate) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบประเมิน" + ); + } + + const achievementData = await this.evaluateAchievementRepository.find({ + select: [ + "output_desc", + "evaluate_expect_level", + "output_desc", + "evaluate_output_level", + ], + where: { + evaluate_id: evaluate.id, + }, + order: { output_id: "ASC" }, + }); + if (!achievementData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const achievements = await achievementData.map((achievement) => { + return { + ...achievement, + evaluate_expect_desc: achievement.output_desc, + evaluate_output_desc: achievement.output_desc, + }; + }); + + evaluateData = await { + id: evaluate.id, + director_id: evaluate.director_id, + assign_id, + no: Number(evaluate.no), + date_start: evaluate.date_start, + date_finish: evaluate.date_finish, + assessor_dated: evaluate.assessor_dated, + knowledge_level: evaluate.knowledge_level, + skill_level: evaluate.skill_level, + competency_level: evaluate.competency_level, + learn_level: evaluate.learn_level, + apply_level: evaluate.apply_level, + achievement_other_desc: evaluate.achievement_other_desc, + achievement_other_level: evaluate.achievement_other_level, + achievement_strength_desc: evaluate.achievement_strength_desc, + achievement_improve_desc: evaluate.achievement_improve_desc, + conduct1_level: evaluate.conduct1_level, + conduct2_level: evaluate.conduct2_level, + conduct3_level: evaluate.conduct3_level, + conduct4_level: evaluate.conduct4_level, + moral1_level: evaluate.moral1_level, + moral2_level: evaluate.moral2_level, + moral3_level: evaluate.moral3_level, + discipline1_level: evaluate.discipline1_level, + discipline2_level: evaluate.discipline2_level, + discipline3_level: evaluate.discipline3_level, + discipline4_level: evaluate.discipline4_level, + discipline5_level: evaluate.discipline5_level, + behavior_other_desc: evaluate.behavior_other_desc, + behavior_other_level: evaluate.behavior_other_level, + behavior_strength_desc: evaluate.behavior_strength_desc, + behavior_improve_desc: evaluate.behavior_improve_desc, + orientation: evaluate.orientation, + self_learning: evaluate.self_learning, + training_seminar: evaluate.training_seminar, + other_training: evaluate.other_training, + createdAt: evaluate.createdAt, + updatedAt: evaluate.updatedAt, + achievements: achievements, + }; + } else { + evaluate = await this.evaluateAssessorRepository.find({ + where: { + director_id: director_id, + assign_id, + }, + order: { no: "ASC" }, + }); + + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + await Promise.all( + evaluate.map(async (element: any, index: number) => { + const achievementData = + await this.evaluateAchievementRepository.find({ + select: [ + "output_desc", + "evaluate_expect_level", + "output_desc", + "evaluate_output_level", + ], + where: { + evaluate_id: element.id, + }, + order: { output_id: "ASC" }, + }); + + const achievements = await achievementData.map((achievement) => { + return { + ...achievement, + evaluate_expect_desc: achievement.output_desc, + evaluate_output_desc: achievement.output_desc, + }; + }); + + evaluateData[index] = await { + id: element.id, + director_id: element.director_id, + assign_id, + no: Number(element.no), + date_start: element.date_start, + date_finish: element.date_finish, + assessor_dated: element.assessor_dated, + knowledge_level: element.knowledge_level, + skill_level: element.skill_level, + competency_level: element.competency_level, + learn_level: element.learn_level, + apply_level: element.apply_level, + achievement_other_desc: element.achievement_other_desc, + achievement_other_level: element.achievement_other_level, + achievement_strength_desc: element.achievement_strength_desc, + achievement_improve_desc: element.achievement_improve_desc, + conduct1_level: element.conduct1_level, + conduct2_level: element.conduct2_level, + conduct3_level: element.conduct3_level, + conduct4_level: element.conduct4_level, + moral1_level: element.moral1_level, + moral2_level: element.moral2_level, + moral3_level: element.moral3_level, + discipline1_level: element.discipline1_level, + discipline2_level: element.discipline2_level, + discipline3_level: element.discipline3_level, + discipline4_level: element.discipline4_level, + discipline5_level: element.discipline5_level, + behavior_other_desc: element.behavior_other_desc, + behavior_other_level: element.behavior_other_level, + behavior_strength_desc: element.behavior_strength_desc, + behavior_improve_desc: element.behavior_improve_desc, + orientation: element.orientation, + self_learning: element.self_learning, + training_seminar: element.training_seminar, + other_training: element.other_training, + createdAt: element.createdAt, + updatedAt: element.updatedAt, + achievements: achievements, + }; + }) + ); + } + + const assign = await this.assignRepository.findOne({ + where: { + id: assign_id, + }, + }); + + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const experimenteeData = await this.personalRepository.find({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "organization", + ], + where: { personal_id: assign.personal_id }, + }); + + const experimentee = await experimenteeData.map((element) => ({ + ...element, + name: element.prefixName + element.firstName + " " + element.lastName, + Oc: element.organization, + })); + + const directorData = await this.assignDirectorRepository.find({ + select: [ + "personal_id", + "dated", + "fullname", + "position", + "posType", + "posLevel", + ], + where: { personal_id: director_id }, + }); + + const directors = await directorData.map((element) => ({ + ...element, + name: element.fullname, + label: `${element.fullname} (${element.position}${element.posLevel})`, + })); + + return new HttpSuccess({ + experimentee: experimentee ? experimentee : null, + director: directors ? directors : null, + assign, + evaluate: evaluateData, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } + + /** + * API เพิ่มแบบบันทึกผล(ผู้ดูแล) + * + * @summary เพิ่มแบบบันทึกผล(ผู้ดูแล) + * + */ + @Post("") + async PostData( + @Query() assign_id: string, + @Body() requestBody: CreateEvaluateAssessor, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); + + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "mentor", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + + const director_id = director.personal_id; + + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const postData: any = await { + assign_id, + ...requestBody, + director_id, + no: requestBody.evaluate_no, + date_start: requestBody.start_date, + personal_id: assign.personal_id, + + achievement_other_desc: requestBody.achievement_other + ? requestBody.achievement_other.text + : "", + achievement_other_level: requestBody.achievement_other + ? Number(requestBody.achievement_other.level) + : 0, + behavior_other_desc: requestBody.behavio_orther.text, + behavior_other_level: + requestBody.behavio_orther.text != "" + ? Number(requestBody.behavio_orther.level) + : 0, + behavior_strength_desc: requestBody.behavior_strength_desc, + behavior_improve_desc: requestBody.behavior_improve_desc, + orientation: requestBody.orientation, + self_learning: requestBody.self_learning, + training_seminar: requestBody.training_seminar, + other_training: requestBody.other_training, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; + + const evaluateAssessor = await this.evaluateAssessorRepository.save( + postData, + { + data: request, + } + ); + + if (evaluateAssessor) { + await Promise.all( + requestBody.evaluate_expenct_level.map(async (expenct, index) => { + const evaluateAchievement: CreateEvaluateAchievement = await { + evaluate_id: evaluateAssessor.id, + assign_id, + output_id: expenct.id.toString(), + + assessor_id: director_id, + evaluate_expect_level: Number(expenct.level), + output_desc: requestBody.evaluate_ouptut[index].text, + evaluate_output_level: Number( + requestBody.evaluate_ouptut[index].level + ), + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; + await this.evaluateAchievementRepository.save(evaluateAchievement, { + data: request, + }); + }) + ); + } + + setLogDataDiff(request, { before: null, after: postData }); + + if (Number(requestBody.evaluate_no) < 3) { + // #noted cronjob + // แจ้งผู้ดูแลและผู้บังคับบัญชาเข้ามาบันทึกผลทุก 2 เดือน 3 ครั้ง + const dateSaveForm = await findEndDate(2, requestBody.start_date); + const nextNo = await (Number(requestBody.evaluate_no) + 1); + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, + body: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, + receiverUserId: director_id, + payload: "", + isSendMail: true, + isSendInbox: true, + receiveDate: dateSaveForm, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + } + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } + + /** + * API แก้ไขข้อมูลแบบบันทึกผล(ผู้ดูแล) + * + * @summary แก้ไขข้อมูลแบบบันทึกผล(ผู้ดูแล) + * + */ + @Put("") + async UpdateData( + @Query() assign_id: string, + @Query() evaluate_id: string, + @Body() requestBody: CreateEvaluateAssessor, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); + + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "mentor", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + + const director_id = director.personal_id; + + let evaluate = await this.evaluateAssessorRepository.findOne({ + where: { id: evaluate_id }, + }); + + const before = evaluate; + + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน"); + } + + evaluate.assessor_dated = requestBody.assessor_dated; + evaluate.knowledge_level = requestBody.knowledge_level; + evaluate.skill_level = requestBody.skill_level; + evaluate.competency_level = requestBody.competency_level; + evaluate.learn_level = requestBody.learn_level; + evaluate.apply_level = requestBody.apply_level; + evaluate.achievement_other_desc = requestBody.achievement_other + ? requestBody.achievement_other.text + : ""; + evaluate.achievement_other_level = + requestBody.achievement_other.text != "" + ? Number(requestBody.achievement_other.level) + : 0; + + evaluate.achievement_strength_desc = + requestBody.achievement_strength_desc; + evaluate.achievement_improve_desc = requestBody.achievement_improve_desc; + evaluate.conduct1_level = requestBody.conduct1_level; + evaluate.conduct2_level = requestBody.conduct2_level; + evaluate.conduct3_level = requestBody.conduct3_level; + evaluate.conduct4_level = requestBody.conduct4_level; + evaluate.moral1_level = requestBody.moral1_level; + evaluate.moral2_level = requestBody.moral2_level; + evaluate.moral3_level = requestBody.moral3_level; + evaluate.discipline1_level = requestBody.discipline1_level; + evaluate.discipline2_level = requestBody.discipline2_level; + evaluate.discipline3_level = requestBody.discipline3_level; + evaluate.discipline4_level = requestBody.discipline4_level; + evaluate.discipline5_level = requestBody.discipline5_level; + evaluate.behavior_other_desc = requestBody.behavio_orther.text; + evaluate.behavior_other_level = + requestBody.behavio_orther.text != "" + ? Number(requestBody.behavio_orther.level) + : 0; + evaluate.behavior_strength_desc = requestBody.behavior_strength_desc; + evaluate.behavior_improve_desc = requestBody.behavior_improve_desc; + evaluate.orientation = requestBody.orientation; + evaluate.self_learning = requestBody.self_learning; + evaluate.training_seminar = requestBody.training_seminar; + evaluate.other_training = requestBody.other_training; + evaluate.updateUserId = request.user.sub; + evaluate.updateFullName = request.user.name; + + const evaluateAssessor = await this.evaluateAssessorRepository.save( + evaluate, + { + data: request, + } + ); + + if (evaluateAssessor) { + await this.evaluateAchievementRepository.delete({ + evaluate_id, + }); + await Promise.all( + requestBody.evaluate_expenct_level.map(async (expenct, index) => { + const evaluateAchievement: CreateEvaluateAchievement = await { + evaluate_id: evaluateAssessor.id, + assign_id, + output_id: expenct.id.toString(), + assessor_id: director_id, + evaluate_expect_level: Number(expenct.level), + output_desc: requestBody.evaluate_ouptut[index].text, + evaluate_output_level: Number( + requestBody.evaluate_ouptut[index].level + ), + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; + await this.evaluateAchievementRepository.save(evaluateAchievement, { + data: request, + }); + }) + ); + } + + setLogDataDiff(request, { before, after: evaluate }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } + + /** + * API ดึงข้อมูลตอนกดสร้างแบบบันทึกผล (ผู้บังคัญบัญชา) + * + * @summary get ข้อมูลตอนกดสร้างแบบบันทึกผล (ผู้บังคัญบัญชา) + * + */ + @Get("create/commander") + async GetCreateCommander( + @Query() assign_id: string, + @Request() request: RequestWithUser + ) { + try { + let _workflow = await new permission().Workflow( + request, + assign_id, + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); + + const directorData = await this.assignDirectorRepository.findOne({ + select: [ + "personal_id", + "dated", + "fullname", + "position", + "posType", + "posLevel", + ], + where: { + assign_id, + role: "commander", + }, + }); + + if (!directorData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const director = await { + ...directorData, + name: directorData.fullname, + label: `${directorData.fullname} (${directorData.position}${directorData.posLevel})`, + }; + + const director_id = director.personal_id; + + const assign = await this.assignRepository.findOne({ + where: { + id: assign_id, + }, + }); + + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const profileData = await this.personalRepository.findOne({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "organization", + ], + where: { + personal_id: assign.personal_id, + }, + }); + if (!profileData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + const profile = await { + id: profileData.personal_id, + name: + profileData.prefixName + + profileData.firstName + + " " + + profileData.lastName, + positionName: profileData.positionName, + positionLevelName: profileData.positionLevelName, + Oc: profileData.organization, + }; + + const output = await this.assignOutputRepository.find({ + select: ["id", "output_desc"], + where: { + assign_id, + }, + order: { id: "ASC" }, + }); + + const evaluate_amount = await this.evaluateAssessorRepository.count({ + where: { + assign_id, + director_id, + }, + }); + + const evaluate_no = await (evaluate_amount + 1); + const start_date = await (evaluate_amount == 0 + ? assign.date_start + : findEndDate(evaluate_amount * 2, assign.date_start)); + + return new HttpSuccess({ + person: profile, + assign, + assign_output: output, + evaluate_no, + start_date, + end_date: findEndDate(2, start_date), + director, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } + + /** + * API ข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) + * + * @summary ข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) + * + */ + @Get("commander") + async GetDataCommander( + @Request() request: RequestWithUser, + @Query() assign_id: string, + @Query() evaluate_no?: string + ) { + try { + await new permission().PermissionGet(request, "SYS_PROBATION"); + + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "commander", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + + const director_id = director.personal_id; + + let evaluate: any = null; + let evaluateData: any = []; + if (evaluate_no) { + evaluate = await this.evaluateAssessorRepository.findOne({ + where: { + director_id, + assign_id, + no: evaluate_no, + }, + }); + + if (!evaluate) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบประเมิน" + ); + } + + const achievementData = await this.evaluateAchievementRepository.find({ + select: [ + "output_desc", + "evaluate_expect_level", + "output_desc", + "evaluate_output_level", + ], + where: { + evaluate_id: evaluate.id, + }, + order: { output_id: "ASC" }, + }); + if (!achievementData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const achievements = await achievementData.map((achievement) => { + return { + ...achievement, + evaluate_expect_desc: achievement.output_desc, + evaluate_output_desc: achievement.output_desc, + }; + }); + + evaluateData = await { + id: evaluate.id, + director_id: evaluate.director_id, + assign_id, + no: Number(evaluate.no), + date_start: evaluate.date_start, + date_finish: evaluate.date_finish, + assessor_dated: evaluate.assessor_dated, + knowledge_level: evaluate.knowledge_level, + skill_level: evaluate.skill_level, + competency_level: evaluate.competency_level, + learn_level: evaluate.learn_level, + apply_level: evaluate.apply_level, + achievement_other_desc: evaluate.achievement_other_desc, + achievement_other_level: evaluate.achievement_other_level, + achievement_strength_desc: evaluate.achievement_strength_desc, + achievement_improve_desc: evaluate.achievement_improve_desc, + conduct1_level: evaluate.conduct1_level, + conduct2_level: evaluate.conduct2_level, + conduct3_level: evaluate.conduct3_level, + conduct4_level: evaluate.conduct4_level, + moral1_level: evaluate.moral1_level, + moral2_level: evaluate.moral2_level, + moral3_level: evaluate.moral3_level, + discipline1_level: evaluate.discipline1_level, + discipline2_level: evaluate.discipline2_level, + discipline3_level: evaluate.discipline3_level, + discipline4_level: evaluate.discipline4_level, + discipline5_level: evaluate.discipline5_level, + behavior_other_desc: evaluate.behavior_other_desc, + behavior_other_level: evaluate.behavior_other_level, + behavior_strength_desc: evaluate.behavior_strength_desc, + behavior_improve_desc: evaluate.behavior_improve_desc, + orientation: evaluate.orientation, + self_learning: evaluate.self_learning, + training_seminar: evaluate.training_seminar, + other_training: evaluate.other_training, + createdAt: evaluate.createdAt, + updatedAt: evaluate.updatedAt, + achievements: achievements, + }; + } else { + evaluate = await this.evaluateAssessorRepository.find({ + where: { + director_id: director_id, + assign_id, + }, + order: { no: "ASC" }, + }); + + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + await Promise.all( + evaluate.map(async (element: any, index: number) => { + const achievementData = + await this.evaluateAchievementRepository.find({ + select: [ + "output_desc", + "evaluate_expect_level", + "output_desc", + "evaluate_output_level", + ], + where: { + evaluate_id: element.id, + }, + order: { output_id: "ASC" }, + }); + + const achievements = await achievementData.map((achievement) => { + return { + ...achievement, + evaluate_expect_desc: achievement.output_desc, + evaluate_output_desc: achievement.output_desc, + }; + }); + + evaluateData[index] = await { + id: element.id, + director_id: element.director_id, + assign_id, + no: Number(element.no), + date_start: element.date_start, + date_finish: element.date_finish, + assessor_dated: element.assessor_dated, + knowledge_level: element.knowledge_level, + skill_level: element.skill_level, + competency_level: element.competency_level, + learn_level: element.learn_level, + apply_level: element.apply_level, + achievement_other_desc: element.achievement_other_desc, + achievement_other_level: element.achievement_other_level, + achievement_strength_desc: element.achievement_strength_desc, + achievement_improve_desc: element.achievement_improve_desc, + conduct1_level: element.conduct1_level, + conduct2_level: element.conduct2_level, + conduct3_level: element.conduct3_level, + conduct4_level: element.conduct4_level, + moral1_level: element.moral1_level, + moral2_level: element.moral2_level, + moral3_level: element.moral3_level, + discipline1_level: element.discipline1_level, + discipline2_level: element.discipline2_level, + discipline3_level: element.discipline3_level, + discipline4_level: element.discipline4_level, + discipline5_level: element.discipline5_level, + behavior_other_desc: element.behavior_other_desc, + behavior_other_level: element.behavior_other_level, + behavior_strength_desc: element.behavior_strength_desc, + behavior_improve_desc: element.behavior_improve_desc, + orientation: element.orientation, + self_learning: element.self_learning, + training_seminar: element.training_seminar, + other_training: element.other_training, + createdAt: element.createdAt, + updatedAt: element.updatedAt, + achievements: achievements, + }; + }) + ); + } + + const assign = await this.assignRepository.findOne({ + where: { + id: assign_id, + }, + }); + + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const experimenteeData = await this.personalRepository.find({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "organization", + ], + where: { personal_id: assign.personal_id }, + }); + + const experimentee = await experimenteeData.map((element) => ({ + ...element, + name: element.prefixName + element.firstName + " " + element.lastName, + Oc: element.organization, + })); + + const directorData = await this.assignDirectorRepository.find({ + select: [ + "personal_id", + "dated", + "fullname", + "position", + "posType", + "posLevel", + ], + where: { personal_id: director_id }, + }); + + const directors = await directorData.map((element) => ({ + ...element, + name: element.fullname, + label: `${element.fullname} (${element.position}${element.posLevel})`, + })); + + return new HttpSuccess({ + experimentee: experimentee ? experimentee : null, + person: directors ? directors : null, + assign, + evaluate: evaluateData, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } + + /** + * API บันทึกข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) + * + * @summary บันทึกข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) + * + */ + @Post("commander") + async PostDataCommander( + @Query() assign_id: string, + @Body() requestBody: CreateEvaluateAssessor, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); + + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "commander", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + + const director_id = director.personal_id; + + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const postData: any = await { + assign_id, + ...requestBody, + director_id, + no: requestBody.evaluate_no, + date_start: requestBody.start_date, + personal_id: assign.personal_id, + + achievement_other_desc: requestBody.achievement_other + ? requestBody.achievement_other.text + : "", + achievement_other_level: requestBody.achievement_other + ? Number(requestBody.achievement_other.level) + : 0, + behavior_other_desc: requestBody.behavio_orther.text, + behavior_other_level: + requestBody.behavio_orther.text != "" + ? Number(requestBody.behavio_orther.level) + : 0, + behavior_strength_desc: requestBody.behavior_strength_desc, + behavior_improve_desc: requestBody.behavior_improve_desc, + orientation: requestBody.orientation, + self_learning: requestBody.self_learning, + training_seminar: requestBody.training_seminar, + other_training: requestBody.other_training, + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; + + const evaluateAssessor = await this.evaluateAssessorRepository.save( + postData, + { + data: request, + } + ); + if (evaluateAssessor) { + await Promise.all( + requestBody.evaluate_expenct_level.map(async (expenct, index) => { + const evaluateAchievement: CreateEvaluateAchievement = await { + evaluate_id: evaluateAssessor.id, + assign_id, + output_id: expenct.id.toString(), + assessor_id: director_id, + evaluate_expect_level: Number(expenct.level), + output_desc: requestBody.evaluate_ouptut[index].text, + evaluate_output_level: Number( + requestBody.evaluate_ouptut[index].level + ), + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; + await this.evaluateAchievementRepository.save(evaluateAchievement, { + data: request, + }); + }) + ); + } + + setLogDataDiff(request, { before: null, after: postData }); + + if (Number(requestBody.evaluate_no) < 3) { + // #noted cronjob + // แจ้งผู้ดูแลและผู้บังคับบัญชาเข้ามาบันทึกผลทุก 2 เดือน 3 ครั้ง + const dateSaveForm = await findEndDate(2, requestBody.start_date); + const nextNo = await (Number(requestBody.evaluate_no) + 1); + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, + body: `ถึงกำหนดบันทึกผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, + receiverUserId: director_id, + payload: "", + isSendMail: true, + isSendInbox: true, + receiveDate: dateSaveForm, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + } + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } + + /** + * API แก้ไขข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) + * @summary แก้ไขข้อมูลแบบบันทึกผล (ผู้บังคัญบัญชา) + * + */ + @Put("commander") + async UpdateDataCommander( + @Query() assign_id: string, + @Query() evaluate_id: string, + @Body() requestBody: CreateEvaluateAssessor, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); + + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "commander", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + + const director_id = director.personal_id; + + let evaluate = await this.evaluateAssessorRepository.findOne({ + where: { id: evaluate_id }, + }); + + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน"); + } + const before = evaluate; + + evaluate.assessor_dated = requestBody.assessor_dated; + evaluate.knowledge_level = requestBody.knowledge_level; + evaluate.skill_level = requestBody.skill_level; + evaluate.competency_level = requestBody.competency_level; + evaluate.learn_level = requestBody.learn_level; + evaluate.apply_level = requestBody.apply_level; + evaluate.achievement_other_desc = requestBody.achievement_other + ? requestBody.achievement_other.text + : ""; + evaluate.achievement_other_level = + requestBody.achievement_other.text != "" + ? Number(requestBody.achievement_other.level) + : 0; + + evaluate.achievement_strength_desc = + requestBody.achievement_strength_desc; + evaluate.achievement_improve_desc = requestBody.achievement_improve_desc; + evaluate.conduct1_level = requestBody.conduct1_level; + evaluate.conduct2_level = requestBody.conduct2_level; + evaluate.conduct3_level = requestBody.conduct3_level; + evaluate.conduct4_level = requestBody.conduct4_level; + evaluate.moral1_level = requestBody.moral1_level; + evaluate.moral2_level = requestBody.moral2_level; + evaluate.moral3_level = requestBody.moral3_level; + evaluate.discipline1_level = requestBody.discipline1_level; + evaluate.discipline2_level = requestBody.discipline2_level; + evaluate.discipline3_level = requestBody.discipline3_level; + evaluate.discipline4_level = requestBody.discipline4_level; + evaluate.discipline5_level = requestBody.discipline5_level; + evaluate.behavior_other_desc = requestBody.behavio_orther.text; + evaluate.behavior_other_level = + requestBody.behavio_orther.text != "" + ? Number(requestBody.behavio_orther.level) + : 0; + evaluate.behavior_strength_desc = requestBody.behavior_strength_desc; + evaluate.behavior_improve_desc = requestBody.behavior_improve_desc; + evaluate.orientation = requestBody.orientation; + evaluate.self_learning = requestBody.self_learning; + evaluate.training_seminar = requestBody.training_seminar; + evaluate.other_training = requestBody.other_training; + evaluate.updateUserId = request.user.sub; + evaluate.updateFullName = request.user.name; + + const evaluateAssessor = await this.evaluateAssessorRepository.save( + evaluate, + { + data: request, + } + ); + + if (evaluateAssessor) { + await this.evaluateAchievementRepository.delete({ + evaluate_id, + }); + await Promise.all( + requestBody.evaluate_expenct_level.map(async (expenct, index) => { + const evaluateAchievement: CreateEvaluateAchievement = await { + evaluate_id: evaluateAssessor.id, + assign_id, + output_id: expenct.id.toString(), + assessor_id: director_id, + evaluate_expect_level: Number(expenct.level), + output_desc: requestBody.evaluate_ouptut[index].text, + evaluate_output_level: Number( + requestBody.evaluate_ouptut[index].level + ), + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; + await this.evaluateAchievementRepository.save(evaluateAchievement, { + data: request, + }); + }) + ); + } + + setLogDataDiff(request, { before, after: evaluate }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } } diff --git a/src/controllers/EvaluateResultController.ts b/src/controllers/EvaluateResultController.ts index ada9864..a847360 100644 --- a/src/controllers/EvaluateResultController.ts +++ b/src/controllers/EvaluateResultController.ts @@ -24,7 +24,10 @@ import { Assign } from "../entities/Assign"; import { Personal } from "../entities/Personal"; import CallAPI from "../interfaces/call-api"; import { EvaluateChairman } from "../entities/EvaluateChairman"; -import { CreateEvaluateResult, EvaluateResult } from "../entities/EvaluateResult"; +import { + CreateEvaluateResult, + EvaluateResult, +} from "../entities/EvaluateResult"; import permission from "../interfaces/permission"; @Route("api/v1/probation/evaluate-result") @@ -32,14 +35,17 @@ import permission from "../interfaces/permission"; @Security("bearerAuth") @Response( HttpStatusCode.INTERNAL_SERVER_ERROR, - "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง", + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง" ) export class EvaluateResultController extends Controller { - private assignDirectorRepository = AppDataSource.getRepository(AssignDirector); + private assignDirectorRepository = + AppDataSource.getRepository(AssignDirector); private assignRepository = AppDataSource.getRepository(Assign); - private evaluateChairmanRepository = AppDataSource.getRepository(EvaluateChairman); + private evaluateChairmanRepository = + AppDataSource.getRepository(EvaluateChairman); private personalRepository = AppDataSource.getRepository(Personal); - private evaluateResultRepository = AppDataSource.getRepository(EvaluateResult); + private evaluateResultRepository = + AppDataSource.getRepository(EvaluateResult); /** * API ข้อมูลตอนกดสร้างแบบรายงานการประเมินฯ @@ -48,168 +54,205 @@ export class EvaluateResultController extends Controller { * */ @Get("create") - async CreateEvaluate(@Query() assign_id: string, @Request() request: RequestWithUser) { - let _workflow = await new permission().Workflow(request, assign_id, "SYS_PROBATION"); - if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION"); - - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }); - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - - const profile = await (assign.profile - ? { - ...assign.profile, - id: assign.profile.personal_id, - name: - assign.profile.prefixName + assign.profile.firstName + " " + assign.profile.lastName, - Oc: assign.profile.organization, - } - : null); - - const directorData = await this.assignDirectorRepository.find({ - where: { assign_id }, - order: { ordering: "ASC" }, - }); - - if (!directorData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน"); - } - - let mentors = []; - const mentorList = await directorData.filter((x) => x.role == "mentor"); - if (mentorList.length > 0) { - for (let index = 0; index < mentorList.length; index++) { - const e = await mentorList[index]; - - mentors.push({ - personal_id: e.personal_id, - dated: e.dated, - name: e.fullname, - label: e.fullname + " " + (e.position ? `(${e.position}${e.posLevel})` : ""), - position: e.position, - posType: e.posType, - posLevel: e.posLevel, - }); - } - } - - const commanderData = await (directorData.find((x) => x.role == "commander") ?? null); - - const commander = - commanderData != null - ? { - personal_id: commanderData.personal_id, - dated: commanderData.dated, - name: commanderData.fullname, - label: - commanderData.fullname + - " " + - (commanderData.position - ? `(${commanderData.position}${commanderData.posLevel})` - : ""), - position: commanderData.position, - posType: commanderData.posType, - posLevel: commanderData.posLevel, - } - : null; - - const chairmanData = await (directorData.find((x) => x.role == "chairman") ?? null); - const chairman = - chairmanData != null - ? { - personal_id: chairmanData.personal_id, - dated: chairmanData.dated, - name: chairmanData.fullname, - label: - chairmanData.fullname + - " " + - (chairmanData.position ? `(${chairmanData.position}${chairmanData.posLevel})` : ""), - position: chairmanData.position, - posType: chairmanData.posType, - posLevel: chairmanData.posLevel, - } - : null; - - const resultData = await this.evaluateChairmanRepository.find({ - select: [ - "develop_orientation_score", - "develop_self_learning_score", - "develop_training_seminar_score", - "evaluate_result", - "no", - ], - where: { + async CreateEvaluate( + @Query() assign_id: string, + @Request() request: RequestWithUser + ) { + try { + let _workflow = await new permission().Workflow( + request, assign_id, - }, - }); + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); - if (!resultData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมินผล"); - } + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } - const result = await Promise.all( - resultData.map(async (e) => { - const check = await this.evaluateResultRepository.count({ where: { assign_id, no: e.no } }); + const profile = await (assign.profile + ? { + ...assign.profile, + id: assign.profile.personal_id, + name: + assign.profile.prefixName + + assign.profile.firstName + + " " + + assign.profile.lastName, + Oc: assign.profile.organization, + } + : null); - const develop_complete = - e.develop_orientation_score > 0 && - e.develop_self_learning_score > 0 && - e.develop_training_seminar_score - ? 1 - : 2; + const directorData = await this.assignDirectorRepository.find({ + where: { assign_id }, + order: { ordering: "ASC" }, + }); - const evaluate_result = e.evaluate_result === 1 ? 1 : 2; + if (!directorData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน" + ); + } - let startDate = assign.date_start; - if (e.no === "2") { - const resultNo1 = await this.evaluateResultRepository.findOne({ - select: ["date_finish"], - where: { assign_id, no: "1" }, + let mentors = []; + const mentorList = await directorData.filter((x) => x.role == "mentor"); + if (mentorList.length > 0) { + for (let index = 0; index < mentorList.length; index++) { + const e = await mentorList[index]; + + mentors.push({ + personal_id: e.personal_id, + dated: e.dated, + name: e.fullname, + label: + e.fullname + + " " + + (e.position ? `(${e.position}${e.posLevel})` : ""), + position: e.position, + posType: e.posType, + posLevel: e.posLevel, }); - startDate = resultNo1?.date_finish ?? assign.date_start; } + } - let endDate: any = assign.date_finish; - if (e.no === "1") { - endDate = findEndDate(3, assign.date_start) ?? assign.date_finish; - } + const commanderData = await (directorData.find( + (x) => x.role == "commander" + ) ?? null); - return { - develop_complete, - evaluate_result, - evaluate_no: Number(e.no), - isResult: check > 0 ? true : false, - start_date: startDate, - end_date: endDate, - }; - }), - ); + const commander = + commanderData != null + ? { + personal_id: commanderData.personal_id, + dated: commanderData.dated, + name: commanderData.fullname, + label: + commanderData.fullname + + " " + + (commanderData.position + ? `(${commanderData.position}${commanderData.posLevel})` + : ""), + position: commanderData.position, + posType: commanderData.posType, + posLevel: commanderData.posLevel, + } + : null; - // const develop_complete = await (resultData.develop_orientation_score > 0 && - // resultData.develop_self_learning_score > 0 && - // resultData.develop_training_seminar_score > 0 - // ? 1 - // : 2); + const chairmanData = await (directorData.find( + (x) => x.role == "chairman" + ) ?? null); + const chairman = + chairmanData != null + ? { + personal_id: chairmanData.personal_id, + dated: chairmanData.dated, + name: chairmanData.fullname, + label: + chairmanData.fullname + + " " + + (chairmanData.position + ? `(${chairmanData.position}${chairmanData.posLevel})` + : ""), + position: chairmanData.position, + posType: chairmanData.posType, + posLevel: chairmanData.posLevel, + } + : null; - // const evaluate_result = await (resultData.evaluate_result == 1 ? 1 : 2); + const resultData = await this.evaluateChairmanRepository.find({ + select: [ + "develop_orientation_score", + "develop_self_learning_score", + "develop_training_seminar_score", + "evaluate_result", + "no", + ], + where: { + assign_id, + }, + }); - // const result = await { - // develop_complete: develop_complete, - // evaluate_result: evaluate_result, - // }; + if (!resultData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลการประเมินผล" + ); + } - return new HttpSuccess({ - person: profile, - assign, - result, - mentors, - commander, - chairman, - }); + const result = await Promise.all( + resultData.map(async (e) => { + const check = await this.evaluateResultRepository.count({ + where: { assign_id, no: e.no }, + }); + + const develop_complete = + e.develop_orientation_score > 0 && + e.develop_self_learning_score > 0 && + e.develop_training_seminar_score + ? 1 + : 2; + + const evaluate_result = e.evaluate_result === 1 ? 1 : 2; + + let startDate = assign.date_start; + if (e.no === "2") { + const resultNo1 = await this.evaluateResultRepository.findOne({ + select: ["date_finish"], + where: { assign_id, no: "1" }, + }); + startDate = resultNo1?.date_finish ?? assign.date_start; + } + + let endDate: any = assign.date_finish; + if (e.no === "1") { + endDate = findEndDate(3, assign.date_start) ?? assign.date_finish; + } + + return { + develop_complete, + evaluate_result, + evaluate_no: Number(e.no), + isResult: check > 0 ? true : false, + start_date: startDate, + end_date: endDate, + }; + }) + ); + + // const develop_complete = await (resultData.develop_orientation_score > 0 && + // resultData.develop_self_learning_score > 0 && + // resultData.develop_training_seminar_score > 0 + // ? 1 + // : 2); + + // const evaluate_result = await (resultData.evaluate_result == 1 ? 1 : 2); + + // const result = await { + // develop_complete: develop_complete, + // evaluate_result: evaluate_result, + // }; + + return new HttpSuccess({ + person: profile, + assign, + result, + mentors, + commander, + chairman, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -222,152 +265,176 @@ export class EvaluateResultController extends Controller { async GetEvaluate( @Request() request: RequestWithUser, @Query() assign_id: string, - @Query() evaluate_no?: string, + @Query() evaluate_no?: string ) { - await new permission().PermissionGet(request, "SYS_PROBATION"); + try { + await new permission().PermissionGet(request, "SYS_PROBATION"); - // ต้องปรับเป็น id ของคนที่ access เข้ามา - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { - assign_id, - role: "chairman", - }, - }); - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); - } - const director_id = director.personal_id; - - const evaluate = await this.evaluateResultRepository.findOne({ - where: { - director_id, - assign_id, - no: evaluate_no ?? "1", - }, - }); - - if (!evaluate) { - return new HttpSuccess(null); - } - - const assign = await this.assignRepository.findOne({ - where: { id: assign_id }, - }); - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - - const experimenteeData = await this.personalRepository.findOne({ - select: [ - "personal_id", - "prefixName", - "firstName", - "lastName", - "positionName", - "positionLevelName", - "organization", - "orgRootName", - ], - where: { personal_id: assign.personal_id }, - }); - - if (!experimenteeData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); - } - - const splitOc = await experimenteeData.organization.split(" "); - const splitOcAmount = await splitOc.length; - const experimentee = await { - ...experimenteeData, - name: - experimenteeData.prefixName + experimenteeData.firstName + " " + experimenteeData.lastName, - PositionLevel: experimenteeData.positionName + experimenteeData.positionLevelName, - Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", - OrganizationOrganization: splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", - Oc: experimenteeData.orgRootName, - }; - - const directorData = await this.assignDirectorRepository.find({ - where: { assign_id }, - order: { ordering: "ASC" }, - }); - - if (!directorData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน"); - } - - let mentors = []; - const mentorList = await directorData.filter((x) => x.role == "mentor"); - if (mentorList.length > 0) { - for (let index = 0; index < mentorList.length; index++) { - const e = await mentorList[index]; - - mentors.push({ - personal_id: e.personal_id, - dated: e.dated, - name: e.fullname, - label: e.fullname + " " + (e.position ? `(${e.position}${e.posLevel})` : ""), - position: e.position + e.posLevel, - posType: e.posType, - posLevel: e.posLevel, - }); + // ต้องปรับเป็น id ของคนที่ access เข้ามา + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "chairman", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); } - } + const director_id = director.personal_id; - // const commanderData = await (directorData.find((x) => x.role == "commander") ?? null); + const evaluate = await this.evaluateResultRepository.findOne({ + where: { + director_id, + assign_id, + no: evaluate_no ?? "1", + }, + }); - // const commander = - // commanderData != null - // ? { - // personal_id: commanderData.personal_id, - // dated: commanderData.dated, - // name: commanderData.fullname, - // label: - // commanderData.fullname + - // " " + - // (commanderData.position - // ? `(${commanderData.position}${commanderData.posLevel})` - // : ""), - // position: commanderData.position + commanderData.posLevel, - // posType: commanderData.posType, - // posLevel: commanderData.posLevel, - // } - // : null; + if (!evaluate) { + return new HttpSuccess(null); + } - const commander = { - dated: evaluate.authority_dated, - name: evaluate.authority_name, + const assign = await this.assignRepository.findOne({ + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } - position: evaluate.authority_pos + evaluate.authority_level, - posType: evaluate.authority_type, - posLevel: evaluate.authority_level, - }; - const chairmanData = await (directorData.find((x) => x.role == "chairman") ?? null); - const chairman = - chairmanData != null - ? { - personal_id: chairmanData.personal_id, - dated: chairmanData.dated, - name: chairmanData.fullname, + const experimenteeData = await this.personalRepository.findOne({ + select: [ + "personal_id", + "prefixName", + "firstName", + "lastName", + "positionName", + "positionLevelName", + "organization", + "orgRootName", + ], + where: { personal_id: assign.personal_id }, + }); + + if (!experimenteeData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + const splitOc = await experimenteeData.organization.split(" "); + const splitOcAmount = await splitOc.length; + const experimentee = await { + ...experimenteeData, + name: + experimenteeData.prefixName + + experimenteeData.firstName + + " " + + experimenteeData.lastName, + PositionLevel: + experimenteeData.positionName + experimenteeData.positionLevelName, + Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", + OrganizationOrganization: + splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", + Oc: experimenteeData.orgRootName, + }; + + const directorData = await this.assignDirectorRepository.find({ + where: { assign_id }, + order: { ordering: "ASC" }, + }); + + if (!directorData) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน" + ); + } + + let mentors = []; + const mentorList = await directorData.filter((x) => x.role == "mentor"); + if (mentorList.length > 0) { + for (let index = 0; index < mentorList.length; index++) { + const e = await mentorList[index]; + + mentors.push({ + personal_id: e.personal_id, + dated: e.dated, + name: e.fullname, label: - chairmanData.fullname + + e.fullname + " " + - (chairmanData.position ? `(${chairmanData.position}${chairmanData.posLevel})` : ""), - position: chairmanData.position + chairmanData.posLevel, - posType: chairmanData.posType, - posLevel: chairmanData.posLevel, - } - : null; + (e.position ? `(${e.position}${e.posLevel})` : ""), + position: e.position + e.posLevel, + posType: e.posType, + posLevel: e.posLevel, + }); + } + } - return new HttpSuccess({ - commander, - chairman, - mentors, - experimentee, - assign, - evaluate: evaluate ? evaluate : null, - }); + // const commanderData = await (directorData.find((x) => x.role == "commander") ?? null); + + // const commander = + // commanderData != null + // ? { + // personal_id: commanderData.personal_id, + // dated: commanderData.dated, + // name: commanderData.fullname, + // label: + // commanderData.fullname + + // " " + + // (commanderData.position + // ? `(${commanderData.position}${commanderData.posLevel})` + // : ""), + // position: commanderData.position + commanderData.posLevel, + // posType: commanderData.posType, + // posLevel: commanderData.posLevel, + // } + // : null; + + const commander = { + dated: evaluate.authority_dated, + name: evaluate.authority_name, + + position: evaluate.authority_pos + evaluate.authority_level, + posType: evaluate.authority_type, + posLevel: evaluate.authority_level, + }; + const chairmanData = await (directorData.find( + (x) => x.role == "chairman" + ) ?? null); + const chairman = + chairmanData != null + ? { + personal_id: chairmanData.personal_id, + dated: chairmanData.dated, + name: chairmanData.fullname, + label: + chairmanData.fullname + + " " + + (chairmanData.position + ? `(${chairmanData.position}${chairmanData.posLevel})` + : ""), + position: chairmanData.position + chairmanData.posLevel, + posType: chairmanData.posType, + posLevel: chairmanData.posLevel, + } + : null; + + return new HttpSuccess({ + commander, + chairman, + mentors, + experimentee, + assign, + evaluate: evaluate ? evaluate : null, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -380,52 +447,62 @@ export class EvaluateResultController extends Controller { async PostData( @Query() assign_id: string, @Body() requestBody: CreateEvaluateResult, - @Request() request: RequestWithUser, + @Request() request: RequestWithUser ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION"); + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - const director = await this.assignDirectorRepository.findOne({ - select: ["personal_id"], - where: { + const director = await this.assignDirectorRepository.findOne({ + select: ["personal_id"], + where: { + assign_id, + role: "chairman", + }, + }); + if (!director) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + } + + const director_id = director.personal_id; + + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const postData: any = await { assign_id, - role: "chairman", - }, - }); - if (!director) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล"); + ...requestBody, + director_id, + no: requestBody.evaluate_no, + personal_id: assign.personal_id, + date_start: requestBody.start_date, + expand_month: + requestBody.pass_result == 3 ? Number(requestBody.expand_month) : 0, + + createdUserId: request.user.sub, + createdFullName: request.user.name, + updateUserId: request.user.sub, + updateFullName: request.user.name, + }; + + await this.evaluateResultRepository.save(postData, { + data: request, + }); + setLogDataDiff(request, { before: null, after: postData }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const director_id = director.personal_id; - - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }); - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - - const postData: any = await { - assign_id, - ...requestBody, - director_id, - no: requestBody.evaluate_no, - personal_id: assign.personal_id, - date_start: requestBody.start_date, - expand_month: requestBody.pass_result == 3 ? Number(requestBody.expand_month) : 0, - - createdUserId: request.user.sub, - createdFullName: request.user.name, - updateUserId: request.user.sub, - updateFullName: request.user.name, - }; - - await this.evaluateResultRepository.save(postData, { - data: request, - }); - setLogDataDiff(request, { before: null, after: postData }); - - return new HttpSuccess(); } /** @@ -438,62 +515,74 @@ export class EvaluateResultController extends Controller { async PatchData( @Query() assign_id: string, @Query() evaluate_no: number | string, - @Request() request: RequestWithUser, + @Request() request: RequestWithUser ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION"); + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }); - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + + const result = await this.evaluateResultRepository.findOne({ + where: { assign_id, no: evaluate_no.toString() }, + }); + + if (!result) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลผลการประเมิน" + ); + } + + const personal = await this.personalRepository.findOne({ + where: { personal_id: assign.personal_id }, + }); + + if (!personal) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + personal.probation_status = + result.pass_result == 1 + ? 2 // ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้รับราชการต่อ + : result.pass_result == 2 + ? 3 // ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ออกจากราชการ + : result.pass_result == 4 + ? 1 // ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ทดลองปฏิบัติหน้าที่ราชการต่อไป + : personal.probation_status; + + if (result.pass_result == 3) { + personal.probation_status = 7; + // #noti ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ กรณีขยายระยะเวลา + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: "ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ", + body: `ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ เห็นควรให้ขยายระยะเวลาทดลองปฏิบัติหน้าที่ราชการต่อไปอีก ${result.expand_month} เดือน`, + receiverUserId: assign.personal_id, + payload: "", + isSendMail: false, + isSendInbox: true, + isSendNotification: true, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + } + + await this.personalRepository.save(personal, { data: request }); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const result = await this.evaluateResultRepository.findOne({ - where: { assign_id, no: evaluate_no.toString() }, - }); - - if (!result) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผลการประเมิน"); - } - - const personal = await this.personalRepository.findOne({ - where: { personal_id: assign.personal_id }, - }); - - if (!personal) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); - } - personal.probation_status = - result.pass_result == 1 - ? 2 // ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้รับราชการต่อ - : result.pass_result == 2 - ? 3 // ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ออกจากราชการ - : result.pass_result == 4 - ? 1 // ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ทดลองปฏิบัติหน้าที่ราชการต่อไป - : personal.probation_status; - - if (result.pass_result == 3) { - personal.probation_status = 7; - // #noti ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ กรณีขยายระยะเวลา - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: "ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ", - body: `ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ เห็นควรให้ขยายระยะเวลาทดลองปฏิบัติหน้าที่ราชการต่อไปอีก ${result.expand_month} เดือน`, - receiverUserId: assign.personal_id, - payload: "", - isSendMail: false, - isSendInbox: true, - isSendNotification: true, - }) - .catch((error) => { - console.error("Error calling API:", error); - }); - } - - await this.personalRepository.save(personal, { data: request }); - return new HttpSuccess(); } /** @@ -507,82 +596,91 @@ export class EvaluateResultController extends Controller { @Query() assign_id: string, @Query() evaluate_id: string, @Body() requestBody: CreateEvaluateResult, - @Request() request: RequestWithUser, + @Request() request: RequestWithUser ) { - await new permission().PermissionUpdate(request, "SYS_PROBATION"); + try { + await new permission().PermissionUpdate(request, "SYS_PROBATION"); - let evaluate = await this.evaluateResultRepository.findOne({ - where: { id: evaluate_id }, - }); + let evaluate = await this.evaluateResultRepository.findOne({ + where: { id: evaluate_id }, + }); - const before = evaluate; + const before = evaluate; - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน"); + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน"); + } + + evaluate.date_start = requestBody.start_date; + evaluate.date_finish = requestBody.date_finish; + evaluate.develop_complete = requestBody.develop_complete; + evaluate.pass_result = requestBody.pass_result; + evaluate.expand_month = + requestBody.pass_result && requestBody.pass_result == 3 + ? Number(requestBody.expand_month) + : 0; + evaluate.reson = requestBody.reson; + evaluate.chairman_dated = requestBody.chairman_dated; + + // evaluate.director1_dated = requestBody.director1_dated; + // evaluate.director2_dated = requestBody.director2_dated; + evaluate.updateUserId = request.user.sub; + evaluate.updateFullName = request.user.name; + + await this.evaluateResultRepository.save(evaluate, { data: request }); + setLogDataDiff(request, { before, after: evaluate }); + + const assign = await this.assignRepository.findOne({ + relations: ["profile"], + where: { id: assign_id }, + }); + if (!assign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลแบบมอบหมายงาน" + ); + } + const personal = await this.personalRepository.findOne({ + where: { personal_id: assign.personal_id }, + }); + + if (!personal) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + personal.probation_status = + requestBody.pass_result == 1 + ? 2 // ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้รับราชการต่อ + : requestBody.pass_result == 2 + ? 3 // ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ออกจากราชการ + : requestBody.pass_result == 4 + ? 1 // ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ทดลองปฏิบัติหน้าที่ราชการต่อไป + : personal.probation_status; + + if (requestBody.pass_result == 3) { + personal.probation_status = 7; + // #noti ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ กรณีขยายระยะเวลา + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: "ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ", + body: `ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ เห็นควรให้ขยายระยะเวลาทดลองปฏิบัติหน้าที่ราชการต่อไปอีก ${requestBody.expand_month} เดือน`, + receiverUserId: assign.personal_id, + payload: "", + isSendMail: false, + isSendInbox: true, + isSendNotification: true, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + } + + await this.personalRepository.save(personal, { data: request }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - evaluate.date_start = requestBody.start_date; - evaluate.date_finish = requestBody.date_finish; - evaluate.develop_complete = requestBody.develop_complete; - evaluate.pass_result = requestBody.pass_result; - evaluate.expand_month = - requestBody.pass_result && requestBody.pass_result == 3 - ? Number(requestBody.expand_month) - : 0; - evaluate.reson = requestBody.reson; - evaluate.chairman_dated = requestBody.chairman_dated; - - // evaluate.director1_dated = requestBody.director1_dated; - // evaluate.director2_dated = requestBody.director2_dated; - evaluate.updateUserId = request.user.sub; - evaluate.updateFullName = request.user.name; - - await this.evaluateResultRepository.save(evaluate, { data: request }); - setLogDataDiff(request, { before, after: evaluate }); - - const assign = await this.assignRepository.findOne({ - relations: ["profile"], - where: { id: assign_id }, - }); - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); - } - const personal = await this.personalRepository.findOne({ - where: { personal_id: assign.personal_id }, - }); - - if (!personal) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); - } - personal.probation_status = - requestBody.pass_result == 1 - ? 2 // ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้รับราชการต่อ - : requestBody.pass_result == 2 - ? 3 // ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ออกจากราชการ - : requestBody.pass_result == 4 - ? 1 // ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ทดลองปฏิบัติหน้าที่ราชการต่อไป - : personal.probation_status; - - if (requestBody.pass_result == 3) { - personal.probation_status = 7; - // #noti ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ กรณีขยายระยะเวลา - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: "ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ", - body: `ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ เห็นควรให้ขยายระยะเวลาทดลองปฏิบัติหน้าที่ราชการต่อไปอีก ${requestBody.expand_month} เดือน`, - receiverUserId: assign.personal_id, - payload: "", - isSendMail: false, - isSendInbox: true, - isSendNotification: true, - }) - .catch((error) => { - console.error("Error calling API:", error); - }); - } - - await this.personalRepository.save(personal, { data: request }); - - return new HttpSuccess(); } } diff --git a/src/controllers/PersonalController.ts b/src/controllers/PersonalController.ts index e8ddb63..95518a0 100644 --- a/src/controllers/PersonalController.ts +++ b/src/controllers/PersonalController.ts @@ -1,246 +1,359 @@ -import { Controller, Post, Route, Security, Tags, Body, Request, SuccessResponse, Response, Get, Query } from "tsoa" -import { AppDataSource } from "../database/data-source" -import HttpSuccess from "../interfaces/http-success" -import HttpStatusCode from "../interfaces/http-status" -import HttpError from "../interfaces/http-error" -import { RequestWithUser } from "../middlewares/user" -import { setLogDataDiff } from "../interfaces/utils" -import { Personal, PostPersonal } from "../entities/Personal" -import permission from "../interfaces/permission" -import { Assign } from "../entities/Assign" -import { Brackets } from "typeorm" +import { + Controller, + Post, + Route, + Security, + Tags, + Body, + Request, + SuccessResponse, + Response, + Get, + Query, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatusCode from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { setLogDataDiff } from "../interfaces/utils"; +import { Personal, PostPersonal } from "../entities/Personal"; +import permission from "../interfaces/permission"; +import { Assign } from "../entities/Assign"; +import { Brackets } from "typeorm"; @Route("api/v1/probation/personal") @Tags("Personal") @Security("bearerAuth") -@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") +@Response( + HttpStatusCode.INTERNAL_SERVER_ERROR, + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง" +) export class PersonalController extends Controller { - private personalRepository = AppDataSource.getRepository(Personal) - private assignRepository = AppDataSource.getRepository(Assign) + private personalRepository = AppDataSource.getRepository(Personal); + private assignRepository = AppDataSource.getRepository(Assign); - /** - * API ข้อมูลบุคคลในระบบทดลองงาน - * - * @summary เพิ่มคนเข้าระบบทดลองงาน - * - */ - @Post("add") - async AddPersonal(@Body() requestBody: PostPersonal, @Request() request: RequestWithUser) { - await new permission().PermissionCreate(request, "SYS_PROBATION") + /** + * API ข้อมูลบุคคลในระบบทดลองงาน + * + * @summary เพิ่มคนเข้าระบบทดลองงาน + * + */ + @Post("add") + async AddPersonal( + @Body() requestBody: PostPersonal, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionCreate(request, "SYS_PROBATION"); - const checkPersonal: number = await this.personalRepository.count({ - where: { personal_id: requestBody.id }, - }) - if (checkPersonal > 0) { - throw new HttpError(HttpStatusCode.BAD_REQUEST, "ผู้ทดลองปฏิบัติหน้าที่ราชการนี้มีอยู่แล้ว") - } + const checkPersonal: number = await this.personalRepository.count({ + where: { personal_id: requestBody.id }, + }); + if (checkPersonal > 0) { + throw new HttpError( + HttpStatusCode.BAD_REQUEST, + "ผู้ทดลองปฏิบัติหน้าที่ราชการนี้มีอยู่แล้ว" + ); + } - let organization = await (requestBody.orgChild4Name ? requestBody.orgChild4Name + " " : "") - organization += await (requestBody.orgChild3Name ? requestBody.orgChild3Name + " " : "") - organization += await (requestBody.orgChild2Name ? requestBody.orgChild2Name + " " : "") - organization += await (requestBody.orgChild1Name ? requestBody.orgChild1Name + " " : "") - organization += await (requestBody.orgRootName ? requestBody.orgRootName : "") + let organization = await (requestBody.orgChild4Name + ? requestBody.orgChild4Name + " " + : ""); + organization += await (requestBody.orgChild3Name + ? requestBody.orgChild3Name + " " + : ""); + organization += await (requestBody.orgChild2Name + ? requestBody.orgChild2Name + " " + : ""); + organization += await (requestBody.orgChild1Name + ? requestBody.orgChild1Name + " " + : ""); + organization += await (requestBody.orgRootName + ? requestBody.orgRootName + : ""); - const personalData = Object.assign(new Personal()) - personalData.personal_id = requestBody.id - personalData.order_number = requestBody.order_number ? requestBody.order_number : "" - personalData.probation_status = 1 - personalData.createdUserId = request.user.sub - personalData.createdFullName = request.user.name - personalData.updateUserId = request.user.sub - personalData.updateFullName = request.user.name + const personalData = Object.assign(new Personal()); + personalData.personal_id = requestBody.id; + personalData.order_number = requestBody.order_number + ? requestBody.order_number + : ""; + personalData.probation_status = 1; + personalData.createdUserId = request.user.sub; + personalData.createdFullName = request.user.name; + personalData.updateUserId = request.user.sub; + personalData.updateFullName = request.user.name; - personalData.idcard = requestBody.idcard - personalData.prefixName = requestBody.prefix - personalData.firstName = requestBody.firstName - personalData.lastName = requestBody.lastName - personalData.isProbation = requestBody.isProbation ? 1 : 0 - personalData.positionLevelName = requestBody.posLevelName ? requestBody.posLevelName : "" - personalData.positionName = requestBody.position ? requestBody.position : "" - personalData.positionLineName = requestBody.posLineName - personalData.positionTypeName = requestBody.posTypeName - personalData.posNo = requestBody.posNo ? requestBody.posNo : "" - personalData.orgRootName = requestBody.orgRootName - personalData.organization = organization + personalData.idcard = requestBody.idcard; + personalData.prefixName = requestBody.prefix; + personalData.firstName = requestBody.firstName; + personalData.lastName = requestBody.lastName; + personalData.isProbation = requestBody.isProbation ? 1 : 0; + personalData.positionLevelName = requestBody.posLevelName + ? requestBody.posLevelName + : ""; + personalData.positionName = requestBody.position + ? requestBody.position + : ""; + personalData.positionLineName = requestBody.posLineName; + personalData.positionTypeName = requestBody.posTypeName; + personalData.posNo = requestBody.posNo ? requestBody.posNo : ""; + personalData.orgRootName = requestBody.orgRootName; + personalData.organization = organization; - personalData.root = requestBody.root - personalData.child1 = requestBody.child1 - personalData.child2 = requestBody.child2 - personalData.child3 = requestBody.child3 - personalData.child4 = requestBody.child4 + personalData.root = requestBody.root; + personalData.child1 = requestBody.child1; + personalData.child2 = requestBody.child2; + personalData.child3 = requestBody.child3; + personalData.child4 = requestBody.child4; - personalData.rootDna = requestBody.rootDna - personalData.child1Dna = requestBody.child1Dna - personalData.child2Dna = requestBody.child2Dna - personalData.child3Dna = requestBody.child3Dna - personalData.child4Dna = requestBody.child4Dna + personalData.rootDna = requestBody.rootDna; + personalData.child1Dna = requestBody.child1Dna; + personalData.child2Dna = requestBody.child2Dna; + personalData.child3Dna = requestBody.child3Dna; + personalData.child4Dna = requestBody.child4Dna; - const before = null - const personal = await this.personalRepository.save(personalData, { - data: request, - }) - setLogDataDiff(request, { before, after: personal }) + const before = null; + const personal = await this.personalRepository.save(personalData, { + data: request, + }); + setLogDataDiff(request, { before, after: personal }); - return new HttpSuccess() - } + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - /** - * API รายการบุคคลในระบบทดลองงาน - * - * @summary รายชื่อคนที่อยู่ในระบบทดลองงาน - * - */ - @Get("list") - async ListPersonal(@Query() status: string = "", @Query() keyword: string = "", @Query("page") page: number = 1, @Query("pageSize") pageSize: number = 10, @Request() request: RequestWithUser) { - await new permission().PermissionList(request, "SYS_PROBATION") - const _data = await new permission().PermissionOrgList(request, "SYS_PROBATION") + /** + * API รายการบุคคลในระบบทดลองงาน + * + * @summary รายชื่อคนที่อยู่ในระบบทดลองงาน + * + */ + @Get("list") + async ListPersonal( + @Query() status: string = "", + @Query() keyword: string = "", + @Query("page") page: number = 1, + @Query("pageSize") pageSize: number = 10, + @Request() request: RequestWithUser + ) { + try { + await new permission().PermissionList(request, "SYS_PROBATION"); + const _data = await new permission().PermissionOrgList( + request, + "SYS_PROBATION" + ); - const conditions: any = {} - if (status) { - conditions.probation_status = status - } + const conditions: any = {}; + if (status) { + conditions.probation_status = status; + } - if (_data.root != undefined && _data.root != null && _data.root[0] != null) { - conditions.root = _data.root - } + if ( + _data.root != undefined && + _data.root != null && + _data.root[0] != null + ) { + conditions.root = _data.root; + } - if (_data.child1 != undefined && _data.child1 != null && _data.child1[0] != null) { - conditions.child1 = _data.child1 - } + if ( + _data.child1 != undefined && + _data.child1 != null && + _data.child1[0] != null + ) { + conditions.child1 = _data.child1; + } - if (_data.child2 != undefined && _data.child2 != null && _data.child2[0] != null) { - conditions.child2 = _data.child2 - } + if ( + _data.child2 != undefined && + _data.child2 != null && + _data.child2[0] != null + ) { + conditions.child2 = _data.child2; + } - if (_data.child3 != undefined && _data.child3 != null && _data.child3[0] != null) { - conditions.child3 = _data.child3 - } + if ( + _data.child3 != undefined && + _data.child3 != null && + _data.child3[0] != null + ) { + conditions.child3 = _data.child3; + } - if (_data.child4 != undefined && _data.child4 != null && _data.child4[0] != null) { - conditions.child4 = _data.child4 - } + if ( + _data.child4 != undefined && + _data.child4 != null && + _data.child4[0] != null + ) { + conditions.child4 = _data.child4; + } - const searchKeyword = await (keyword ? keyword.trim() : null) + const searchKeyword = await (keyword ? keyword.trim() : null); - const [lists, total] = await AppDataSource.getRepository(Personal) - .createQueryBuilder("personal") - .where(conditions) - .andWhere( - new Brackets(qb => { - qb.orWhere(searchKeyword ? `CONCAT(prefixName, firstName," ",lastName) like '%${keyword}%'` : "1=1", { - keyword: `%${searchKeyword}%`, - }) - qb.orWhere(searchKeyword ? `positionName like '%${keyword}%'` : "1=1", { - keyword: `%${searchKeyword}%`, - }) - qb.orWhere(searchKeyword ? `positionLevelName like '%${keyword}%'` : "1=1", { - keyword: `%${searchKeyword}%`, - }) - qb.orWhere(searchKeyword ? `organization like '%${keyword}%'` : "1=1", { - keyword: `%${searchKeyword}%`, - }) - qb.orWhere(searchKeyword ? `order_number like '%${keyword}%'` : "1=1", { - keyword: `%${searchKeyword}%`, - }) - }) - ) - .orderBy("updatedAt", "DESC") - .skip((page - 1) * pageSize) - .take(pageSize) - .getManyAndCount() + const [lists, total] = await AppDataSource.getRepository(Personal) + .createQueryBuilder("personal") + .where(conditions) + .andWhere( + new Brackets((qb) => { + qb.orWhere( + searchKeyword + ? `CONCAT(prefixName, firstName," ",lastName) like '%${keyword}%'` + : "1=1", + { + keyword: `%${searchKeyword}%`, + } + ); + qb.orWhere( + searchKeyword ? `positionName like '%${keyword}%'` : "1=1", + { + keyword: `%${searchKeyword}%`, + } + ); + qb.orWhere( + searchKeyword ? `positionLevelName like '%${keyword}%'` : "1=1", + { + keyword: `%${searchKeyword}%`, + } + ); + qb.orWhere( + searchKeyword ? `organization like '%${keyword}%'` : "1=1", + { + keyword: `%${searchKeyword}%`, + } + ); + qb.orWhere( + searchKeyword ? `order_number like '%${keyword}%'` : "1=1", + { + keyword: `%${searchKeyword}%`, + } + ); + }) + ) + .orderBy("updatedAt", "DESC") + .skip((page - 1) * pageSize) + .take(pageSize) + .getManyAndCount(); - if (!lists) { - throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "ไม่สามารถแสดงข้อมูลได้") - } + if (!lists) { + throw new HttpError( + HttpStatusCode.INTERNAL_SERVER_ERROR, + "ไม่สามารถแสดงข้อมูลได้" + ); + } - let result: any = [] + let result: any = []; - for (let i = 0; i < lists.length; i++) { - const probation_no = await this.assignRepository.count({ - where: { personal_id: lists[i].personal_id }, - }) + for (let i = 0; i < lists.length; i++) { + const probation_no = await this.assignRepository.count({ + where: { personal_id: lists[i].personal_id }, + }); - await result.push({ - personal_id: lists[i].personal_id, - ordering: i + 1, - name: lists[i].prefixName + lists[i].firstName + " " + lists[i].lastName, - prefixName: lists[i].prefixName, - firstName: lists[i].firstName, - lastName: lists[i].lastName, - idcard: lists[i].idcard, - position_line: lists[i].positionName, - position_level: lists[i].positionLevelName, - position_type: lists[i].positionTypeName, - organization: lists[i].organization, - probation_no: probation_no, - order_number: lists[i].order_number, - probation_status: lists[i].probation_status, - }) - } - // await Promise.all( - // lists.map(async (item, index) => { - // const probation_no = await this.assignRepository.count({ - // where: { - // personal_id: item.personal_id, - // }, - // }); + await result.push({ + personal_id: lists[i].personal_id, + ordering: i + 1, + name: + lists[i].prefixName + lists[i].firstName + " " + lists[i].lastName, + prefixName: lists[i].prefixName, + firstName: lists[i].firstName, + lastName: lists[i].lastName, + idcard: lists[i].idcard, + position_line: lists[i].positionName, + position_level: lists[i].positionLevelName, + position_type: lists[i].positionTypeName, + organization: lists[i].organization, + probation_no: probation_no, + order_number: lists[i].order_number, + probation_status: lists[i].probation_status, + }); + } + // await Promise.all( + // lists.map(async (item, index) => { + // const probation_no = await this.assignRepository.count({ + // where: { + // personal_id: item.personal_id, + // }, + // }); - // await result.push({ - // personal_id: item.personal_id, - // ordering: index + 1, - // name: item.prefixName + item.firstName + " " + item.lastName, - // idcard: item.idcard, - // // prefixName: item.prefixName, - // // firstName: item.firstName, - // // lastName: item.lastName, - // position_line: item.positionName, - // position_level: item.positionLevelName, - // position_type: item.positionTypeName, - // organization: item.organization, - // probation_no: probation_no, - // order_number: item.order_number, - // probation_status: item.probation_status, - // }); - // }), - // ); + // await result.push({ + // personal_id: item.personal_id, + // ordering: index + 1, + // name: item.prefixName + item.firstName + " " + item.lastName, + // idcard: item.idcard, + // // prefixName: item.prefixName, + // // firstName: item.firstName, + // // lastName: item.lastName, + // position_line: item.positionName, + // position_level: item.positionLevelName, + // position_type: item.positionTypeName, + // organization: item.organization, + // probation_no: probation_no, + // order_number: item.order_number, + // probation_status: item.probation_status, + // }); + // }), + // ); - return new HttpSuccess({ data: result, total: total }) - } + return new HttpSuccess({ data: result, total: total }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - /** - * API ข้อมูลบุคคลในระบบทดลองงาน - * - * @summary ข้อมูลคนที่อยูาในระบบทดลองงาน - * - */ - @Get("") - async GetPersonal(@Request() request: RequestWithUser, @Query() personal_id: string) { - let _workflow = await new permission().Workflow(request, personal_id, "SYS_PROBATION") - if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION") - const person = await this.personalRepository.findOne({ - where: { personal_id: personal_id }, - }) + /** + * API ข้อมูลบุคคลในระบบทดลองงาน + * + * @summary ข้อมูลคนที่อยูาในระบบทดลองงาน + * + */ + @Get("") + async GetPersonal( + @Request() request: RequestWithUser, + @Query() personal_id: string + ) { + try { + let _workflow = await new permission().Workflow( + request, + personal_id, + "SYS_PROBATION" + ); + if (_workflow == false) + await new permission().PermissionGet(request, "SYS_PROBATION"); + const person = await this.personalRepository.findOne({ + where: { personal_id: personal_id }, + }); - if (!person) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล") - } + if (!person) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } - const probation_no = await this.assignRepository.count({ - where: { personal_id: person.personal_id }, - }) + const probation_no = await this.assignRepository.count({ + where: { personal_id: person.personal_id }, + }); - const result = await { - personal_id: person.personal_id, - name: person.prefixName + person.firstName + " " + person.lastName, - position_line: person.positionName, - position_level: person.positionLevelName, - position_type: person.positionTypeName, - organization: person.organization, - probation_no: probation_no, - order_number: person.order_number, - probation_status: person.probation_status, - } + const result = await { + personal_id: person.personal_id, + name: person.prefixName + person.firstName + " " + person.lastName, + position_line: person.positionName, + position_level: person.positionLevelName, + position_type: person.positionTypeName, + organization: person.organization, + probation_no: probation_no, + order_number: person.order_number, + probation_status: person.probation_status, + }; - return new HttpSuccess(result) - } + return new HttpSuccess(result); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } } diff --git a/src/controllers/ReportController.ts b/src/controllers/ReportController.ts index 6e9d082..c436a4e 100644 --- a/src/controllers/ReportController.ts +++ b/src/controllers/ReportController.ts @@ -70,61 +70,67 @@ export class ReportController extends Controller { @Query() assign_id: string, @Query() evaluate_no: number = 1 ) { - const evaluate = await this.evaluateChairmanRepository.findOne({ - where: { assign_id, no: evaluate_no.toString() }, - }); + try { + const evaluate = await this.evaluateChairmanRepository.findOne({ + where: { assign_id, no: evaluate_no.toString() }, + }); - const result = await this.evaluateResultRepository.findOne({ - where: { assign_id, no: evaluate_no.toString() }, - }); + const result = await this.evaluateResultRepository.findOne({ + where: { assign_id, no: evaluate_no.toString() }, + }); - if (!evaluate || !result) { - throw new HttpError( - HttpStatusCode.NOT_FOUND, - "ไม่พบข้อมูลผลการทดลองปฏิบัติราชการ" - ); + if (!evaluate || !result) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบข้อมูลผลการทดลองปฏิบัติราชการ" + ); + } + + const develop_total_score = + (await (Number(evaluate.develop_orientation_score) + + Number(evaluate.develop_self_learning_score) + + Number(evaluate.develop_training_seminar_score) + + Number(evaluate.develop_other_training_score))) / 4; + const develop_total_percent = + (await (Number(evaluate.develop_orientation_percent) + + Number(evaluate.develop_self_learning_percent) + + Number(evaluate.develop_training_seminar_percent) + + Number(evaluate.develop_other_training_percent))) / 4; + + const data = await { + develop_orientation_score: evaluate.develop_orientation_score, + develop_self_learning_score: evaluate.develop_self_learning_score, + develop_training_seminar_score: evaluate.develop_training_seminar_score, + develop_other_training_score: evaluate.develop_other_training_score, + develop_total_score, + develop_orientation_percent: evaluate.develop_orientation_percent, + develop_self_learning_percent: evaluate.develop_self_learning_percent, + develop_training_seminar_percent: + evaluate.develop_training_seminar_percent, + develop_other_training_percent: evaluate.develop_other_training_percent, + develop_total_percent, + develop_result: evaluate.develop_result, + achievement_score: evaluate.achievement_score, + achievement_score_total: evaluate.achievement_score_total, + achievement_percent: evaluate.achievement_percent, + achievement_result: evaluate.achievement_result, + behavior_score: evaluate.behavior_score, + behavior_score_total: evaluate.behavior_score_total, + behavior_percent: evaluate.behavior_percent, + behavior_result: evaluate.behavior_result, + sum_score: evaluate.sum_score, + sum_percent: evaluate.sum_percent, + reason: result.reson, + pass_result: result.pass_result, + evaluate_date: result.chairman_dated, + }; + + return new HttpSuccess(data); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const develop_total_score = - (await (Number(evaluate.develop_orientation_score) + - Number(evaluate.develop_self_learning_score) + - Number(evaluate.develop_training_seminar_score) + - Number(evaluate.develop_other_training_score))) / 4; - const develop_total_percent = - (await (Number(evaluate.develop_orientation_percent) + - Number(evaluate.develop_self_learning_percent) + - Number(evaluate.develop_training_seminar_percent) + - Number(evaluate.develop_other_training_percent))) / 4; - - const data = await { - develop_orientation_score: evaluate.develop_orientation_score, - develop_self_learning_score: evaluate.develop_self_learning_score, - develop_training_seminar_score: evaluate.develop_training_seminar_score, - develop_other_training_score: evaluate.develop_other_training_score, - develop_total_score, - develop_orientation_percent: evaluate.develop_orientation_percent, - develop_self_learning_percent: evaluate.develop_self_learning_percent, - develop_training_seminar_percent: - evaluate.develop_training_seminar_percent, - develop_other_training_percent: evaluate.develop_other_training_percent, - develop_total_percent, - develop_result: evaluate.develop_result, - achievement_score: evaluate.achievement_score, - achievement_score_total: evaluate.achievement_score_total, - achievement_percent: evaluate.achievement_percent, - achievement_result: evaluate.achievement_result, - behavior_score: evaluate.behavior_score, - behavior_score_total: evaluate.behavior_score_total, - behavior_percent: evaluate.behavior_percent, - behavior_result: evaluate.behavior_result, - sum_score: evaluate.sum_score, - sum_percent: evaluate.sum_percent, - reason: result.reson, - pass_result: result.pass_result, - evaluate_date: result.chairman_dated, - }; - - return new HttpSuccess(data); } /** @@ -135,30 +141,36 @@ export class ReportController extends Controller { */ @Get("pass") async GetPass() { - const lists = await this.personalRepository.find({ - where: { probation_status: 2 }, - }); + try { + const lists = await this.personalRepository.find({ + where: { probation_status: 2 }, + }); - let data: DataPass[] = []; - await Promise.all( - lists.map(async (list) => { - const assign = await AppDataSource.getRepository(Assign).findOne({ - select: ["date_start", "date_finish"], - where: { personal_id: list.personal_id }, - }); - - if (assign) - data.push({ - person: { - id: list.personal_id, - name: `${list.prefixName}${list.firstName} ${list.lastName}`, - }, - assign, + let data: DataPass[] = []; + await Promise.all( + lists.map(async (list) => { + const assign = await AppDataSource.getRepository(Assign).findOne({ + select: ["date_start", "date_finish"], + where: { personal_id: list.personal_id }, }); - }) - ); - return new HttpSuccess(data); + if (assign) + data.push({ + person: { + id: list.personal_id, + name: `${list.prefixName}${list.firstName} ${list.lastName}`, + }, + assign, + }); + }) + ); + + return new HttpSuccess(data); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -169,30 +181,36 @@ export class ReportController extends Controller { */ @Get("not-pass") async GetDataNotPass() { - const lists = await this.personalRepository.find({ - where: { probation_status: 3 }, - }); + try { + const lists = await this.personalRepository.find({ + where: { probation_status: 3 }, + }); - let data: DataPass[] = []; - await Promise.all( - lists.map(async (list) => { - const assign = await AppDataSource.getRepository(Assign).findOne({ - select: ["date_start", "date_finish"], - where: { personal_id: list.personal_id }, - }); - - if (assign) - data.push({ - person: { - id: list.personal_id, - name: `${list.prefixName}${list.firstName} ${list.lastName}`, - }, - assign, + let data: DataPass[] = []; + await Promise.all( + lists.map(async (list) => { + const assign = await AppDataSource.getRepository(Assign).findOne({ + select: ["date_start", "date_finish"], + where: { personal_id: list.personal_id }, }); - }) - ); - return new HttpSuccess(data); + if (assign) + data.push({ + person: { + id: list.personal_id, + name: `${list.prefixName}${list.firstName} ${list.lastName}`, + }, + assign, + }); + }) + ); + + return new HttpSuccess(data); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -204,12 +222,18 @@ export class ReportController extends Controller { @Get("expand") async GetDataExpand() { - const data = await this.personalRepository.find({ - select: ["personal_id"], - where: { probation_status: 7 }, - }); + try { + const data = await this.personalRepository.find({ + select: ["personal_id"], + where: { probation_status: 7 }, + }); - return new HttpSuccess(data); + return new HttpSuccess(data); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -224,43 +248,49 @@ export class ReportController extends Controller { @Body() requestBody: { command_no: string }, @Request() request: RequestWithUser ) { - const personal = await this.personalRepository.findOne({ - where: { personal_id }, - }); - const before = personal; - - if (!personal) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); - } - - personal.order_number = requestBody.command_no; - personal.probation_status = 8; - personal.updateFullName = request.user.name; - personal.updateUserId = request.user.sub; - - this.personalRepository.save(personal, { data: request }); - setLogDataDiff(request, { before, after: personal }); - - const resultText = - (await personal.probation_status) === 2 - ? "ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้รับราชการต่อ" - : "ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ออกจากราชการ"; - - await new CallAPI() - .PostData(request, "/placement/noti", { - subject: "ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ", - body: `ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ ${resultText}`, - receiverUserId: personal_id, - payload: "", - isSendMail: false, - isSendInbox: true, - isSendNotification: true, - }) - .catch((error) => { - console.error("Error calling API:", error); + try { + const personal = await this.personalRepository.findOne({ + where: { personal_id }, }); + const before = personal; - return new HttpSuccess(); + if (!personal) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + personal.order_number = requestBody.command_no; + personal.probation_status = 8; + personal.updateFullName = request.user.name; + personal.updateUserId = request.user.sub; + + this.personalRepository.save(personal, { data: request }); + setLogDataDiff(request, { before, after: personal }); + + const resultText = + (await personal.probation_status) === 2 + ? "ไม่ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้รับราชการต่อ" + : "ต่ำกว่ามาตรฐานที่กำหนด เห็นควรให้ออกจากราชการ"; + + await new CallAPI() + .PostData(request, "/placement/noti", { + subject: "ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ", + body: `ผลการประเมินการทดลองปฏิบัติหน้าที่ราชการ ${resultText}`, + receiverUserId: personal_id, + payload: "", + isSendMail: false, + isSendInbox: true, + isSendNotification: true, + }) + .catch((error) => { + console.error("Error calling API:", error); + }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } /** @@ -275,23 +305,29 @@ export class ReportController extends Controller { @Body() reqBody: { status: number }, @Request() request: RequestWithUser ) { - const personal = await this.personalRepository.findOne({ - where: { personal_id }, - }); - const before = personal; + try { + const personal = await this.personalRepository.findOne({ + where: { personal_id }, + }); + const before = personal; - if (!personal) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + if (!personal) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล"); + } + + personal.probation_status = await reqBody.status; + personal.updateFullName = request.user.name; + personal.updateUserId = request.user.sub; + + await this.personalRepository.save(personal, { data: request }); + setLogDataDiff(request, { before, after: personal }); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - personal.probation_status = await reqBody.status; - personal.updateFullName = request.user.name; - personal.updateUserId = request.user.sub; - - await this.personalRepository.save(personal, { data: request }); - setLogDataDiff(request, { before, after: personal }); - - return new HttpSuccess(); } /** @@ -302,308 +338,317 @@ export class ReportController extends Controller { */ @Get("form-record") async GetDataFormRecord(@Query() id: string) { - const evaluate = await this.evaluateAssessorRepository.findOne({ - where: { id }, - }); - - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const directorData = await this.assignDirectorRepository.findOne({ - select: [ - "personal_id", - "fullname", - "position", - "posType", - "posLevel", - "role", - "dated", - ], - where: { personal_id: evaluate.director_id }, - }); - - if (!directorData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const director = await { - ...directorData, - name: directorData.fullname, - position: directorData.position + directorData.posLevel, - }; - - const achievements = await this.evaluateAchievementRepository.find({ - select: [ - "evaluate_expect_level", - "evaluate_output_level", - "output_desc", - "output_id", - "assign_id", - ], - where: { evaluate_id: evaluate.id }, - order: { updatedAt: "ASC" }, - }); - - if (!achievements) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - let evaluate_expect_level: any = []; - let evaluate_output_level: any = []; - for (let index = 0; index < achievements.length; index++) { - const element = achievements[index]; - - const outputData = await this.assignOutputRepository.findOne({ - select: ["output_desc"], - where: { id: Number(element.output_id), assign_id: element.assign_id }, - }); - await evaluate_expect_level.push({ - title: outputData?.output_desc ?? "-", - col1: element.evaluate_expect_level == 1 ? "/" : "", - col2: element.evaluate_expect_level == 2 ? "/" : "", - col3: element.evaluate_expect_level == 3 ? "/" : "", - col4: element.evaluate_expect_level == 4 ? "/" : "", - col5: element.evaluate_expect_level == 5 ? "/" : "", + try { + const evaluate = await this.evaluateAssessorRepository.findOne({ + where: { id }, }); - await evaluate_output_level.push({ - title: element.output_desc, - col1: element.evaluate_output_level == 1 ? "/" : "", - col2: element.evaluate_output_level == 2 ? "/" : "", - col3: element.evaluate_output_level == 3 ? "/" : "", - col4: element.evaluate_output_level == 4 ? "/" : "", - col5: element.evaluate_output_level == 5 ? "/" : "", + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const directorData = await this.assignDirectorRepository.findOne({ + select: [ + "personal_id", + "fullname", + "position", + "posType", + "posLevel", + "role", + "dated", + ], + where: { personal_id: evaluate.director_id }, }); + + if (!directorData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const director = await { + ...directorData, + name: directorData.fullname, + position: directorData.position + directorData.posLevel, + }; + + const achievements = await this.evaluateAchievementRepository.find({ + select: [ + "evaluate_expect_level", + "evaluate_output_level", + "output_desc", + "output_id", + "assign_id", + ], + where: { evaluate_id: evaluate.id }, + order: { updatedAt: "ASC" }, + }); + + if (!achievements) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + let evaluate_expect_level: any = []; + let evaluate_output_level: any = []; + for (let index = 0; index < achievements.length; index++) { + const element = achievements[index]; + + const outputData = await this.assignOutputRepository.findOne({ + select: ["output_desc"], + where: { + id: Number(element.output_id), + assign_id: element.assign_id, + }, + }); + await evaluate_expect_level.push({ + title: outputData?.output_desc ?? "-", + col1: element.evaluate_expect_level == 1 ? "/" : "", + col2: element.evaluate_expect_level == 2 ? "/" : "", + col3: element.evaluate_expect_level == 3 ? "/" : "", + col4: element.evaluate_expect_level == 4 ? "/" : "", + col5: element.evaluate_expect_level == 5 ? "/" : "", + }); + + await evaluate_output_level.push({ + title: element.output_desc, + col1: element.evaluate_output_level == 1 ? "/" : "", + col2: element.evaluate_output_level == 2 ? "/" : "", + col3: element.evaluate_output_level == 3 ? "/" : "", + col4: element.evaluate_output_level == 4 ? "/" : "", + col5: element.evaluate_output_level == 5 ? "/" : "", + }); + } + + let achievement = { + evaluate_expect_level: evaluate_expect_level, + evaluate_output_level: evaluate_output_level, + }; + + const evaluateData = await { + id: evaluate.id, + no: evaluate.no, + date_start: evaluate.date_start, + date_finish: evaluate.date_finish, + sign_dated: evaluate.assessor_dated, + knowledge_level: { + col1: evaluate.knowledge_level == 1 ? "/" : "", + col2: evaluate.knowledge_level == 2 ? "/" : "", + col3: evaluate.knowledge_level == 3 ? "/" : "", + col4: evaluate.knowledge_level == 4 ? "/" : "", + col5: evaluate.knowledge_level == 5 ? "/" : "", + }, + skill_level: { + col1: evaluate.skill_level == 1 ? "/" : "", + col2: evaluate.skill_level == 2 ? "/" : "", + col3: evaluate.skill_level == 3 ? "/" : "", + col4: evaluate.skill_level == 4 ? "/" : "", + col5: evaluate.skill_level == 5 ? "/" : "", + }, + competency_level: { + col1: evaluate.competency_level == 1 ? "/" : "", + col2: evaluate.competency_level == 2 ? "/" : "", + col3: evaluate.competency_level == 3 ? "/" : "", + col4: evaluate.competency_level == 4 ? "/" : "", + col5: evaluate.competency_level == 5 ? "/" : "", + }, + learn_level: { + col1: evaluate.learn_level == 1 ? "/" : "", + col2: evaluate.learn_level == 2 ? "/" : "", + col3: evaluate.learn_level == 3 ? "/" : "", + col4: evaluate.learn_level == 4 ? "/" : "", + col5: evaluate.learn_level == 5 ? "/" : "", + }, + apply_level: { + col1: evaluate.apply_level == 1 ? "/" : "", + col2: evaluate.apply_level == 2 ? "/" : "", + col3: evaluate.apply_level == 3 ? "/" : "", + col4: evaluate.apply_level == 4 ? "/" : "", + col5: evaluate.apply_level == 5 ? "/" : "", + }, + achievement_other_desc: evaluate.achievement_other_desc, + achievement_other_level: + evaluate.achievement_other_level != null + ? { + col1: evaluate.achievement_other_level == 1 ? "/" : "", + col2: evaluate.achievement_other_level == 2 ? "/" : "", + col3: evaluate.achievement_other_level == 3 ? "/" : "", + col4: evaluate.achievement_other_level == 4 ? "/" : "", + col5: evaluate.achievement_other_level == 5 ? "/" : "", + } + : { + col1: "", + col2: "", + col3: "", + col4: "", + col5: "", + }, + achievement_strength_desc: evaluate.achievement_strength_desc, + achievement_improve_desc: evaluate.achievement_improve_desc, + conduct1_level: { + col1: evaluate.conduct1_level == 1 ? "/" : "", + col2: evaluate.conduct1_level == 2 ? "/" : "", + col3: evaluate.conduct1_level == 3 ? "/" : "", + col4: evaluate.conduct1_level == 4 ? "/" : "", + col5: evaluate.conduct1_level == 5 ? "/" : "", + }, + conduct2_level: { + col1: evaluate.conduct2_level == 1 ? "/" : "", + col2: evaluate.conduct2_level == 2 ? "/" : "", + col3: evaluate.conduct2_level == 3 ? "/" : "", + col4: evaluate.conduct2_level == 4 ? "/" : "", + col5: evaluate.conduct2_level == 5 ? "/" : "", + }, + conduct3_level: { + col1: evaluate.conduct3_level == 1 ? "/" : "", + col2: evaluate.conduct3_level == 2 ? "/" : "", + col3: evaluate.conduct3_level == 3 ? "/" : "", + col4: evaluate.conduct3_level == 4 ? "/" : "", + col5: evaluate.conduct3_level == 5 ? "/" : "", + }, + conduct4_level: { + col1: evaluate.conduct4_level == 1 ? "/" : "", + col2: evaluate.conduct4_level == 2 ? "/" : "", + col3: evaluate.conduct4_level == 3 ? "/" : "", + col4: evaluate.conduct4_level == 4 ? "/" : "", + col5: evaluate.conduct4_level == 5 ? "/" : "", + }, + moral1_level: { + col1: evaluate.moral1_level == 1 ? "/" : "", + col2: evaluate.moral1_level == 2 ? "/" : "", + col3: evaluate.moral1_level == 3 ? "/" : "", + col4: evaluate.moral1_level == 4 ? "/" : "", + col5: evaluate.moral1_level == 5 ? "/" : "", + }, + moral2_level: { + col1: evaluate.moral2_level == 1 ? "/" : "", + col2: evaluate.moral2_level == 2 ? "/" : "", + col3: evaluate.moral2_level == 3 ? "/" : "", + col4: evaluate.moral2_level == 4 ? "/" : "", + col5: evaluate.moral2_level == 5 ? "/" : "", + }, + moral3_level: { + col1: evaluate.moral3_level == 1 ? "/" : "", + col2: evaluate.moral3_level == 2 ? "/" : "", + col3: evaluate.moral3_level == 3 ? "/" : "", + col4: evaluate.moral3_level == 4 ? "/" : "", + col5: evaluate.moral3_level == 5 ? "/" : "", + }, + discipline1_level: { + col1: evaluate.discipline1_level == 1 ? "/" : "", + col2: evaluate.discipline1_level == 2 ? "/" : "", + col3: evaluate.discipline1_level == 3 ? "/" : "", + col4: evaluate.discipline1_level == 4 ? "/" : "", + col5: evaluate.discipline1_level == 5 ? "/" : "", + }, + discipline2_level: { + col1: evaluate.discipline2_level == 1 ? "/" : "", + col2: evaluate.discipline2_level == 2 ? "/" : "", + col3: evaluate.discipline2_level == 3 ? "/" : "", + col4: evaluate.discipline2_level == 4 ? "/" : "", + col5: evaluate.discipline2_level == 5 ? "/" : "", + }, + discipline3_level: { + col1: evaluate.discipline3_level == 1 ? "/" : "", + col2: evaluate.discipline3_level == 2 ? "/" : "", + col3: evaluate.discipline3_level == 3 ? "/" : "", + col4: evaluate.discipline3_level == 4 ? "/" : "", + col5: evaluate.discipline3_level == 5 ? "/" : "", + }, + discipline4_level: { + col1: evaluate.discipline4_level == 1 ? "/" : "", + col2: evaluate.discipline4_level == 2 ? "/" : "", + col3: evaluate.discipline4_level == 3 ? "/" : "", + col4: evaluate.discipline4_level == 4 ? "/" : "", + col5: evaluate.discipline4_level == 5 ? "/" : "", + }, + discipline5_level: { + col1: evaluate.discipline5_level == 1 ? "/" : "", + col2: evaluate.discipline5_level == 2 ? "/" : "", + col3: evaluate.discipline5_level == 3 ? "/" : "", + col4: evaluate.discipline5_level == 4 ? "/" : "", + col5: evaluate.discipline5_level == 5 ? "/" : "", + }, + behavior_other_desc: evaluate.behavior_other_desc, + behavior_other_level: + evaluate.behavior_other_level != null + ? { + col1: evaluate.behavior_other_level == 1 ? "/" : "", + col2: evaluate.behavior_other_level == 2 ? "/" : "", + col3: evaluate.behavior_other_level == 3 ? "/" : "", + col4: evaluate.behavior_other_level == 4 ? "/" : "", + col5: evaluate.behavior_other_level == 5 ? "/" : "", + } + : { + col1: "", + col2: "", + col3: "", + col4: "", + col5: "", + }, + + behavior_strength_desc: evaluate.behavior_strength_desc, + behavior_improve_desc: evaluate.behavior_improve_desc, + orientation: evaluate.orientation, + self_learning: evaluate.self_learning, + training_seminar: evaluate.training_seminar, + other_training: evaluate.other_training, + createdAt: evaluate.createdAt, + updatedAt: evaluate.updatedAt, + achievements: achievement, + role: director.role, + }; + + const assign = await AppDataSource.getRepository(Assign).findOne({ + select: ["id", "personal_id", "round_no", "date_start", "date_finish"], + where: { id: evaluate.assign_id }, + }); + + if (!assign) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const experimenteeData = await this.personalRepository.findOne({ + where: { + personal_id: assign.personal_id, + }, + }); + + if (!experimenteeData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const splitOc = await experimenteeData.organization.split(" "); + const splitOcAmount = await splitOc.length; + const organization = await experimenteeData.organization.replace( + /\//g, + " " + ); + + const experimentee = await { + ...experimenteeData, + organization: organization, + name: `${experimenteeData.prefixName}${experimenteeData.firstName} ${experimenteeData.lastName}`, + PositionLevelName: experimenteeData.positionLevelName, + PositionLineName: experimenteeData.positionLineName, + Position: experimenteeData.positionName, + Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", + OrganizationOrganization: + splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", + Oc: experimenteeData.orgRootName, + PositionLevel: + experimenteeData.positionName + experimenteeData.positionLevelName, + }; + + const data = await { + experimentee: experimentee ? experimentee : null, + director: director ? director : null, + assign, + evaluate: evaluateData, + }; + return new HttpSuccess(data); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - let achievement = { - evaluate_expect_level: evaluate_expect_level, - evaluate_output_level: evaluate_output_level, - }; - - const evaluateData = await { - id: evaluate.id, - no: evaluate.no, - date_start: evaluate.date_start, - date_finish: evaluate.date_finish, - sign_dated: evaluate.assessor_dated, - knowledge_level: { - col1: evaluate.knowledge_level == 1 ? "/" : "", - col2: evaluate.knowledge_level == 2 ? "/" : "", - col3: evaluate.knowledge_level == 3 ? "/" : "", - col4: evaluate.knowledge_level == 4 ? "/" : "", - col5: evaluate.knowledge_level == 5 ? "/" : "", - }, - skill_level: { - col1: evaluate.skill_level == 1 ? "/" : "", - col2: evaluate.skill_level == 2 ? "/" : "", - col3: evaluate.skill_level == 3 ? "/" : "", - col4: evaluate.skill_level == 4 ? "/" : "", - col5: evaluate.skill_level == 5 ? "/" : "", - }, - competency_level: { - col1: evaluate.competency_level == 1 ? "/" : "", - col2: evaluate.competency_level == 2 ? "/" : "", - col3: evaluate.competency_level == 3 ? "/" : "", - col4: evaluate.competency_level == 4 ? "/" : "", - col5: evaluate.competency_level == 5 ? "/" : "", - }, - learn_level: { - col1: evaluate.learn_level == 1 ? "/" : "", - col2: evaluate.learn_level == 2 ? "/" : "", - col3: evaluate.learn_level == 3 ? "/" : "", - col4: evaluate.learn_level == 4 ? "/" : "", - col5: evaluate.learn_level == 5 ? "/" : "", - }, - apply_level: { - col1: evaluate.apply_level == 1 ? "/" : "", - col2: evaluate.apply_level == 2 ? "/" : "", - col3: evaluate.apply_level == 3 ? "/" : "", - col4: evaluate.apply_level == 4 ? "/" : "", - col5: evaluate.apply_level == 5 ? "/" : "", - }, - achievement_other_desc: evaluate.achievement_other_desc, - achievement_other_level: - evaluate.achievement_other_level != null - ? { - col1: evaluate.achievement_other_level == 1 ? "/" : "", - col2: evaluate.achievement_other_level == 2 ? "/" : "", - col3: evaluate.achievement_other_level == 3 ? "/" : "", - col4: evaluate.achievement_other_level == 4 ? "/" : "", - col5: evaluate.achievement_other_level == 5 ? "/" : "", - } - : { - col1: "", - col2: "", - col3: "", - col4: "", - col5: "", - }, - achievement_strength_desc: evaluate.achievement_strength_desc, - achievement_improve_desc: evaluate.achievement_improve_desc, - conduct1_level: { - col1: evaluate.conduct1_level == 1 ? "/" : "", - col2: evaluate.conduct1_level == 2 ? "/" : "", - col3: evaluate.conduct1_level == 3 ? "/" : "", - col4: evaluate.conduct1_level == 4 ? "/" : "", - col5: evaluate.conduct1_level == 5 ? "/" : "", - }, - conduct2_level: { - col1: evaluate.conduct2_level == 1 ? "/" : "", - col2: evaluate.conduct2_level == 2 ? "/" : "", - col3: evaluate.conduct2_level == 3 ? "/" : "", - col4: evaluate.conduct2_level == 4 ? "/" : "", - col5: evaluate.conduct2_level == 5 ? "/" : "", - }, - conduct3_level: { - col1: evaluate.conduct3_level == 1 ? "/" : "", - col2: evaluate.conduct3_level == 2 ? "/" : "", - col3: evaluate.conduct3_level == 3 ? "/" : "", - col4: evaluate.conduct3_level == 4 ? "/" : "", - col5: evaluate.conduct3_level == 5 ? "/" : "", - }, - conduct4_level: { - col1: evaluate.conduct4_level == 1 ? "/" : "", - col2: evaluate.conduct4_level == 2 ? "/" : "", - col3: evaluate.conduct4_level == 3 ? "/" : "", - col4: evaluate.conduct4_level == 4 ? "/" : "", - col5: evaluate.conduct4_level == 5 ? "/" : "", - }, - moral1_level: { - col1: evaluate.moral1_level == 1 ? "/" : "", - col2: evaluate.moral1_level == 2 ? "/" : "", - col3: evaluate.moral1_level == 3 ? "/" : "", - col4: evaluate.moral1_level == 4 ? "/" : "", - col5: evaluate.moral1_level == 5 ? "/" : "", - }, - moral2_level: { - col1: evaluate.moral2_level == 1 ? "/" : "", - col2: evaluate.moral2_level == 2 ? "/" : "", - col3: evaluate.moral2_level == 3 ? "/" : "", - col4: evaluate.moral2_level == 4 ? "/" : "", - col5: evaluate.moral2_level == 5 ? "/" : "", - }, - moral3_level: { - col1: evaluate.moral3_level == 1 ? "/" : "", - col2: evaluate.moral3_level == 2 ? "/" : "", - col3: evaluate.moral3_level == 3 ? "/" : "", - col4: evaluate.moral3_level == 4 ? "/" : "", - col5: evaluate.moral3_level == 5 ? "/" : "", - }, - discipline1_level: { - col1: evaluate.discipline1_level == 1 ? "/" : "", - col2: evaluate.discipline1_level == 2 ? "/" : "", - col3: evaluate.discipline1_level == 3 ? "/" : "", - col4: evaluate.discipline1_level == 4 ? "/" : "", - col5: evaluate.discipline1_level == 5 ? "/" : "", - }, - discipline2_level: { - col1: evaluate.discipline2_level == 1 ? "/" : "", - col2: evaluate.discipline2_level == 2 ? "/" : "", - col3: evaluate.discipline2_level == 3 ? "/" : "", - col4: evaluate.discipline2_level == 4 ? "/" : "", - col5: evaluate.discipline2_level == 5 ? "/" : "", - }, - discipline3_level: { - col1: evaluate.discipline3_level == 1 ? "/" : "", - col2: evaluate.discipline3_level == 2 ? "/" : "", - col3: evaluate.discipline3_level == 3 ? "/" : "", - col4: evaluate.discipline3_level == 4 ? "/" : "", - col5: evaluate.discipline3_level == 5 ? "/" : "", - }, - discipline4_level: { - col1: evaluate.discipline4_level == 1 ? "/" : "", - col2: evaluate.discipline4_level == 2 ? "/" : "", - col3: evaluate.discipline4_level == 3 ? "/" : "", - col4: evaluate.discipline4_level == 4 ? "/" : "", - col5: evaluate.discipline4_level == 5 ? "/" : "", - }, - discipline5_level: { - col1: evaluate.discipline5_level == 1 ? "/" : "", - col2: evaluate.discipline5_level == 2 ? "/" : "", - col3: evaluate.discipline5_level == 3 ? "/" : "", - col4: evaluate.discipline5_level == 4 ? "/" : "", - col5: evaluate.discipline5_level == 5 ? "/" : "", - }, - behavior_other_desc: evaluate.behavior_other_desc, - behavior_other_level: - evaluate.behavior_other_level != null - ? { - col1: evaluate.behavior_other_level == 1 ? "/" : "", - col2: evaluate.behavior_other_level == 2 ? "/" : "", - col3: evaluate.behavior_other_level == 3 ? "/" : "", - col4: evaluate.behavior_other_level == 4 ? "/" : "", - col5: evaluate.behavior_other_level == 5 ? "/" : "", - } - : { - col1: "", - col2: "", - col3: "", - col4: "", - col5: "", - }, - - behavior_strength_desc: evaluate.behavior_strength_desc, - behavior_improve_desc: evaluate.behavior_improve_desc, - orientation: evaluate.orientation, - self_learning: evaluate.self_learning, - training_seminar: evaluate.training_seminar, - other_training: evaluate.other_training, - createdAt: evaluate.createdAt, - updatedAt: evaluate.updatedAt, - achievements: achievement, - role: director.role, - }; - - const assign = await AppDataSource.getRepository(Assign).findOne({ - select: ["id", "personal_id", "round_no", "date_start", "date_finish"], - where: { id: evaluate.assign_id }, - }); - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const experimenteeData = await this.personalRepository.findOne({ - where: { - personal_id: assign.personal_id, - }, - }); - - if (!experimenteeData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const splitOc = await experimenteeData.organization.split(" "); - const splitOcAmount = await splitOc.length; - const organization = await experimenteeData.organization.replace( - /\//g, - " " - ); - - const experimentee = await { - ...experimenteeData, - organization: organization, - name: `${experimenteeData.prefixName}${experimenteeData.firstName} ${experimenteeData.lastName}`, - PositionLevelName: experimenteeData.positionLevelName, - PositionLineName: experimenteeData.positionLineName, - Position: experimenteeData.positionName, - Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", - OrganizationOrganization: - splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", - Oc: experimenteeData.orgRootName, - PositionLevel: - experimenteeData.positionName + experimenteeData.positionLevelName, - }; - - const data = await { - experimentee: experimentee ? experimentee : null, - director: director ? director : null, - assign, - evaluate: evaluateData, - }; - return new HttpSuccess(data); } /** @@ -617,261 +662,267 @@ export class ReportController extends Controller { @Query() id: string, @Request() request: RequestWithUser ) { - const evaluate = await this.evaluateCommanderRepository.findOne({ - where: { id }, - }); + try { + const evaluate = await this.evaluateCommanderRepository.findOne({ + where: { id }, + }); - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const evaluateData = await { + id: evaluate.id, + no: evaluate.no, + date_start: evaluate.date_start, + date_finish: evaluate.date_finish, + sign_dated: evaluate.commander_dated, + knowledge_level: { + col1: evaluate.knowledge_level == 1 ? "/" : "", + col2: evaluate.knowledge_level == 2 ? "/" : "", + col3: evaluate.knowledge_level == 3 ? "/" : "", + col4: evaluate.knowledge_level == 4 ? "/" : "", + col5: evaluate.knowledge_level == 5 ? "/" : "", + }, + skill_level: { + col1: evaluate.skill_level == 1 ? "/" : "", + col2: evaluate.skill_level == 2 ? "/" : "", + col3: evaluate.skill_level == 3 ? "/" : "", + col4: evaluate.skill_level == 4 ? "/" : "", + col5: evaluate.skill_level == 5 ? "/" : "", + }, + competency_level: { + col1: evaluate.competency_level == 1 ? "/" : "", + col2: evaluate.competency_level == 2 ? "/" : "", + col3: evaluate.competency_level == 3 ? "/" : "", + col4: evaluate.competency_level == 4 ? "/" : "", + col5: evaluate.competency_level == 5 ? "/" : "", + }, + learn_level: { + col1: evaluate.learn_level == 1 ? "/" : "", + col2: evaluate.learn_level == 2 ? "/" : "", + col3: evaluate.learn_level == 3 ? "/" : "", + col4: evaluate.learn_level == 4 ? "/" : "", + col5: evaluate.learn_level == 5 ? "/" : "", + }, + apply_level: { + col1: evaluate.apply_level == 1 ? "/" : "", + col2: evaluate.apply_level == 2 ? "/" : "", + col3: evaluate.apply_level == 3 ? "/" : "", + col4: evaluate.apply_level == 4 ? "/" : "", + col5: evaluate.apply_level == 5 ? "/" : "", + }, + success_level: { + col1: evaluate.success_level == 1 ? "/" : "", + col2: evaluate.success_level == 2 ? "/" : "", + col3: evaluate.success_level == 3 ? "/" : "", + col4: evaluate.success_level == 4 ? "/" : "", + col5: evaluate.success_level == 5 ? "/" : "", + }, + achievement_other_desc: evaluate.achievement_other_desc, + achievement_other_level: + evaluate.achievement_other_level != null + ? { + col1: evaluate.achievement_other_level == 1 ? "/" : "", + col2: evaluate.achievement_other_level == 2 ? "/" : "", + col3: evaluate.achievement_other_level == 3 ? "/" : "", + col4: evaluate.achievement_other_level == 4 ? "/" : "", + col5: evaluate.achievement_other_level == 5 ? "/" : "", + } + : { + col1: "", + col2: "", + col3: "", + col4: "", + col5: "", + }, + conduct1_level: { + col1: evaluate.conduct1_level == 1 ? "/" : "", + col2: evaluate.conduct1_level == 2 ? "/" : "", + col3: evaluate.conduct1_level == 3 ? "/" : "", + col4: evaluate.conduct1_level == 4 ? "/" : "", + col5: evaluate.conduct1_level == 5 ? "/" : "", + }, + conduct2_level: { + col1: evaluate.conduct2_level == 1 ? "/" : "", + col2: evaluate.conduct2_level == 2 ? "/" : "", + col3: evaluate.conduct2_level == 3 ? "/" : "", + col4: evaluate.conduct2_level == 4 ? "/" : "", + col5: evaluate.conduct2_level == 5 ? "/" : "", + }, + conduct3_level: { + col1: evaluate.conduct3_level == 1 ? "/" : "", + col2: evaluate.conduct3_level == 2 ? "/" : "", + col3: evaluate.conduct3_level == 3 ? "/" : "", + col4: evaluate.conduct3_level == 4 ? "/" : "", + col5: evaluate.conduct3_level == 5 ? "/" : "", + }, + conduct4_level: { + col1: evaluate.conduct4_level == 1 ? "/" : "", + col2: evaluate.conduct4_level == 2 ? "/" : "", + col3: evaluate.conduct4_level == 3 ? "/" : "", + col4: evaluate.conduct4_level == 4 ? "/" : "", + col5: evaluate.conduct4_level == 5 ? "/" : "", + }, + moral1_level: { + col1: evaluate.moral1_level == 1 ? "/" : "", + col2: evaluate.moral1_level == 2 ? "/" : "", + col3: evaluate.moral1_level == 3 ? "/" : "", + col4: evaluate.moral1_level == 4 ? "/" : "", + col5: evaluate.moral1_level == 5 ? "/" : "", + }, + moral2_level: { + col1: evaluate.moral2_level == 1 ? "/" : "", + col2: evaluate.moral2_level == 2 ? "/" : "", + col3: evaluate.moral2_level == 3 ? "/" : "", + col4: evaluate.moral2_level == 4 ? "/" : "", + col5: evaluate.moral2_level == 5 ? "/" : "", + }, + moral3_level: { + col1: evaluate.moral3_level == 1 ? "/" : "", + col2: evaluate.moral3_level == 2 ? "/" : "", + col3: evaluate.moral3_level == 3 ? "/" : "", + col4: evaluate.moral3_level == 4 ? "/" : "", + col5: evaluate.moral3_level == 5 ? "/" : "", + }, + discipline1_level: { + col1: evaluate.discipline1_level == 1 ? "/" : "", + col2: evaluate.discipline1_level == 2 ? "/" : "", + col3: evaluate.discipline1_level == 3 ? "/" : "", + col4: evaluate.discipline1_level == 4 ? "/" : "", + col5: evaluate.discipline1_level == 5 ? "/" : "", + }, + discipline2_level: { + col1: evaluate.discipline2_level == 1 ? "/" : "", + col2: evaluate.discipline2_level == 2 ? "/" : "", + col3: evaluate.discipline2_level == 3 ? "/" : "", + col4: evaluate.discipline2_level == 4 ? "/" : "", + col5: evaluate.discipline2_level == 5 ? "/" : "", + }, + discipline3_level: { + col1: evaluate.discipline3_level == 1 ? "/" : "", + col2: evaluate.discipline3_level == 2 ? "/" : "", + col3: evaluate.discipline3_level == 3 ? "/" : "", + col4: evaluate.discipline3_level == 4 ? "/" : "", + col5: evaluate.discipline3_level == 5 ? "/" : "", + }, + discipline4_level: { + col1: evaluate.discipline4_level == 1 ? "/" : "", + col2: evaluate.discipline4_level == 2 ? "/" : "", + col3: evaluate.discipline4_level == 3 ? "/" : "", + col4: evaluate.discipline4_level == 4 ? "/" : "", + col5: evaluate.discipline4_level == 5 ? "/" : "", + }, + discipline5_level: { + col1: evaluate.discipline5_level == 1 ? "/" : "", + col2: evaluate.discipline5_level == 2 ? "/" : "", + col3: evaluate.discipline5_level == 3 ? "/" : "", + col4: evaluate.discipline5_level == 4 ? "/" : "", + col5: evaluate.discipline5_level == 5 ? "/" : "", + }, + behavior_other_desc: evaluate.behavior_other_desc, + behavior_other_level: + evaluate.behavior_other_level != null + ? { + col1: evaluate.behavior_other_level == 1 ? "/" : "", + col2: evaluate.behavior_other_level == 2 ? "/" : "", + col3: evaluate.behavior_other_level == 3 ? "/" : "", + col4: evaluate.behavior_other_level == 4 ? "/" : "", + col5: evaluate.behavior_other_level == 5 ? "/" : "", + } + : { + col1: "", + col2: "", + col3: "", + col4: "", + col5: "", + }, + behavior_strength_desc: evaluate.behavior_strength_desc, + behavior_improve_desc: evaluate.behavior_improve_desc, + orientation: evaluate.orientation, + self_learning: evaluate.self_learning, + training_seminar: evaluate.training_seminar, + other_training: evaluate.other_training, + createdAt: evaluate.createdAt, + updatedAt: evaluate.updatedAt, + }; + + const assign = await AppDataSource.getRepository(Assign).findOne({ + select: ["id", "personal_id", "round_no", "date_start", "date_finish"], + where: { id: evaluate.assign_id }, + }); + + if (!assign) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const experimenteeData = await this.personalRepository.findOne({ + where: { + personal_id: assign.personal_id, + }, + }); + + if (!experimenteeData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const splitOc = await experimenteeData.organization.split(" "); + const splitOcAmount = await splitOc.length; + const organization = await experimenteeData.organization.replace( + /\//g, + " " + ); + + const experimentee = await { + ...experimenteeData, + organization: organization, + name: `${experimenteeData.prefixName}${experimenteeData.firstName} ${experimenteeData.lastName}`, + PositionLevelName: experimenteeData.positionLevelName, + PositionLineName: experimenteeData.positionLineName, + Position: experimenteeData.positionName, + Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", + OrganizationOrganization: + splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", + Oc: experimenteeData.orgRootName, + PositionLevel: + experimenteeData.positionName + experimenteeData.positionLevelName, + }; + + const commanderData = await this.assignDirectorRepository.findOne({ + select: [ + "personal_id", + "fullname", + "position", + "position", + "posType", + "posLevel", + "role", + "dated", + ], + where: { personal_id: evaluate.director_id }, + }); + + if (!commanderData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const commander = await { + ...commanderData, + name: commanderData.fullname, + Position: commanderData.position + commanderData.posLevel, + }; + + return new HttpSuccess({ + experimentee: experimentee ? experimentee : null, + commander: commander ? commander : null, + assign, + evaluate: evaluateData, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const evaluateData = await { - id: evaluate.id, - no: evaluate.no, - date_start: evaluate.date_start, - date_finish: evaluate.date_finish, - sign_dated: evaluate.commander_dated, - knowledge_level: { - col1: evaluate.knowledge_level == 1 ? "/" : "", - col2: evaluate.knowledge_level == 2 ? "/" : "", - col3: evaluate.knowledge_level == 3 ? "/" : "", - col4: evaluate.knowledge_level == 4 ? "/" : "", - col5: evaluate.knowledge_level == 5 ? "/" : "", - }, - skill_level: { - col1: evaluate.skill_level == 1 ? "/" : "", - col2: evaluate.skill_level == 2 ? "/" : "", - col3: evaluate.skill_level == 3 ? "/" : "", - col4: evaluate.skill_level == 4 ? "/" : "", - col5: evaluate.skill_level == 5 ? "/" : "", - }, - competency_level: { - col1: evaluate.competency_level == 1 ? "/" : "", - col2: evaluate.competency_level == 2 ? "/" : "", - col3: evaluate.competency_level == 3 ? "/" : "", - col4: evaluate.competency_level == 4 ? "/" : "", - col5: evaluate.competency_level == 5 ? "/" : "", - }, - learn_level: { - col1: evaluate.learn_level == 1 ? "/" : "", - col2: evaluate.learn_level == 2 ? "/" : "", - col3: evaluate.learn_level == 3 ? "/" : "", - col4: evaluate.learn_level == 4 ? "/" : "", - col5: evaluate.learn_level == 5 ? "/" : "", - }, - apply_level: { - col1: evaluate.apply_level == 1 ? "/" : "", - col2: evaluate.apply_level == 2 ? "/" : "", - col3: evaluate.apply_level == 3 ? "/" : "", - col4: evaluate.apply_level == 4 ? "/" : "", - col5: evaluate.apply_level == 5 ? "/" : "", - }, - success_level: { - col1: evaluate.success_level == 1 ? "/" : "", - col2: evaluate.success_level == 2 ? "/" : "", - col3: evaluate.success_level == 3 ? "/" : "", - col4: evaluate.success_level == 4 ? "/" : "", - col5: evaluate.success_level == 5 ? "/" : "", - }, - achievement_other_desc: evaluate.achievement_other_desc, - achievement_other_level: - evaluate.achievement_other_level != null - ? { - col1: evaluate.achievement_other_level == 1 ? "/" : "", - col2: evaluate.achievement_other_level == 2 ? "/" : "", - col3: evaluate.achievement_other_level == 3 ? "/" : "", - col4: evaluate.achievement_other_level == 4 ? "/" : "", - col5: evaluate.achievement_other_level == 5 ? "/" : "", - } - : { - col1: "", - col2: "", - col3: "", - col4: "", - col5: "", - }, - conduct1_level: { - col1: evaluate.conduct1_level == 1 ? "/" : "", - col2: evaluate.conduct1_level == 2 ? "/" : "", - col3: evaluate.conduct1_level == 3 ? "/" : "", - col4: evaluate.conduct1_level == 4 ? "/" : "", - col5: evaluate.conduct1_level == 5 ? "/" : "", - }, - conduct2_level: { - col1: evaluate.conduct2_level == 1 ? "/" : "", - col2: evaluate.conduct2_level == 2 ? "/" : "", - col3: evaluate.conduct2_level == 3 ? "/" : "", - col4: evaluate.conduct2_level == 4 ? "/" : "", - col5: evaluate.conduct2_level == 5 ? "/" : "", - }, - conduct3_level: { - col1: evaluate.conduct3_level == 1 ? "/" : "", - col2: evaluate.conduct3_level == 2 ? "/" : "", - col3: evaluate.conduct3_level == 3 ? "/" : "", - col4: evaluate.conduct3_level == 4 ? "/" : "", - col5: evaluate.conduct3_level == 5 ? "/" : "", - }, - conduct4_level: { - col1: evaluate.conduct4_level == 1 ? "/" : "", - col2: evaluate.conduct4_level == 2 ? "/" : "", - col3: evaluate.conduct4_level == 3 ? "/" : "", - col4: evaluate.conduct4_level == 4 ? "/" : "", - col5: evaluate.conduct4_level == 5 ? "/" : "", - }, - moral1_level: { - col1: evaluate.moral1_level == 1 ? "/" : "", - col2: evaluate.moral1_level == 2 ? "/" : "", - col3: evaluate.moral1_level == 3 ? "/" : "", - col4: evaluate.moral1_level == 4 ? "/" : "", - col5: evaluate.moral1_level == 5 ? "/" : "", - }, - moral2_level: { - col1: evaluate.moral2_level == 1 ? "/" : "", - col2: evaluate.moral2_level == 2 ? "/" : "", - col3: evaluate.moral2_level == 3 ? "/" : "", - col4: evaluate.moral2_level == 4 ? "/" : "", - col5: evaluate.moral2_level == 5 ? "/" : "", - }, - moral3_level: { - col1: evaluate.moral3_level == 1 ? "/" : "", - col2: evaluate.moral3_level == 2 ? "/" : "", - col3: evaluate.moral3_level == 3 ? "/" : "", - col4: evaluate.moral3_level == 4 ? "/" : "", - col5: evaluate.moral3_level == 5 ? "/" : "", - }, - discipline1_level: { - col1: evaluate.discipline1_level == 1 ? "/" : "", - col2: evaluate.discipline1_level == 2 ? "/" : "", - col3: evaluate.discipline1_level == 3 ? "/" : "", - col4: evaluate.discipline1_level == 4 ? "/" : "", - col5: evaluate.discipline1_level == 5 ? "/" : "", - }, - discipline2_level: { - col1: evaluate.discipline2_level == 1 ? "/" : "", - col2: evaluate.discipline2_level == 2 ? "/" : "", - col3: evaluate.discipline2_level == 3 ? "/" : "", - col4: evaluate.discipline2_level == 4 ? "/" : "", - col5: evaluate.discipline2_level == 5 ? "/" : "", - }, - discipline3_level: { - col1: evaluate.discipline3_level == 1 ? "/" : "", - col2: evaluate.discipline3_level == 2 ? "/" : "", - col3: evaluate.discipline3_level == 3 ? "/" : "", - col4: evaluate.discipline3_level == 4 ? "/" : "", - col5: evaluate.discipline3_level == 5 ? "/" : "", - }, - discipline4_level: { - col1: evaluate.discipline4_level == 1 ? "/" : "", - col2: evaluate.discipline4_level == 2 ? "/" : "", - col3: evaluate.discipline4_level == 3 ? "/" : "", - col4: evaluate.discipline4_level == 4 ? "/" : "", - col5: evaluate.discipline4_level == 5 ? "/" : "", - }, - discipline5_level: { - col1: evaluate.discipline5_level == 1 ? "/" : "", - col2: evaluate.discipline5_level == 2 ? "/" : "", - col3: evaluate.discipline5_level == 3 ? "/" : "", - col4: evaluate.discipline5_level == 4 ? "/" : "", - col5: evaluate.discipline5_level == 5 ? "/" : "", - }, - behavior_other_desc: evaluate.behavior_other_desc, - behavior_other_level: - evaluate.behavior_other_level != null - ? { - col1: evaluate.behavior_other_level == 1 ? "/" : "", - col2: evaluate.behavior_other_level == 2 ? "/" : "", - col3: evaluate.behavior_other_level == 3 ? "/" : "", - col4: evaluate.behavior_other_level == 4 ? "/" : "", - col5: evaluate.behavior_other_level == 5 ? "/" : "", - } - : { - col1: "", - col2: "", - col3: "", - col4: "", - col5: "", - }, - behavior_strength_desc: evaluate.behavior_strength_desc, - behavior_improve_desc: evaluate.behavior_improve_desc, - orientation: evaluate.orientation, - self_learning: evaluate.self_learning, - training_seminar: evaluate.training_seminar, - other_training: evaluate.other_training, - createdAt: evaluate.createdAt, - updatedAt: evaluate.updatedAt, - }; - - const assign = await AppDataSource.getRepository(Assign).findOne({ - select: ["id", "personal_id", "round_no", "date_start", "date_finish"], - where: { id: evaluate.assign_id }, - }); - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const experimenteeData = await this.personalRepository.findOne({ - where: { - personal_id: assign.personal_id, - }, - }); - - if (!experimenteeData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const splitOc = await experimenteeData.organization.split(" "); - const splitOcAmount = await splitOc.length; - const organization = await experimenteeData.organization.replace( - /\//g, - " " - ); - - const experimentee = await { - ...experimenteeData, - organization: organization, - name: `${experimenteeData.prefixName}${experimenteeData.firstName} ${experimenteeData.lastName}`, - PositionLevelName: experimenteeData.positionLevelName, - PositionLineName: experimenteeData.positionLineName, - Position: experimenteeData.positionName, - Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", - OrganizationOrganization: - splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", - Oc: experimenteeData.orgRootName, - PositionLevel: - experimenteeData.positionName + experimenteeData.positionLevelName, - }; - - const commanderData = await this.assignDirectorRepository.findOne({ - select: [ - "personal_id", - "fullname", - "position", - "position", - "posType", - "posLevel", - "role", - "dated", - ], - where: { personal_id: evaluate.director_id }, - }); - - if (!commanderData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const commander = await { - ...commanderData, - name: commanderData.fullname, - Position: commanderData.position + commanderData.posLevel, - }; - - return new HttpSuccess({ - experimentee: experimentee ? experimentee : null, - commander: commander ? commander : null, - assign, - evaluate: evaluateData, - }); } /** @@ -885,292 +936,300 @@ export class ReportController extends Controller { @Query() id: string, @Request() request: RequestWithUser ) { - const evaluate = await this.evaluateChairmanRepository.findOne({ - where: { id }, - }); + try { + const evaluate = await this.evaluateChairmanRepository.findOne({ + where: { id }, + }); - if (!evaluate) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + if (!evaluate) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const develop_total_score = await (Number( + evaluate.develop_orientation_score + ) + + Number(evaluate.develop_self_learning_score) + + Number(evaluate.develop_training_seminar_score) + + Number(evaluate.develop_other_training_score)); + const develop_total_percent = await (Number( + evaluate.develop_orientation_percent + ) + + Number(evaluate.develop_orientation_percent) + + Number(evaluate.develop_self_learning_percent) + + Number(evaluate.develop_training_seminar_percent)); + + const evaluateData = await { + id: evaluate.id, + // director_id: evaluate.director_id, + // assign_id: evaluate.assign_id, + no: evaluate.no, + date_start: evaluate.date_start, + date_finish: evaluate.date_finish, + chairman_dated: evaluate.chairman_dated, + director1_dated: evaluate.director1_dated, + director2_dated: evaluate.director2_dated, + knowledge_level: { + col1: evaluate.knowledge_level == 1 ? "/" : "", + col2: evaluate.knowledge_level == 2 ? "/" : "", + col3: evaluate.knowledge_level == 3 ? "/" : "", + col4: evaluate.knowledge_level == 4 ? "/" : "", + col5: evaluate.knowledge_level == 5 ? "/" : "", + }, + apply_level: { + col1: evaluate.apply_level == 1 ? "/" : "", + col2: evaluate.apply_level == 2 ? "/" : "", + col3: evaluate.apply_level == 3 ? "/" : "", + col4: evaluate.apply_level == 4 ? "/" : "", + col5: evaluate.apply_level == 5 ? "/" : "", + }, + success_level: { + col1: evaluate.success_level == 1 ? "/" : "", + col2: evaluate.success_level == 2 ? "/" : "", + col3: evaluate.success_level == 3 ? "/" : "", + col4: evaluate.success_level == 4 ? "/" : "", + col5: evaluate.success_level == 5 ? "/" : "", + }, + achievement_other_desc: evaluate.achievement_other_desc, + achievement_other_level: + evaluate.achievement_other_level != null + ? { + col1: evaluate.achievement_other_level == 1 ? "/" : "", + col2: evaluate.achievement_other_level == 2 ? "/" : "", + col3: evaluate.achievement_other_level == 3 ? "/" : "", + col4: evaluate.achievement_other_level == 4 ? "/" : "", + col5: evaluate.achievement_other_level == 5 ? "/" : "", + } + : { + col1: "", + col2: "", + col3: "", + col4: "", + col5: "", + }, + conduct1_level: { + col1: evaluate.conduct1_level == 1 ? "/" : "", + col2: evaluate.conduct1_level == 2 ? "/" : "", + col3: evaluate.conduct1_level == 3 ? "/" : "", + col4: evaluate.conduct1_level == 4 ? "/" : "", + col5: evaluate.conduct1_level == 5 ? "/" : "", + }, + conduct2_level: { + col1: evaluate.conduct2_level == 1 ? "/" : "", + col2: evaluate.conduct2_level == 2 ? "/" : "", + col3: evaluate.conduct2_level == 3 ? "/" : "", + col4: evaluate.conduct2_level == 4 ? "/" : "", + col5: evaluate.conduct2_level == 5 ? "/" : "", + }, + conduct3_level: { + col1: evaluate.conduct3_level == 1 ? "/" : "", + col2: evaluate.conduct3_level == 2 ? "/" : "", + col3: evaluate.conduct3_level == 3 ? "/" : "", + col4: evaluate.conduct3_level == 4 ? "/" : "", + col5: evaluate.conduct3_level == 5 ? "/" : "", + }, + conduct4_level: { + col1: evaluate.conduct4_level == 1 ? "/" : "", + col2: evaluate.conduct4_level == 2 ? "/" : "", + col3: evaluate.conduct4_level == 3 ? "/" : "", + col4: evaluate.conduct4_level == 4 ? "/" : "", + col5: evaluate.conduct4_level == 5 ? "/" : "", + }, + moral1_level: { + col1: evaluate.moral1_level == 1 ? "/" : "", + col2: evaluate.moral1_level == 2 ? "/" : "", + col3: evaluate.moral1_level == 3 ? "/" : "", + col4: evaluate.moral1_level == 4 ? "/" : "", + col5: evaluate.moral1_level == 5 ? "/" : "", + }, + moral2_level: { + col1: evaluate.moral2_level == 1 ? "/" : "", + col2: evaluate.moral2_level == 2 ? "/" : "", + col3: evaluate.moral2_level == 3 ? "/" : "", + col4: evaluate.moral2_level == 4 ? "/" : "", + col5: evaluate.moral2_level == 5 ? "/" : "", + }, + moral3_level: { + col1: evaluate.moral3_level == 1 ? "/" : "", + col2: evaluate.moral3_level == 2 ? "/" : "", + col3: evaluate.moral3_level == 3 ? "/" : "", + col4: evaluate.moral3_level == 4 ? "/" : "", + col5: evaluate.moral3_level == 5 ? "/" : "", + }, + discipline1_level: { + col1: evaluate.discipline1_level == 1 ? "/" : "", + col2: evaluate.discipline1_level == 2 ? "/" : "", + col3: evaluate.discipline1_level == 3 ? "/" : "", + col4: evaluate.discipline1_level == 4 ? "/" : "", + col5: evaluate.discipline1_level == 5 ? "/" : "", + }, + discipline2_level: { + col1: evaluate.discipline2_level == 1 ? "/" : "", + col2: evaluate.discipline2_level == 2 ? "/" : "", + col3: evaluate.discipline2_level == 3 ? "/" : "", + col4: evaluate.discipline2_level == 4 ? "/" : "", + col5: evaluate.discipline2_level == 5 ? "/" : "", + }, + discipline3_level: { + col1: evaluate.discipline3_level == 1 ? "/" : "", + col2: evaluate.discipline3_level == 2 ? "/" : "", + col3: evaluate.discipline3_level == 3 ? "/" : "", + col4: evaluate.discipline3_level == 4 ? "/" : "", + col5: evaluate.discipline3_level == 5 ? "/" : "", + }, + discipline4_level: { + col1: evaluate.discipline4_level == 1 ? "/" : "", + col2: evaluate.discipline4_level == 2 ? "/" : "", + col3: evaluate.discipline4_level == 3 ? "/" : "", + col4: evaluate.discipline4_level == 4 ? "/" : "", + col5: evaluate.discipline4_level == 5 ? "/" : "", + }, + discipline5_level: { + col1: evaluate.discipline5_level == 1 ? "/" : "", + col2: evaluate.discipline5_level == 2 ? "/" : "", + col3: evaluate.discipline5_level == 3 ? "/" : "", + col4: evaluate.discipline5_level == 4 ? "/" : "", + col5: evaluate.discipline5_level == 5 ? "/" : "", + }, + behavior_other_desc: evaluate.behavior_other_desc, + behavior_other_level: + evaluate.behavior_other_level != null + ? { + col1: evaluate.behavior_other_level == 1 ? "/" : "", + col2: evaluate.behavior_other_level == 2 ? "/" : "", + col3: evaluate.behavior_other_level == 3 ? "/" : "", + col4: evaluate.behavior_other_level == 4 ? "/" : "", + col5: evaluate.behavior_other_level == 5 ? "/" : "", + } + : { + col1: "", + col2: "", + col3: "", + col4: "", + col5: "", + }, + + achievement_score: evaluate.achievement_score, + achievement_score_total: evaluate.achievement_score_total, + achievement_percent: evaluate.achievement_percent, + achievement_result: evaluate.achievement_result, + behavior_score: evaluate.behavior_score, + behavior_score_total: evaluate.behavior_score_total, + behavior_percent: evaluate.behavior_percent, + behavior_result: evaluate.behavior_result, + sum_score: evaluate.sum_score, + sum_percent: evaluate.sum_percent, + + develop_orientation_score: evaluate.develop_orientation_score, + develop_self_learning_score: evaluate.develop_self_learning_score, + develop_training_seminar_score: evaluate.develop_training_seminar_score, + develop_other_training_score: evaluate.develop_other_training_score, + develop_total_score: develop_total_score, + develop_orientation_percent: evaluate.develop_orientation_percent, + develop_self_learning_percent: evaluate.develop_self_learning_percent, + develop_training_seminar_percent: + evaluate.develop_training_seminar_percent, + develop_other_training_percent: evaluate.develop_other_training_percent, + develop_total_percent: develop_total_percent, + develop_result: evaluate.develop_result, + evaluate_result: evaluate.evaluate_result, + createdAt: evaluate.createdAt, + updatedAt: evaluate.updatedAt, + }; + + const assign = await AppDataSource.getRepository(Assign).findOne({ + select: ["id", "personal_id", "round_no", "date_start", "date_finish"], + where: { id: evaluate.assign_id }, + }); + + if (!assign) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const experimenteeData = await this.personalRepository.findOne({ + where: { + personal_id: assign.personal_id, + }, + }); + + if (!experimenteeData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const splitOc = await experimenteeData.organization.split(" "); + const splitOcAmount = await splitOc.length; + const organization = await experimenteeData.organization.replace( + /\//g, + " " + ); + + const experimentee = await { + ...experimenteeData, + organization: organization, + name: `${experimenteeData.prefixName}${experimenteeData.firstName} ${experimenteeData.lastName}`, + PositionLevelName: experimenteeData.positionLevelName, + PositionLineName: experimenteeData.positionLineName, + Position: experimenteeData.positionName, + Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", + OrganizationOrganization: + splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", + Oc: experimenteeData.orgRootName, + PositionLevel: + experimenteeData.positionName + experimenteeData.positionLevelName, + }; + + const directorData = await this.assignDirectorRepository.find({ + select: [ + "personal_id", + "fullname", + "position", + "posType", + "posLevel", + "role", + "dated", + ], + where: { assign_id: assign.id }, + }); + + if (!directorData) { + throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const director = await Promise.all( + directorData.map(async (element) => { + return { + ...element, + name: element.fullname, + Position: element.position + element.posLevel, + }; + }) + ); + + const mentorData = await (director.find((x) => x.role == "mentor") ?? + null); + const mentor = mentorData != null ? mentorData : null; + + const commanderData = await (director.find( + (x) => x.role == "commander" + ) ?? null); + const commander = commanderData != null ? commanderData : null; + + const chairmanData = await (director.find((x) => x.role == "chairman") ?? + null); + const chairman = chairmanData != null ? chairmanData : null; + + return new HttpSuccess({ + experimentee: experimentee ? experimentee : null, + chairman: chairman ? chairman : null, + director1: commander ? commander : null, + director2: mentor ? mentor : null, + assign, + evaluate: evaluateData, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); } - - const develop_total_score = await (Number( - evaluate.develop_orientation_score - ) + - Number(evaluate.develop_self_learning_score) + - Number(evaluate.develop_training_seminar_score) + - Number(evaluate.develop_other_training_score)); - const develop_total_percent = await (Number( - evaluate.develop_orientation_percent - ) + - Number(evaluate.develop_orientation_percent) + - Number(evaluate.develop_self_learning_percent) + - Number(evaluate.develop_training_seminar_percent)); - - const evaluateData = await { - id: evaluate.id, - // director_id: evaluate.director_id, - // assign_id: evaluate.assign_id, - no: evaluate.no, - date_start: evaluate.date_start, - date_finish: evaluate.date_finish, - chairman_dated: evaluate.chairman_dated, - director1_dated: evaluate.director1_dated, - director2_dated: evaluate.director2_dated, - knowledge_level: { - col1: evaluate.knowledge_level == 1 ? "/" : "", - col2: evaluate.knowledge_level == 2 ? "/" : "", - col3: evaluate.knowledge_level == 3 ? "/" : "", - col4: evaluate.knowledge_level == 4 ? "/" : "", - col5: evaluate.knowledge_level == 5 ? "/" : "", - }, - apply_level: { - col1: evaluate.apply_level == 1 ? "/" : "", - col2: evaluate.apply_level == 2 ? "/" : "", - col3: evaluate.apply_level == 3 ? "/" : "", - col4: evaluate.apply_level == 4 ? "/" : "", - col5: evaluate.apply_level == 5 ? "/" : "", - }, - success_level: { - col1: evaluate.success_level == 1 ? "/" : "", - col2: evaluate.success_level == 2 ? "/" : "", - col3: evaluate.success_level == 3 ? "/" : "", - col4: evaluate.success_level == 4 ? "/" : "", - col5: evaluate.success_level == 5 ? "/" : "", - }, - achievement_other_desc: evaluate.achievement_other_desc, - achievement_other_level: - evaluate.achievement_other_level != null - ? { - col1: evaluate.achievement_other_level == 1 ? "/" : "", - col2: evaluate.achievement_other_level == 2 ? "/" : "", - col3: evaluate.achievement_other_level == 3 ? "/" : "", - col4: evaluate.achievement_other_level == 4 ? "/" : "", - col5: evaluate.achievement_other_level == 5 ? "/" : "", - } - : { - col1: "", - col2: "", - col3: "", - col4: "", - col5: "", - }, - conduct1_level: { - col1: evaluate.conduct1_level == 1 ? "/" : "", - col2: evaluate.conduct1_level == 2 ? "/" : "", - col3: evaluate.conduct1_level == 3 ? "/" : "", - col4: evaluate.conduct1_level == 4 ? "/" : "", - col5: evaluate.conduct1_level == 5 ? "/" : "", - }, - conduct2_level: { - col1: evaluate.conduct2_level == 1 ? "/" : "", - col2: evaluate.conduct2_level == 2 ? "/" : "", - col3: evaluate.conduct2_level == 3 ? "/" : "", - col4: evaluate.conduct2_level == 4 ? "/" : "", - col5: evaluate.conduct2_level == 5 ? "/" : "", - }, - conduct3_level: { - col1: evaluate.conduct3_level == 1 ? "/" : "", - col2: evaluate.conduct3_level == 2 ? "/" : "", - col3: evaluate.conduct3_level == 3 ? "/" : "", - col4: evaluate.conduct3_level == 4 ? "/" : "", - col5: evaluate.conduct3_level == 5 ? "/" : "", - }, - conduct4_level: { - col1: evaluate.conduct4_level == 1 ? "/" : "", - col2: evaluate.conduct4_level == 2 ? "/" : "", - col3: evaluate.conduct4_level == 3 ? "/" : "", - col4: evaluate.conduct4_level == 4 ? "/" : "", - col5: evaluate.conduct4_level == 5 ? "/" : "", - }, - moral1_level: { - col1: evaluate.moral1_level == 1 ? "/" : "", - col2: evaluate.moral1_level == 2 ? "/" : "", - col3: evaluate.moral1_level == 3 ? "/" : "", - col4: evaluate.moral1_level == 4 ? "/" : "", - col5: evaluate.moral1_level == 5 ? "/" : "", - }, - moral2_level: { - col1: evaluate.moral2_level == 1 ? "/" : "", - col2: evaluate.moral2_level == 2 ? "/" : "", - col3: evaluate.moral2_level == 3 ? "/" : "", - col4: evaluate.moral2_level == 4 ? "/" : "", - col5: evaluate.moral2_level == 5 ? "/" : "", - }, - moral3_level: { - col1: evaluate.moral3_level == 1 ? "/" : "", - col2: evaluate.moral3_level == 2 ? "/" : "", - col3: evaluate.moral3_level == 3 ? "/" : "", - col4: evaluate.moral3_level == 4 ? "/" : "", - col5: evaluate.moral3_level == 5 ? "/" : "", - }, - discipline1_level: { - col1: evaluate.discipline1_level == 1 ? "/" : "", - col2: evaluate.discipline1_level == 2 ? "/" : "", - col3: evaluate.discipline1_level == 3 ? "/" : "", - col4: evaluate.discipline1_level == 4 ? "/" : "", - col5: evaluate.discipline1_level == 5 ? "/" : "", - }, - discipline2_level: { - col1: evaluate.discipline2_level == 1 ? "/" : "", - col2: evaluate.discipline2_level == 2 ? "/" : "", - col3: evaluate.discipline2_level == 3 ? "/" : "", - col4: evaluate.discipline2_level == 4 ? "/" : "", - col5: evaluate.discipline2_level == 5 ? "/" : "", - }, - discipline3_level: { - col1: evaluate.discipline3_level == 1 ? "/" : "", - col2: evaluate.discipline3_level == 2 ? "/" : "", - col3: evaluate.discipline3_level == 3 ? "/" : "", - col4: evaluate.discipline3_level == 4 ? "/" : "", - col5: evaluate.discipline3_level == 5 ? "/" : "", - }, - discipline4_level: { - col1: evaluate.discipline4_level == 1 ? "/" : "", - col2: evaluate.discipline4_level == 2 ? "/" : "", - col3: evaluate.discipline4_level == 3 ? "/" : "", - col4: evaluate.discipline4_level == 4 ? "/" : "", - col5: evaluate.discipline4_level == 5 ? "/" : "", - }, - discipline5_level: { - col1: evaluate.discipline5_level == 1 ? "/" : "", - col2: evaluate.discipline5_level == 2 ? "/" : "", - col3: evaluate.discipline5_level == 3 ? "/" : "", - col4: evaluate.discipline5_level == 4 ? "/" : "", - col5: evaluate.discipline5_level == 5 ? "/" : "", - }, - behavior_other_desc: evaluate.behavior_other_desc, - behavior_other_level: - evaluate.behavior_other_level != null - ? { - col1: evaluate.behavior_other_level == 1 ? "/" : "", - col2: evaluate.behavior_other_level == 2 ? "/" : "", - col3: evaluate.behavior_other_level == 3 ? "/" : "", - col4: evaluate.behavior_other_level == 4 ? "/" : "", - col5: evaluate.behavior_other_level == 5 ? "/" : "", - } - : { - col1: "", - col2: "", - col3: "", - col4: "", - col5: "", - }, - - achievement_score: evaluate.achievement_score, - achievement_score_total: evaluate.achievement_score_total, - achievement_percent: evaluate.achievement_percent, - achievement_result: evaluate.achievement_result, - behavior_score: evaluate.behavior_score, - behavior_score_total: evaluate.behavior_score_total, - behavior_percent: evaluate.behavior_percent, - behavior_result: evaluate.behavior_result, - sum_score: evaluate.sum_score, - sum_percent: evaluate.sum_percent, - - develop_orientation_score: evaluate.develop_orientation_score, - develop_self_learning_score: evaluate.develop_self_learning_score, - develop_training_seminar_score: evaluate.develop_training_seminar_score, - develop_other_training_score: evaluate.develop_other_training_score, - develop_total_score: develop_total_score, - develop_orientation_percent: evaluate.develop_orientation_percent, - develop_self_learning_percent: evaluate.develop_self_learning_percent, - develop_training_seminar_percent: - evaluate.develop_training_seminar_percent, - develop_other_training_percent: evaluate.develop_other_training_percent, - develop_total_percent: develop_total_percent, - develop_result: evaluate.develop_result, - evaluate_result: evaluate.evaluate_result, - createdAt: evaluate.createdAt, - updatedAt: evaluate.updatedAt, - }; - - const assign = await AppDataSource.getRepository(Assign).findOne({ - select: ["id", "personal_id", "round_no", "date_start", "date_finish"], - where: { id: evaluate.assign_id }, - }); - - if (!assign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const experimenteeData = await this.personalRepository.findOne({ - where: { - personal_id: assign.personal_id, - }, - }); - - if (!experimenteeData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const splitOc = await experimenteeData.organization.split(" "); - const splitOcAmount = await splitOc.length; - const organization = await experimenteeData.organization.replace( - /\//g, - " " - ); - - const experimentee = await { - ...experimenteeData, - organization: organization, - name: `${experimenteeData.prefixName}${experimenteeData.firstName} ${experimenteeData.lastName}`, - PositionLevelName: experimenteeData.positionLevelName, - PositionLineName: experimenteeData.positionLineName, - Position: experimenteeData.positionName, - Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", - OrganizationOrganization: - splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", - Oc: experimenteeData.orgRootName, - PositionLevel: - experimenteeData.positionName + experimenteeData.positionLevelName, - }; - - const directorData = await this.assignDirectorRepository.find({ - select: [ - "personal_id", - "fullname", - "position", - "posType", - "posLevel", - "role", - "dated", - ], - where: { assign_id: assign.id }, - }); - - if (!directorData) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); - } - - const director = await Promise.all( - directorData.map(async (element) => { - return { - ...element, - name: element.fullname, - Position: element.position + element.posLevel, - }; - }) - ); - - const mentorData = await (director.find((x) => x.role == "mentor") ?? null); - const mentor = mentorData != null ? mentorData : null; - - const commanderData = await (director.find((x) => x.role == "commander") ?? - null); - const commander = commanderData != null ? commanderData : null; - - const chairmanData = await (director.find((x) => x.role == "chairman") ?? - null); - const chairman = chairmanData != null ? chairmanData : null; - - return new HttpSuccess({ - experimentee: experimentee ? experimentee : null, - chairman: chairman ? chairman : null, - director1: commander ? commander : null, - director2: mentor ? mentor : null, - assign, - evaluate: evaluateData, - }); } @Post("command11/officer/report/excecute") @@ -1195,41 +1254,50 @@ export class ReportController extends Controller { }[]; } ) { - await new CallAPI() - .PostData(request, "/org/command/excexute/salary-probation", { - data: body.refIds.map((v) => ({ - profileId: v.refId, - commandId: v.commandId, - amount: v.amount, - amountSpecial: v.amountSpecial, - positionSalaryAmount: v.positionSalaryAmount, - mouthSalaryAmount: v.mouthSalaryAmount, - commandNo: v.commandNo, - commandYear: v.commandYear, - commandDateAffect: v.commandDateAffect, - commandDateSign: v.commandDateSign, - commandCode: v.commandCode, - commandName: v.commandName, - remark: v.remark, - })), - }) - .then(async (res) => { - const lists = await this.personalRepository.find({ - where: { - probation_status: 8, - personal_id: In(body.refIds.map((x) => x.refId)), - }, - }); - await Promise.all( - lists.map(async (list) => { - list.probation_status = 9; - await this.personalRepository.save(list); - }) - ); - }) - .catch(() => {}); - return new HttpSuccess(); + try { + await new CallAPI().PostData( + request, + "/org/command/excexute/salary-probation", + { + data: body.refIds.map((v) => ({ + profileId: v.refId, + commandId: v.commandId, + amount: v.amount, + amountSpecial: v.amountSpecial, + positionSalaryAmount: v.positionSalaryAmount, + mouthSalaryAmount: v.mouthSalaryAmount, + commandNo: v.commandNo, + commandYear: v.commandYear, + commandDateAffect: v.commandDateAffect, + commandDateSign: v.commandDateSign, + commandCode: v.commandCode, + commandName: v.commandName, + remark: v.remark, + })), + } + ); + + const lists = await this.personalRepository.find({ + where: { + probation_status: 8, + personal_id: In(body.refIds.map((x) => x.refId)), + }, + }); + await Promise.all( + lists.map(async (list) => { + list.probation_status = 9; + await this.personalRepository.save(list); + }) + ); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } + @Post("command11/officer/report") public async command11( @Request() req: RequestWithUser, @@ -1238,18 +1306,25 @@ export class ReportController extends Controller { refIds: string[]; } ) { - const lists = await this.personalRepository.find({ - where: { probation_status: 2, personal_id: In(body.refIds) }, - }); - await Promise.all( - lists.map(async (list) => { - list.probation_status = 8; - await this.personalRepository.save(list); - }) - ); + try { + const lists = await this.personalRepository.find({ + where: { probation_status: 2, personal_id: In(body.refIds) }, + }); + await Promise.all( + lists.map(async (list) => { + list.probation_status = 8; + await this.personalRepository.save(list); + }) + ); - return new HttpSuccess(); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } + @Post("command11/officer/report/delete") public async command11Delete( @Request() req: RequestWithUser, @@ -1258,17 +1333,23 @@ export class ReportController extends Controller { refIds: string[]; } ) { - const lists = await this.personalRepository.find({ - where: { probation_status: 8, personal_id: In(body.refIds) }, - }); - await Promise.all( - lists.map(async (list) => { - list.probation_status = 2; - await this.personalRepository.save(list); - }) - ); + try { + const lists = await this.personalRepository.find({ + where: { probation_status: 8, personal_id: In(body.refIds) }, + }); + await Promise.all( + lists.map(async (list) => { + list.probation_status = 2; + await this.personalRepository.save(list); + }) + ); - return new HttpSuccess(); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } @Post("command12/officer/report/excecute") @@ -1293,42 +1374,51 @@ export class ReportController extends Controller { }[]; } ) { - await new CallAPI() - .PostData(request, "/org/command/excexute/salary-probation-leave", { - data: body.refIds.map((v) => ({ - profileId: v.refId, - commandId: v.commandId, - amount: v.amount, - amountSpecial: v.amountSpecial, - positionSalaryAmount: v.positionSalaryAmount, - mouthSalaryAmount: v.mouthSalaryAmount, - isGovernment: false, - commandNo: v.commandNo, - commandYear: v.commandYear, - commandDateAffect: v.commandDateAffect, - commandDateSign: v.commandDateSign, - commandCode: v.commandCode, - commandName: v.commandName, - remark: v.remark, - })), - }) - .then(async (res) => { - const lists = await this.personalRepository.find({ - where: { - probation_status: 8, - personal_id: In(body.refIds.map((x) => x.refId)), - }, - }); - await Promise.all( - lists.map(async (list) => { - list.probation_status = 9; - await this.personalRepository.save(list); - }) - ); - }) - .catch(() => {}); - return new HttpSuccess(); + try { + await new CallAPI().PostData( + request, + "/org/command/excexute/salary-probation-leave", + { + data: body.refIds.map((v) => ({ + profileId: v.refId, + commandId: v.commandId, + amount: v.amount, + amountSpecial: v.amountSpecial, + positionSalaryAmount: v.positionSalaryAmount, + mouthSalaryAmount: v.mouthSalaryAmount, + isGovernment: false, + commandNo: v.commandNo, + commandYear: v.commandYear, + commandDateAffect: v.commandDateAffect, + commandDateSign: v.commandDateSign, + commandCode: v.commandCode, + commandName: v.commandName, + remark: v.remark, + })), + } + ); + + const lists = await this.personalRepository.find({ + where: { + probation_status: 8, + personal_id: In(body.refIds.map((x) => x.refId)), + }, + }); + await Promise.all( + lists.map(async (list) => { + list.probation_status = 9; + await this.personalRepository.save(list); + }) + ); + + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } + @Post("command12/officer/report") public async command12( @Request() req: RequestWithUser, @@ -1337,17 +1427,24 @@ export class ReportController extends Controller { refIds: string[]; } ) { - const lists = await this.personalRepository.find({ - where: { probation_status: 3, personal_id: In(body.refIds) }, - }); - await Promise.all( - lists.map(async (list) => { - list.probation_status = 8; - await this.personalRepository.save(list); - }) - ); - return new HttpSuccess(); + try { + const lists = await this.personalRepository.find({ + where: { probation_status: 3, personal_id: In(body.refIds) }, + }); + await Promise.all( + lists.map(async (list) => { + list.probation_status = 8; + await this.personalRepository.save(list); + }) + ); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } + @Post("command12/officer/report/delete") public async command12Delete( @Request() req: RequestWithUser, @@ -1356,16 +1453,22 @@ export class ReportController extends Controller { refIds: string[]; } ) { - const lists = await this.personalRepository.find({ - where: { probation_status: 8, personal_id: In(body.refIds) }, - }); - await Promise.all( - lists.map(async (list) => { - list.probation_status = 3; - await this.personalRepository.save(list); - }) - ); - return new HttpSuccess(); + try { + const lists = await this.personalRepository.find({ + where: { probation_status: 8, personal_id: In(body.refIds) }, + }); + await Promise.all( + lists.map(async (list) => { + list.probation_status = 3; + await this.personalRepository.save(list); + }) + ); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } @Post("command10/officer/report/excecute") @@ -1395,18 +1498,25 @@ export class ReportController extends Controller { }[]; } ) { - const lists = await this.appointRepository.find({ - where: { id: In(body.refIds.map((x) => x.refId)) }, - }); - await Promise.all( - lists.map(async (list) => { - list.status = "DONE"; - list.commandNo = `${body?.refIds[0]?.commandNo || ""}/${body.refIds[0].commandYear + 543}`; - await this.appointRepository.save(list); - }) - ); - return new HttpSuccess(); + try { + const lists = await this.appointRepository.find({ + where: { id: In(body.refIds.map((x) => x.refId)) }, + }); + await Promise.all( + lists.map(async (list) => { + list.status = "DONE"; + list.commandNo = `${body?.refIds[0]?.commandNo || ""}/${body.refIds[0].commandYear + 543}`; + await this.appointRepository.save(list); + }) + ); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } + @Post("command10/officer/report") public async command10( @Request() req: RequestWithUser, @@ -1415,17 +1525,24 @@ export class ReportController extends Controller { refIds: string[]; } ) { - const lists = await this.appointRepository.find({ - where: { id: In(body.refIds) }, - }); - await Promise.all( - lists.map(async (list) => { - list.status = "REPORT"; - await this.appointRepository.save(list); - }) - ); - return new HttpSuccess(); + try { + const lists = await this.appointRepository.find({ + where: { id: In(body.refIds) }, + }); + await Promise.all( + lists.map(async (list) => { + list.status = "REPORT"; + await this.appointRepository.save(list); + }) + ); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } + @Post("command10/officer/report/delete") public async command10Delete( @Request() req: RequestWithUser, @@ -1434,16 +1551,22 @@ export class ReportController extends Controller { refIds: string[]; } ) { - const lists = await this.appointRepository.find({ - where: { id: In(body.refIds) }, - }); - await Promise.all( - lists.map(async (list) => { - list.status = "PENDING"; - await this.appointRepository.save(list); - }) - ); - return new HttpSuccess(); + try { + const lists = await this.appointRepository.find({ + where: { id: In(body.refIds) }, + }); + await Promise.all( + lists.map(async (list) => { + list.status = "PENDING"; + await this.appointRepository.save(list); + }) + ); + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } @Get("command10/appoints/{refId}") @@ -1451,23 +1574,29 @@ export class ReportController extends Controller { @Request() req: RequestWithUser, @Path() refId: string ) { - const lists = await this.AppointDirectorRepository.find({ - where: { appointId: refId }, - order: { createdAt: "ASC" }, - }); - const directors = await Promise.all( - lists.map(async (director) => { - return { - profileId: director.profileId, - name: director.name, - position: director.position, - positionType: director.positionType, - positionLevel: director.positionLevel, - role: director.role === "chairman" ? "ประธาน" : "กรรมการ", - }; - }) - ); - return new HttpSuccess(directors); + try { + const lists = await this.AppointDirectorRepository.find({ + where: { appointId: refId }, + order: { createdAt: "ASC" }, + }); + const directors = await Promise.all( + lists.map(async (director) => { + return { + profileId: director.profileId, + name: director.name, + position: director.position, + positionType: director.positionType, + positionLevel: director.positionLevel, + role: director.role === "chairman" ? "ประธาน" : "กรรมการ", + }; + }) + ); + return new HttpSuccess(directors); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } @Get("report1") @@ -1490,271 +1619,324 @@ export class ReportController extends Controller { status7: number; }; } + try { + const rootNode = await new CallAPI() + .PostData(req, "/org/find/node-all", { nodeId: nodeId, node: node }) + .catch((error) => { + console.error("Error calling API:", error); + }); + const rootNodeTrue = rootNode["isRootTrue"]; + const rootNodeFalse = rootNode["isRootFalse"]; - const rootNode = await new CallAPI() - .PostData(req, "/org/find/node-all", { nodeId: nodeId, node: node }) - .catch((error) => { - console.error("Error calling API:", error); + let whereRootTrue = + rootNodeTrue && rootNodeTrue.rootDnaId + ? { rootDna: rootNodeTrue.rootDnaId } + : {}; + let listsRootTrue = + rootNodeTrue && rootNodeTrue.rootDnaId + ? await this.personalRepository.find({ + where: { + ...whereRootTrue, + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : undefined, + }, + }) + : []; + + let rootDnaIds = rootNodeFalse.map((node: any) => node.rootDnaId); + let listsRootFalse = + rootDnaIds && rootDnaIds.length + ? await this.personalRepository.find({ + where: { + rootDna: In(rootDnaIds), + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : undefined, + }, + }) + : []; + + let resultTrue: Result = {}; + let resultFalse: Result = {}; + + listsRootTrue.forEach((item) => { + let rootDnaId = item.rootDna; + let status = item.probation_status; + let rootName = item.orgRootName; + + if (!resultTrue[rootDnaId]) { + resultTrue[rootDnaId] = { + rootName: rootName, + status1: 0, + status2: 0, + status3: 0, + status4: 0, + status5: 0, + status6: 0, + status7: 0, + }; + } + + if (status >= 1 && status <= 7) { + (resultTrue[rootDnaId] as { [key: string]: any })[ + `status${status}` + ]++; + } }); - const rootNodeTrue = rootNode["isRootTrue"]; - const rootNodeFalse = rootNode["isRootFalse"]; + listsRootFalse.forEach((item) => { + let rootDnaId = item.rootDna; + let status = item.probation_status; + let rootName = item.orgRootName; - let whereRootTrue = - rootNodeTrue && rootNodeTrue.rootDnaId - ? { rootDna: rootNodeTrue.rootDnaId } - : {}; - let listsRootTrue = - rootNodeTrue && rootNodeTrue.rootDnaId - ? await this.personalRepository.find({ - where: { - ...whereRootTrue, - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : undefined, - }, - }) - : []; + if (!resultFalse[rootDnaId]) { + resultFalse[rootDnaId] = { + rootName: rootName, + status1: 0, + status2: 0, + status3: 0, + status4: 0, + status5: 0, + status6: 0, + status7: 0, + }; + } - let rootDnaIds = rootNodeFalse.map((node: any) => node.rootDnaId); - let listsRootFalse = - rootDnaIds && rootDnaIds.length - ? await this.personalRepository.find({ - where: { - rootDna: In(rootDnaIds), - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : undefined, - }, - }) - : []; - - let resultTrue: Result = {}; - let resultFalse: Result = {}; - - listsRootTrue.forEach((item) => { - let rootDnaId = item.rootDna; - let status = item.probation_status; - let rootName = item.orgRootName; - - if (!resultTrue[rootDnaId]) { - resultTrue[rootDnaId] = { - rootName: rootName, - status1: 0, - status2: 0, - status3: 0, - status4: 0, - status5: 0, - status6: 0, - status7: 0, - }; - } - - if (status >= 1 && status <= 7) { - (resultTrue[rootDnaId] as { [key: string]: any })[`status${status}`]++; - } - }); - listsRootFalse.forEach((item) => { - let rootDnaId = item.rootDna; - let status = item.probation_status; - let rootName = item.orgRootName; - - if (!resultFalse[rootDnaId]) { - resultFalse[rootDnaId] = { - rootName: rootName, - status1: 0, - status2: 0, - status3: 0, - status4: 0, - status5: 0, - status6: 0, - status7: 0, - }; - } - - if (status >= 1 && status <= 7) { - (resultFalse[rootDnaId] as { [key: string]: any })[`status${status}`]++; - } - }); - const resultTruePass = Object.values(resultTrue).reduce( - (sum, { status2 }) => sum + status2, - 0 - ); - const resultTrueExtand = Object.values(resultTrue).reduce( - (sum, { status7 }) => sum + status7, - 0 - ); - const resultTrueSuspension = "-"; - const resultTrueChangePos = Object.values(resultTrue).reduce( - (sum, { status4 }) => sum + status4, - 0 - ); - const resultTrueResign = Object.values(resultTrue).reduce( - (sum, { status5 }) => sum + status5, - 0 - ); - const resultTrueDeceased = Object.values(resultTrue).reduce( - (sum, { status6 }) => sum + status6, - 0 - ); - const resultTrueNotPass = Object.values(resultTrue).reduce( - (sum, { status3 }) => sum + status3, - 0 - ); - const resultFalsePass = Object.values(resultFalse).reduce( - (sum, { status2 }) => sum + status2, - 0 - ); - const resultFalseExtand = Object.values(resultFalse).reduce( - (sum, { status7 }) => sum + status7, - 0 - ); - const resultFalseSuspension = "-"; - const resultFalseChangePos = Object.values(resultFalse).reduce( - (sum, { status4 }) => sum + status4, - 0 - ); - const resultFalseResign = Object.values(resultFalse).reduce( - (sum, { status5 }) => sum + status5, - 0 - ); - const resultFalseDeceased = Object.values(resultFalse).reduce( - (sum, { status6 }) => sum + status6, - 0 - ); - const resultFalseNotPass = Object.values(resultFalse).reduce( - (sum, { status3 }) => sum + status3, - 0 - ); - const sumPass = - Object.values(resultTrue).reduce((sum, { status2 }) => sum + status2, 0) + - Object.values(resultFalse).reduce((sum, { status2 }) => sum + status2, 0); - const sumExtand = - Object.values(resultTrue).reduce((sum, { status7 }) => sum + status7, 0) + - Object.values(resultFalse).reduce((sum, { status7 }) => sum + status7, 0); - const sumSuspension = "-"; - const sumChangePos = - Object.values(resultTrue).reduce((sum, { status4 }) => sum + status4, 0) + - Object.values(resultFalse).reduce((sum, { status4 }) => sum + status4, 0); - const sumResign = - Object.values(resultTrue).reduce((sum, { status5 }) => sum + status5, 0) + - Object.values(resultFalse).reduce((sum, { status5 }) => sum + status5, 0); - const sumDeceased = - Object.values(resultTrue).reduce((sum, { status6 }) => sum + status6, 0) + - Object.values(resultFalse).reduce((sum, { status6 }) => sum + status6, 0); - const sumNotPass = - Object.values(resultTrue).reduce((sum, { status3 }) => sum + status3, 0) + - Object.values(resultFalse).reduce((sum, { status3 }) => sum + status3, 0); - const sumResultTrue = Object.values(resultTrue).reduce( - (total, { status2, status7, status4, status5, status6, status3 }) => { - return ( - total + status2 + status7 + status4 + status5 + status6 + status3 + if (status >= 1 && status <= 7) { + (resultFalse[rootDnaId] as { [key: string]: any })[ + `status${status}` + ]++; + } + }); + const resultTruePass = Object.values(resultTrue).reduce( + (sum, { status2 }) => sum + status2, + 0 + ); + const resultTrueExtand = Object.values(resultTrue).reduce( + (sum, { status7 }) => sum + status7, + 0 + ); + const resultTrueSuspension = "-"; + const resultTrueChangePos = Object.values(resultTrue).reduce( + (sum, { status4 }) => sum + status4, + 0 + ); + const resultTrueResign = Object.values(resultTrue).reduce( + (sum, { status5 }) => sum + status5, + 0 + ); + const resultTrueDeceased = Object.values(resultTrue).reduce( + (sum, { status6 }) => sum + status6, + 0 + ); + const resultTrueNotPass = Object.values(resultTrue).reduce( + (sum, { status3 }) => sum + status3, + 0 + ); + const resultFalsePass = Object.values(resultFalse).reduce( + (sum, { status2 }) => sum + status2, + 0 + ); + const resultFalseExtand = Object.values(resultFalse).reduce( + (sum, { status7 }) => sum + status7, + 0 + ); + const resultFalseSuspension = "-"; + const resultFalseChangePos = Object.values(resultFalse).reduce( + (sum, { status4 }) => sum + status4, + 0 + ); + const resultFalseResign = Object.values(resultFalse).reduce( + (sum, { status5 }) => sum + status5, + 0 + ); + const resultFalseDeceased = Object.values(resultFalse).reduce( + (sum, { status6 }) => sum + status6, + 0 + ); + const resultFalseNotPass = Object.values(resultFalse).reduce( + (sum, { status3 }) => sum + status3, + 0 + ); + const sumPass = + Object.values(resultTrue).reduce( + (sum, { status2 }) => sum + status2, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status2 }) => sum + status2, + 0 ); - }, - 0 - ); - const sumResultFalse = Object.values(resultFalse).reduce( - (total, { status2, status7, status4, status5, status6, status3 }) => { - return ( - total + status2 + status7 + status4 + status5 + status6 + status3 + const sumExtand = + Object.values(resultTrue).reduce( + (sum, { status7 }) => sum + status7, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status7 }) => sum + status7, + 0 ); - }, - 0 - ); - const sumAll = - sumPass + sumExtand + sumChangePos + sumResign + sumDeceased + sumNotPass; - const nowDate = Extension.ToThaiNumber( - Extension.ToThaiShortDate(new Date()) - ); - const formattedData = { - topic: "หน่วยงานระดับสำนักหรือเทียบเท่า", - dateNow: nowDate, - dateStart: startDate - ? Extension.ToThaiNumber(Extension.ToThaiNoprefixDate(startDate)) - : "", - dateEnd: endDate - ? Extension.ToThaiNumber(Extension.ToThaiNoprefixDate(endDate)) - : "", - resultTrueProbation: Object.keys(resultTrue).map((rootDnaId, index) => { - const { - status2, - status7, - status4, - status5, - status6, - status3, - rootName, - } = resultTrue[rootDnaId]; - const sum = status2 + status7 + status4 + status5 + status6 + status3; - return { - rowNo: (index + 1).toString(), - rootName: rootName.toString(), - pass: status2.toString(), - extand: status7.toString(), - suspension: "-", - changePos: status4.toString(), - resign: status5.toString(), - deceased: status6.toString(), - notPass: status3.toString(), - total: sum.toString(), - }; - }), - resultTruePass: resultTruePass.toString(), - resultTrueExtand: resultTrueExtand.toString(), - resultTrueSuspension: "-", - resultTrueChangePos: resultTrueChangePos.toString(), - resultTrueResign: resultTrueResign.toString(), - resultTrueDeceased: resultTrueDeceased.toString(), - resultTrueNotPass: resultTrueNotPass.toString(), - topic2: "หน่วยงานระดับสำนักงานเขต", - resultFalseProbation: Object.keys(resultFalse).map((rootDnaId, index) => { - const { - status2, - status7, - status4, - status5, - status6, - status3, - rootName, - } = resultFalse[rootDnaId]; - const sum = status2 + status7 + status4 + status5 + status6 + status3; - return { - rowNo: (index + 1).toString(), - rootName: rootName.toString(), - pass: status2.toString(), - extand: status7.toString(), - suspension: "-", - changePos: status4.toString(), - resign: status5.toString(), - deceased: status6.toString(), - notPass: status3.toString(), - total: sum.toString(), - }; - }), - resultFalsePass: resultFalsePass.toString(), - resultFalseExtand: resultFalseExtand.toString(), - resultFalseSuspension: "-", - resultFalseChangePos: resultFalseChangePos.toString(), - resultFalseResign: resultFalseResign.toString(), - resultFalseDeceased: resultFalseDeceased.toString(), - resultFalseNotPass: resultFalseNotPass.toString(), - sumPass: sumPass.toString(), - sumExtand: sumExtand.toString(), - sumSuspension: "-", - sumChangePos: sumChangePos.toString(), - sumResign: sumResign.toString(), - sumDeceased: sumDeceased.toString(), - sumNotPass: sumNotPass.toString(), - sumResultTrue: sumResultTrue.toString(), - sumResultFalse: sumResultFalse.toString(), - sumAll: sumAll.toString(), - }; - return new HttpSuccess({ - template: "placementProbation01", - reportName: "xlsx-report", - data: formattedData, - }); + const sumSuspension = "-"; + const sumChangePos = + Object.values(resultTrue).reduce( + (sum, { status4 }) => sum + status4, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status4 }) => sum + status4, + 0 + ); + const sumResign = + Object.values(resultTrue).reduce( + (sum, { status5 }) => sum + status5, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status5 }) => sum + status5, + 0 + ); + const sumDeceased = + Object.values(resultTrue).reduce( + (sum, { status6 }) => sum + status6, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status6 }) => sum + status6, + 0 + ); + const sumNotPass = + Object.values(resultTrue).reduce( + (sum, { status3 }) => sum + status3, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status3 }) => sum + status3, + 0 + ); + const sumResultTrue = Object.values(resultTrue).reduce( + (total, { status2, status7, status4, status5, status6, status3 }) => { + return ( + total + status2 + status7 + status4 + status5 + status6 + status3 + ); + }, + 0 + ); + const sumResultFalse = Object.values(resultFalse).reduce( + (total, { status2, status7, status4, status5, status6, status3 }) => { + return ( + total + status2 + status7 + status4 + status5 + status6 + status3 + ); + }, + 0 + ); + const sumAll = + sumPass + + sumExtand + + sumChangePos + + sumResign + + sumDeceased + + sumNotPass; + const nowDate = Extension.ToThaiNumber( + Extension.ToThaiShortDate(new Date()) + ); + const formattedData = { + topic: "หน่วยงานระดับสำนักหรือเทียบเท่า", + dateNow: nowDate, + dateStart: startDate + ? Extension.ToThaiNumber(Extension.ToThaiNoprefixDate(startDate)) + : "", + dateEnd: endDate + ? Extension.ToThaiNumber(Extension.ToThaiNoprefixDate(endDate)) + : "", + resultTrueProbation: Object.keys(resultTrue).map((rootDnaId, index) => { + const { + status2, + status7, + status4, + status5, + status6, + status3, + rootName, + } = resultTrue[rootDnaId]; + const sum = status2 + status7 + status4 + status5 + status6 + status3; + return { + rowNo: (index + 1).toString(), + rootName: rootName.toString(), + pass: status2.toString(), + extand: status7.toString(), + suspension: "-", + changePos: status4.toString(), + resign: status5.toString(), + deceased: status6.toString(), + notPass: status3.toString(), + total: sum.toString(), + }; + }), + resultTruePass: resultTruePass.toString(), + resultTrueExtand: resultTrueExtand.toString(), + resultTrueSuspension: "-", + resultTrueChangePos: resultTrueChangePos.toString(), + resultTrueResign: resultTrueResign.toString(), + resultTrueDeceased: resultTrueDeceased.toString(), + resultTrueNotPass: resultTrueNotPass.toString(), + topic2: "หน่วยงานระดับสำนักงานเขต", + resultFalseProbation: Object.keys(resultFalse).map( + (rootDnaId, index) => { + const { + status2, + status7, + status4, + status5, + status6, + status3, + rootName, + } = resultFalse[rootDnaId]; + const sum = + status2 + status7 + status4 + status5 + status6 + status3; + return { + rowNo: (index + 1).toString(), + rootName: rootName.toString(), + pass: status2.toString(), + extand: status7.toString(), + suspension: "-", + changePos: status4.toString(), + resign: status5.toString(), + deceased: status6.toString(), + notPass: status3.toString(), + total: sum.toString(), + }; + } + ), + resultFalsePass: resultFalsePass.toString(), + resultFalseExtand: resultFalseExtand.toString(), + resultFalseSuspension: "-", + resultFalseChangePos: resultFalseChangePos.toString(), + resultFalseResign: resultFalseResign.toString(), + resultFalseDeceased: resultFalseDeceased.toString(), + resultFalseNotPass: resultFalseNotPass.toString(), + sumPass: sumPass.toString(), + sumExtand: sumExtand.toString(), + sumSuspension: "-", + sumChangePos: sumChangePos.toString(), + sumResign: sumResign.toString(), + sumDeceased: sumDeceased.toString(), + sumNotPass: sumNotPass.toString(), + sumResultTrue: sumResultTrue.toString(), + sumResultFalse: sumResultFalse.toString(), + sumAll: sumAll.toString(), + }; + return new HttpSuccess({ + template: "placementProbation01", + reportName: "xlsx-report", + data: formattedData, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } @Get("report2") @@ -1765,256 +1947,263 @@ export class ReportController extends Controller { @Query("startDate") startDate?: Date, @Query("endDate") endDate?: Date ) { - let personal = null; - let result: Array = []; - switch (node) { - case 0: { - personal = await this.personalRepository.find({ - where: { - rootDna: nodeId, - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : Not(IsNull()), - }, - }); - personal = await Promise.all( - personal.map(async (p, idx) => { - const assigns = await this.assignRepository.find({ - where: { personal_id: p.personal_id }, - }); - const no = idx + 1; - return { - no: no, - fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, - positionName: p.positionName, - organization: p.organization, - probation_status: p.probation_status, - idcard: p.idcard, - assigns: assigns, - }; - }) - ); - break; - } - case 1: { - personal = await this.personalRepository.find({ - where: { - child1Dna: nodeId, - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : Not(IsNull()), - }, - }); - personal = await Promise.all( - personal.map(async (p, idx) => { - const assigns = await this.assignRepository.find({ - where: { personal_id: p.personal_id }, - }); - const no = idx + 1; - return { - no: no, - fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, - positionName: p.positionName, - organization: p.organization, - probation_status: p.probation_status, - idcard: p.idcard, - assigns: assigns, - }; - }) - ); - break; - } - case 2: { - personal = await this.personalRepository.find({ - where: { - child2Dna: nodeId, - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : Not(IsNull()), - }, - }); - personal = await Promise.all( - personal.map(async (p, idx) => { - const assigns = await this.assignRepository.find({ - where: { personal_id: p.personal_id }, - }); - const no = idx + 1; - return { - no: no, - fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, - positionName: p.positionName, - organization: p.organization, - probation_status: p.probation_status, - idcard: p.idcard, - assigns: assigns, - }; - }) - ); - break; - } - case 3: { - personal = await this.personalRepository.find({ - where: { - child3Dna: nodeId, - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : Not(IsNull()), - }, - }); - personal = await Promise.all( - personal.map(async (p, idx) => { - const assigns = await this.assignRepository.find({ - where: { personal_id: p.personal_id }, - }); - const no = idx + 1; - return { - no: no, - fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, - positionName: p.positionName, - organization: p.organization, - probation_status: p.probation_status, - idcard: p.idcard, - assigns: assigns, - }; - }) - ); - break; - } - case 4: { - personal = await this.personalRepository.find({ - where: { - child4Dna: nodeId, - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : Not(IsNull()), - }, - }); - personal = await Promise.all( - personal.map(async (p, idx) => { - const assigns = await this.assignRepository.find({ - where: { personal_id: p.personal_id }, - }); - const no = idx + 1; - return { - no: no, - fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, - positionName: p.positionName, - organization: p.organization, - probation_status: p.probation_status, - idcard: p.idcard, - assigns: assigns, - }; - }) - ); - break; - } - default: { - personal = await this.personalRepository.find({}); - personal = await Promise.all( - personal.map(async (p, idx) => { - const assigns = await this.assignRepository.find({ - where: { personal_id: p.personal_id }, - }); - const no = idx + 1; - return { - no: no, - fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, - positionName: p.positionName, - organization: p.organization, - probation_status: p.probation_status, - idcard: p.idcard, - assigns: assigns, - }; - }) - ); - } - } - - result = await Promise.all( - personal.flatMap((x) => - (x.assigns.length > 0 - ? x.assigns - : [{ id: null, date_start: null, date_finish: null }] - ).map(async (assign) => { - let accExam: string = ""; - let dateAppoint: Date | any = null; - await new CallAPI() - .GetData(req, `/placement/exam-probation/${x.idcard}`) - .then(async (x) => { - accExam = x.examName; - dateAppoint = x.dateAppoint; + try { + let personal = null; + let result: Array = []; + switch (node) { + case 0: { + personal = await this.personalRepository.find({ + where: { + rootDna: nodeId, + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : Not(IsNull()), + }, + }); + personal = await Promise.all( + personal.map(async (p, idx) => { + const assigns = await this.assignRepository.find({ + where: { personal_id: p.personal_id }, + }); + const no = idx + 1; + return { + no: no, + fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, + positionName: p.positionName, + organization: p.organization, + probation_status: p.probation_status, + idcard: p.idcard, + assigns: assigns, + }; }) - .catch((errr) => {}); - - const evaluateComman = await this.evaluateCommanderRepository.findOne( - { - where: { assign_id: assign.id ?? "" }, - } ); + break; + } + case 1: { + personal = await this.personalRepository.find({ + where: { + child1Dna: nodeId, + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : Not(IsNull()), + }, + }); + personal = await Promise.all( + personal.map(async (p, idx) => { + const assigns = await this.assignRepository.find({ + where: { personal_id: p.personal_id }, + }); + const no = idx + 1; + return { + no: no, + fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, + positionName: p.positionName, + organization: p.organization, + probation_status: p.probation_status, + idcard: p.idcard, + assigns: assigns, + }; + }) + ); + break; + } + case 2: { + personal = await this.personalRepository.find({ + where: { + child2Dna: nodeId, + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : Not(IsNull()), + }, + }); + personal = await Promise.all( + personal.map(async (p, idx) => { + const assigns = await this.assignRepository.find({ + where: { personal_id: p.personal_id }, + }); + const no = idx + 1; + return { + no: no, + fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, + positionName: p.positionName, + organization: p.organization, + probation_status: p.probation_status, + idcard: p.idcard, + assigns: assigns, + }; + }) + ); + break; + } + case 3: { + personal = await this.personalRepository.find({ + where: { + child3Dna: nodeId, + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : Not(IsNull()), + }, + }); + personal = await Promise.all( + personal.map(async (p, idx) => { + const assigns = await this.assignRepository.find({ + where: { personal_id: p.personal_id }, + }); + const no = idx + 1; + return { + no: no, + fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, + positionName: p.positionName, + organization: p.organization, + probation_status: p.probation_status, + idcard: p.idcard, + assigns: assigns, + }; + }) + ); + break; + } + case 4: { + personal = await this.personalRepository.find({ + where: { + child4Dna: nodeId, + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : Not(IsNull()), + }, + }); + personal = await Promise.all( + personal.map(async (p, idx) => { + const assigns = await this.assignRepository.find({ + where: { personal_id: p.personal_id }, + }); + const no = idx + 1; + return { + no: no, + fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, + positionName: p.positionName, + organization: p.organization, + probation_status: p.probation_status, + idcard: p.idcard, + assigns: assigns, + }; + }) + ); + break; + } + default: { + personal = await this.personalRepository.find({}); + personal = await Promise.all( + personal.map(async (p, idx) => { + const assigns = await this.assignRepository.find({ + where: { personal_id: p.personal_id }, + }); + const no = idx + 1; + return { + no: no, + fullName: `${p.prefixName}${p.firstName} ${p.lastName}`, + positionName: p.positionName, + organization: p.organization, + probation_status: p.probation_status, + idcard: p.idcard, + assigns: assigns, + }; + }) + ); + } + } - return { - no: Extension.ToThaiNumber(x.no.toString()), - accExam: accExam, - fullName: x.fullName, - positionName: x.positionName, - organization: x.organization, - dateAppoint: dateAppoint - ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(dateAppoint)) - : "", - dateStart: - x.assigns.length > 0 && assign.date_start != null - ? Extension.ToThaiNumber( - Extension.ToThaiFullDate2(assign.date_start) - ) - : "", - dateFinish: - x.assigns.length > 0 && assign.date_finish != null - ? Extension.ToThaiNumber( - Extension.ToThaiFullDate2(assign.date_finish) - ) - : "", - day: - x.assigns.length > 0 && - assign.date_start != null && - assign.date_finish != null - ? Extension.ToThaiNumber( - `${Math.ceil((new Date(assign.date_finish).getTime() - new Date(assign.date_start).getTime()) / (1000 * 60 * 60 * 24))} วัน` - ) - : "", - status: x.probation_status - ? Extension.probationStatus(x.probation_status) - : "", - orientation: - evaluateComman && evaluateComman?.orientation == 1 ? "☑" : "☐", - learning: - evaluateComman && evaluateComman?.self_learning == 1 ? "☑" : "☐", - seminar: - evaluateComman && evaluateComman?.training_seminar == 1 - ? "☑" - : "☐", - other: - evaluateComman && evaluateComman?.other_training == 1 - ? "☑" - : "☐", - }; - }) - ) - ); + result = await Promise.all( + personal.flatMap((x) => + (x.assigns.length > 0 + ? x.assigns + : [{ id: null, date_start: null, date_finish: null }] + ).map(async (assign) => { + let accExam: string = ""; + let dateAppoint: Date | any = null; + await new CallAPI() + .GetData(req, `/placement/exam-probation/${x.idcard}`) + .then(async (x) => { + accExam = x.examName; + dateAppoint = x.dateAppoint; + }) + .catch((errr) => {}); - return new HttpSuccess({ - template: "placementProbation02", - reportName: "xlsx-report", - data: { - date: `ตั้งแต่${Extension.ToThaiNumber(Extension.ToThaiNoprefixDate2(startDate ?? new Date()))} ถึง ${Extension.ToThaiNumber(Extension.ToThaiNoprefixDate2(endDate ?? new Date()))}`, - dateCurrent: `ณ ${Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date()))}`, - data: result, - }, - }); + const evaluateComman = + await this.evaluateCommanderRepository.findOne({ + where: { assign_id: assign.id ?? "" }, + }); + + return { + no: Extension.ToThaiNumber(x.no.toString()), + accExam: accExam, + fullName: x.fullName, + positionName: x.positionName, + organization: x.organization, + dateAppoint: dateAppoint + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(dateAppoint)) + : "", + dateStart: + x.assigns.length > 0 && assign.date_start != null + ? Extension.ToThaiNumber( + Extension.ToThaiFullDate2(assign.date_start) + ) + : "", + dateFinish: + x.assigns.length > 0 && assign.date_finish != null + ? Extension.ToThaiNumber( + Extension.ToThaiFullDate2(assign.date_finish) + ) + : "", + day: + x.assigns.length > 0 && + assign.date_start != null && + assign.date_finish != null + ? Extension.ToThaiNumber( + `${Math.ceil((new Date(assign.date_finish).getTime() - new Date(assign.date_start).getTime()) / (1000 * 60 * 60 * 24))} วัน` + ) + : "", + status: x.probation_status + ? Extension.probationStatus(x.probation_status) + : "", + orientation: + evaluateComman && evaluateComman?.orientation == 1 ? "☑" : "☐", + learning: + evaluateComman && evaluateComman?.self_learning == 1 + ? "☑" + : "☐", + seminar: + evaluateComman && evaluateComman?.training_seminar == 1 + ? "☑" + : "☐", + other: + evaluateComman && evaluateComman?.other_training == 1 + ? "☑" + : "☐", + }; + }) + ) + ); + + return new HttpSuccess({ + template: "placementProbation02", + reportName: "xlsx-report", + data: { + date: `ตั้งแต่${Extension.ToThaiNumber(Extension.ToThaiNoprefixDate2(startDate ?? new Date()))} ถึง ${Extension.ToThaiNumber(Extension.ToThaiNoprefixDate2(endDate ?? new Date()))}`, + dateCurrent: `ณ ${Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date()))}`, + data: result, + }, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } @Get("report3") @@ -2038,270 +2227,324 @@ export class ReportController extends Controller { }; } - const rootNode = await new CallAPI() - .PostData(req, "/org/find/node-all", { nodeId: nodeId, node: node }) - .catch((error) => { - console.error("Error calling API:", error); + try { + const rootNode = await new CallAPI() + .PostData(req, "/org/find/node-all", { nodeId: nodeId, node: node }) + .catch((error) => { + console.error("Error calling API:", error); + }); + const rootNodeTrue = rootNode["isRootTrue"]; + const rootNodeFalse = rootNode["isRootFalse"]; + + let whereRootTrue = + rootNodeTrue && rootNodeTrue.rootDnaId + ? { rootDna: rootNodeTrue.rootDnaId } + : {}; + let listsRootTrue = + rootNodeTrue && rootNodeTrue.rootDnaId + ? await this.personalRepository.find({ + where: { + ...whereRootTrue, + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : undefined, + }, + }) + : []; + + let rootDnaIds = rootNodeFalse.map((node: any) => node.rootDnaId); + let listsRootFalse = + rootDnaIds && rootDnaIds.length + ? await this.personalRepository.find({ + where: { + rootDna: In(rootDnaIds), + createdAt: + startDate && endDate + ? Between(new Date(startDate), new Date(endDate)) + : undefined, + }, + }) + : []; + + let resultTrue: Result = {}; + let resultFalse: Result = {}; + + listsRootTrue.forEach((item) => { + let rootDnaId = item.rootDna; + let status = item.probation_status; + let rootName = item.orgRootName; + + if (!resultTrue[rootDnaId]) { + resultTrue[rootDnaId] = { + rootName: rootName, + status1: 0, + status2: 0, + status3: 0, + status4: 0, + status5: 0, + status6: 0, + status7: 0, + }; + } + + if (status >= 1 && status <= 7) { + (resultTrue[rootDnaId] as { [key: string]: any })[ + `status${status}` + ]++; + } }); - const rootNodeTrue = rootNode["isRootTrue"]; - const rootNodeFalse = rootNode["isRootFalse"]; + listsRootFalse.forEach((item) => { + let rootDnaId = item.rootDna; + let status = item.probation_status; + let rootName = item.orgRootName; - let whereRootTrue = - rootNodeTrue && rootNodeTrue.rootDnaId - ? { rootDna: rootNodeTrue.rootDnaId } - : {}; - let listsRootTrue = - rootNodeTrue && rootNodeTrue.rootDnaId - ? await this.personalRepository.find({ - where: { - ...whereRootTrue, - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : undefined, - }, - }) - : []; + if (!resultFalse[rootDnaId]) { + resultFalse[rootDnaId] = { + rootName: rootName, + status1: 0, + status2: 0, + status3: 0, + status4: 0, + status5: 0, + status6: 0, + status7: 0, + }; + } - let rootDnaIds = rootNodeFalse.map((node: any) => node.rootDnaId); - let listsRootFalse = - rootDnaIds && rootDnaIds.length - ? await this.personalRepository.find({ - where: { - rootDna: In(rootDnaIds), - createdAt: - startDate && endDate - ? Between(new Date(startDate), new Date(endDate)) - : undefined, - }, - }) - : []; - - let resultTrue: Result = {}; - let resultFalse: Result = {}; - - listsRootTrue.forEach((item) => { - let rootDnaId = item.rootDna; - let status = item.probation_status; - let rootName = item.orgRootName; - - if (!resultTrue[rootDnaId]) { - resultTrue[rootDnaId] = { - rootName: rootName, - status1: 0, - status2: 0, - status3: 0, - status4: 0, - status5: 0, - status6: 0, - status7: 0, - }; - } - - if (status >= 1 && status <= 7) { - (resultTrue[rootDnaId] as { [key: string]: any })[`status${status}`]++; - } - }); - listsRootFalse.forEach((item) => { - let rootDnaId = item.rootDna; - let status = item.probation_status; - let rootName = item.orgRootName; - - if (!resultFalse[rootDnaId]) { - resultFalse[rootDnaId] = { - rootName: rootName, - status1: 0, - status2: 0, - status3: 0, - status4: 0, - status5: 0, - status6: 0, - status7: 0, - }; - } - - if (status >= 1 && status <= 7) { - (resultFalse[rootDnaId] as { [key: string]: any })[`status${status}`]++; - } - }); - const resultTruePass = Object.values(resultTrue).reduce( - (sum, { status2 }) => sum + status2, - 0 - ); - const resultTrueExtand = Object.values(resultTrue).reduce( - (sum, { status7 }) => sum + status7, - 0 - ); - const resultTrueSuspension = "-"; - const resultTrueChangePos = Object.values(resultTrue).reduce( - (sum, { status4 }) => sum + status4, - 0 - ); - const resultTrueResign = Object.values(resultTrue).reduce( - (sum, { status5 }) => sum + status5, - 0 - ); - const resultTrueDeceased = Object.values(resultTrue).reduce( - (sum, { status6 }) => sum + status6, - 0 - ); - const resultTrueNotPass = Object.values(resultTrue).reduce( - (sum, { status3 }) => sum + status3, - 0 - ); - const resultFalsePass = Object.values(resultFalse).reduce( - (sum, { status2 }) => sum + status2, - 0 - ); - const resultFalseExtand = Object.values(resultFalse).reduce( - (sum, { status7 }) => sum + status7, - 0 - ); - const resultFalseSuspension = "-"; - const resultFalseChangePos = Object.values(resultFalse).reduce( - (sum, { status4 }) => sum + status4, - 0 - ); - const resultFalseResign = Object.values(resultFalse).reduce( - (sum, { status5 }) => sum + status5, - 0 - ); - const resultFalseDeceased = Object.values(resultFalse).reduce( - (sum, { status6 }) => sum + status6, - 0 - ); - const resultFalseNotPass = Object.values(resultFalse).reduce( - (sum, { status3 }) => sum + status3, - 0 - ); - const sumPass = - Object.values(resultTrue).reduce((sum, { status2 }) => sum + status2, 0) + - Object.values(resultFalse).reduce((sum, { status2 }) => sum + status2, 0); - const sumExtand = - Object.values(resultTrue).reduce((sum, { status7 }) => sum + status7, 0) + - Object.values(resultFalse).reduce((sum, { status7 }) => sum + status7, 0); - const sumSuspension = "-"; - const sumChangePos = - Object.values(resultTrue).reduce((sum, { status4 }) => sum + status4, 0) + - Object.values(resultFalse).reduce((sum, { status4 }) => sum + status4, 0); - const sumResign = - Object.values(resultTrue).reduce((sum, { status5 }) => sum + status5, 0) + - Object.values(resultFalse).reduce((sum, { status5 }) => sum + status5, 0); - const sumDeceased = - Object.values(resultTrue).reduce((sum, { status6 }) => sum + status6, 0) + - Object.values(resultFalse).reduce((sum, { status6 }) => sum + status6, 0); - const sumNotPass = - Object.values(resultTrue).reduce((sum, { status3 }) => sum + status3, 0) + - Object.values(resultFalse).reduce((sum, { status3 }) => sum + status3, 0); - const sumResultTrue = Object.values(resultTrue).reduce( - (total, { status2, status7, status4, status5, status6, status3 }) => { - return ( - total + status2 + status7 + status4 + status5 + status6 + status3 + if (status >= 1 && status <= 7) { + (resultFalse[rootDnaId] as { [key: string]: any })[ + `status${status}` + ]++; + } + }); + const resultTruePass = Object.values(resultTrue).reduce( + (sum, { status2 }) => sum + status2, + 0 + ); + const resultTrueExtand = Object.values(resultTrue).reduce( + (sum, { status7 }) => sum + status7, + 0 + ); + const resultTrueSuspension = "-"; + const resultTrueChangePos = Object.values(resultTrue).reduce( + (sum, { status4 }) => sum + status4, + 0 + ); + const resultTrueResign = Object.values(resultTrue).reduce( + (sum, { status5 }) => sum + status5, + 0 + ); + const resultTrueDeceased = Object.values(resultTrue).reduce( + (sum, { status6 }) => sum + status6, + 0 + ); + const resultTrueNotPass = Object.values(resultTrue).reduce( + (sum, { status3 }) => sum + status3, + 0 + ); + const resultFalsePass = Object.values(resultFalse).reduce( + (sum, { status2 }) => sum + status2, + 0 + ); + const resultFalseExtand = Object.values(resultFalse).reduce( + (sum, { status7 }) => sum + status7, + 0 + ); + const resultFalseSuspension = "-"; + const resultFalseChangePos = Object.values(resultFalse).reduce( + (sum, { status4 }) => sum + status4, + 0 + ); + const resultFalseResign = Object.values(resultFalse).reduce( + (sum, { status5 }) => sum + status5, + 0 + ); + const resultFalseDeceased = Object.values(resultFalse).reduce( + (sum, { status6 }) => sum + status6, + 0 + ); + const resultFalseNotPass = Object.values(resultFalse).reduce( + (sum, { status3 }) => sum + status3, + 0 + ); + const sumPass = + Object.values(resultTrue).reduce( + (sum, { status2 }) => sum + status2, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status2 }) => sum + status2, + 0 ); - }, - 0 - ); - const sumResultFalse = Object.values(resultFalse).reduce( - (total, { status2, status7, status4, status5, status6, status3 }) => { - return ( - total + status2 + status7 + status4 + status5 + status6 + status3 + const sumExtand = + Object.values(resultTrue).reduce( + (sum, { status7 }) => sum + status7, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status7 }) => sum + status7, + 0 ); - }, - 0 - ); - const sumAll = - sumPass + sumExtand + sumChangePos + sumResign + sumDeceased + sumNotPass; - const nowDate = Extension.ToThaiNumber( - Extension.ToThaiShortDate(new Date()) - ); - const formattedData = { - topic: "หน่วยงานระดับสำนักหรือเทียบเท่า", - dateNow: nowDate, - accExam: "", - dateStart: startDate - ? Extension.ToThaiNumber(Extension.ToThaiNoprefixDate(startDate)) - : "", - dateEnd: endDate - ? Extension.ToThaiNumber(Extension.ToThaiNoprefixDate(endDate)) - : "", - resultTrueProbation: Object.keys(resultTrue).map((rootDnaId, index) => { - const { - status2, - status7, - status4, - status5, - status6, - status3, - rootName, - } = resultTrue[rootDnaId]; - const sum = status2 + status7 + status4 + status5 + status6 + status3; - return { - rowNo: (index + 1).toString(), - rootName: rootName.toString(), - pass: status2.toString(), - extand: status7.toString(), - suspension: "-", - changePos: status4.toString(), - resign: status5.toString(), - deceased: status6.toString(), - notPass: status3.toString(), - total: sum.toString(), - }; - }), - resultTruePass: resultTruePass.toString(), - resultTrueExtand: resultTrueExtand.toString(), - resultTrueSuspension: "-", - resultTrueChangePos: resultTrueChangePos.toString(), - resultTrueResign: resultTrueResign.toString(), - resultTrueDeceased: resultTrueDeceased.toString(), - resultTrueNotPass: resultTrueNotPass.toString(), - topic2: "หน่วยงานระดับสำนักงานเขต", - resultFalseProbation: Object.keys(resultFalse).map((rootDnaId, index) => { - const { - status2, - status7, - status4, - status5, - status6, - status3, - rootName, - } = resultFalse[rootDnaId]; - const sum = status2 + status7 + status4 + status5 + status6 + status3; - return { - rowNo: (index + 1).toString(), - rootName: rootName.toString(), - pass: status2.toString(), - extand: status7.toString(), - suspension: "-", - changePos: status4.toString(), - resign: status5.toString(), - deceased: status6.toString(), - notPass: status3.toString(), - total: sum.toString(), - }; - }), - resultFalsePass: resultFalsePass.toString(), - resultFalseExtand: resultFalseExtand.toString(), - resultFalseSuspension: "-", - resultFalseChangePos: resultFalseChangePos.toString(), - resultFalseResign: resultFalseResign.toString(), - resultFalseDeceased: resultFalseDeceased.toString(), - resultFalseNotPass: resultFalseNotPass.toString(), - sumPass: sumPass.toString(), - sumExtand: sumExtand.toString(), - sumSuspension: "-", - sumChangePos: sumChangePos.toString(), - sumResign: sumResign.toString(), - sumDeceased: sumDeceased.toString(), - sumNotPass: sumNotPass.toString(), - sumResultTrue: sumResultTrue.toString(), - sumResultFalse: sumResultFalse.toString(), - sumAll: sumAll.toString(), - }; - return new HttpSuccess({ - template: "placementProbation03", - reportName: "xlsx-report", - data: formattedData, - }); + const sumSuspension = "-"; + const sumChangePos = + Object.values(resultTrue).reduce( + (sum, { status4 }) => sum + status4, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status4 }) => sum + status4, + 0 + ); + const sumResign = + Object.values(resultTrue).reduce( + (sum, { status5 }) => sum + status5, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status5 }) => sum + status5, + 0 + ); + const sumDeceased = + Object.values(resultTrue).reduce( + (sum, { status6 }) => sum + status6, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status6 }) => sum + status6, + 0 + ); + const sumNotPass = + Object.values(resultTrue).reduce( + (sum, { status3 }) => sum + status3, + 0 + ) + + Object.values(resultFalse).reduce( + (sum, { status3 }) => sum + status3, + 0 + ); + const sumResultTrue = Object.values(resultTrue).reduce( + (total, { status2, status7, status4, status5, status6, status3 }) => { + return ( + total + status2 + status7 + status4 + status5 + status6 + status3 + ); + }, + 0 + ); + const sumResultFalse = Object.values(resultFalse).reduce( + (total, { status2, status7, status4, status5, status6, status3 }) => { + return ( + total + status2 + status7 + status4 + status5 + status6 + status3 + ); + }, + 0 + ); + const sumAll = + sumPass + + sumExtand + + sumChangePos + + sumResign + + sumDeceased + + sumNotPass; + const nowDate = Extension.ToThaiNumber( + Extension.ToThaiShortDate(new Date()) + ); + const formattedData = { + topic: "หน่วยงานระดับสำนักหรือเทียบเท่า", + dateNow: nowDate, + accExam: "", + dateStart: startDate + ? Extension.ToThaiNumber(Extension.ToThaiNoprefixDate(startDate)) + : "", + dateEnd: endDate + ? Extension.ToThaiNumber(Extension.ToThaiNoprefixDate(endDate)) + : "", + resultTrueProbation: Object.keys(resultTrue).map((rootDnaId, index) => { + const { + status2, + status7, + status4, + status5, + status6, + status3, + rootName, + } = resultTrue[rootDnaId]; + const sum = status2 + status7 + status4 + status5 + status6 + status3; + return { + rowNo: (index + 1).toString(), + rootName: rootName.toString(), + pass: status2.toString(), + extand: status7.toString(), + suspension: "-", + changePos: status4.toString(), + resign: status5.toString(), + deceased: status6.toString(), + notPass: status3.toString(), + total: sum.toString(), + }; + }), + resultTruePass: resultTruePass.toString(), + resultTrueExtand: resultTrueExtand.toString(), + resultTrueSuspension: "-", + resultTrueChangePos: resultTrueChangePos.toString(), + resultTrueResign: resultTrueResign.toString(), + resultTrueDeceased: resultTrueDeceased.toString(), + resultTrueNotPass: resultTrueNotPass.toString(), + topic2: "หน่วยงานระดับสำนักงานเขต", + resultFalseProbation: Object.keys(resultFalse).map( + (rootDnaId, index) => { + const { + status2, + status7, + status4, + status5, + status6, + status3, + rootName, + } = resultFalse[rootDnaId]; + const sum = + status2 + status7 + status4 + status5 + status6 + status3; + return { + rowNo: (index + 1).toString(), + rootName: rootName.toString(), + pass: status2.toString(), + extand: status7.toString(), + suspension: "-", + changePos: status4.toString(), + resign: status5.toString(), + deceased: status6.toString(), + notPass: status3.toString(), + total: sum.toString(), + }; + } + ), + resultFalsePass: resultFalsePass.toString(), + resultFalseExtand: resultFalseExtand.toString(), + resultFalseSuspension: "-", + resultFalseChangePos: resultFalseChangePos.toString(), + resultFalseResign: resultFalseResign.toString(), + resultFalseDeceased: resultFalseDeceased.toString(), + resultFalseNotPass: resultFalseNotPass.toString(), + sumPass: sumPass.toString(), + sumExtand: sumExtand.toString(), + sumSuspension: "-", + sumChangePos: sumChangePos.toString(), + sumResign: sumResign.toString(), + sumDeceased: sumDeceased.toString(), + sumNotPass: sumNotPass.toString(), + sumResultTrue: sumResultTrue.toString(), + sumResultFalse: sumResultFalse.toString(), + sumAll: sumAll.toString(), + }; + return new HttpSuccess({ + template: "placementProbation03", + reportName: "xlsx-report", + data: formattedData, + }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } } } diff --git a/src/controllers/SurveyController.ts b/src/controllers/SurveyController.ts index 1e2ec98..58f458b 100644 --- a/src/controllers/SurveyController.ts +++ b/src/controllers/SurveyController.ts @@ -1,132 +1,190 @@ -import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Post, Body, Query } from "tsoa" -import HttpSuccess from "../interfaces/http-success" -import HttpStatusCode from "../interfaces/http-status" -import HttpError from "../interfaces/http-error" -import { RequestWithUser } from "../middlewares/user" -import { setLogDataDiff } from "../interfaces/utils" -import { Survey } from "../entities/Survey" -import { Assign } from "../entities/Assign" -import { AppDataSource } from "../database/data-source" -import CallAPI from "../interfaces/call-api" -import permission from "../interfaces/permission" -import { Brackets } from "typeorm" +import { + Controller, + Route, + Security, + Tags, + Request, + SuccessResponse, + Response, + Get, + Post, + Body, + Query, +} from "tsoa"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatusCode from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { setLogDataDiff } from "../interfaces/utils"; +import { Survey } from "../entities/Survey"; +import { Assign } from "../entities/Assign"; +import { AppDataSource } from "../database/data-source"; +import CallAPI from "../interfaces/call-api"; +import permission from "../interfaces/permission"; +import { Brackets } from "typeorm"; @Route("api/v1/probation/survey") @Tags("Survey") @Security("bearerAuth") -@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") +@Response( + HttpStatusCode.INTERNAL_SERVER_ERROR, + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง" +) export class SurveyController extends Controller { - private surveyRepository = AppDataSource.getRepository(Survey) - private assignRepository = AppDataSource.getRepository(Assign) + private surveyRepository = AppDataSource.getRepository(Survey); + private assignRepository = AppDataSource.getRepository(Assign); - /** - * API แบบสำรวจความคิดเห็น - * - * @summary แบบสำรวจความคิดเห็น - * - */ - @Get("") - async GetSurvey(@Request() request: RequestWithUser) { - const personalId = await new CallAPI().GetData(request, "/org/profile/keycloak").catch(error => { - console.error("Error calling API:", error) - }) + /** + * API แบบสำรวจความคิดเห็น + * + * @summary แบบสำรวจความคิดเห็น + * + */ + @Get("") + async GetSurvey(@Request() request: RequestWithUser) { + try { + const personalId = await new CallAPI().GetData( + request, + "/org/profile/keycloak" + ); - const dataAssign = await this.assignRepository.findOne({ - select: ["id"], - where: { personal_id: personalId }, - order: { date_start: "DESC" }, - }) - if (!dataAssign) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบผลการประเมินการทดลองปฏิบัติหน้าที่ราชการนี้") - } - const assign_id = dataAssign.id + const dataAssign = await this.assignRepository.findOne({ + select: ["id"], + where: { personal_id: personalId }, + order: { date_start: "DESC" }, + }); + if (!dataAssign) { + throw new HttpError( + HttpStatusCode.NOT_FOUND, + "ไม่พบผลการประเมินการทดลองปฏิบัติหน้าที่ราชการนี้" + ); + } + const assign_id = dataAssign.id; - const data = await this.surveyRepository.findOne({ - where: { - assign_id, - }, - }) - return new HttpSuccess({ data: data, assignId: assign_id }) - } + const data = await this.surveyRepository.findOne({ + where: { + assign_id, + }, + }); + return new HttpSuccess({ data: data, assignId: assign_id }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - /** - * API บันทึกแบบสำรวจความคิดเห็น - * - * @summary บันทึกแบบสำรวจความคิดเห็น - * - */ - @Post("") - async PostSurvey(@Query() assign_id: string, @Body() requestBody: any, @Request() request: RequestWithUser) { - const personalId = await new CallAPI().GetData(request, "/org/profile/keycloak").catch(error => { - console.error("Error calling API:", error) - }) + /** + * API บันทึกแบบสำรวจความคิดเห็น + * + * @summary บันทึกแบบสำรวจความคิดเห็น + * + */ + @Post("") + async PostSurvey( + @Query() assign_id: string, + @Body() requestBody: any, + @Request() request: RequestWithUser + ) { + try { + const personalId = await new CallAPI().GetData( + request, + "/org/profile/keycloak" + ); - const before = null - const data = await { - ...requestBody, - personal_id: personalId, - assign_id, - createdUserId: request.user.sub, - updateUserId: request.user.sub, - } - await this.surveyRepository.save(data, { data: request }) - setLogDataDiff(request, { before, after: data }) + const before = null; + const data = await { + ...requestBody, + personal_id: personalId, + assign_id, + createdUserId: request.user.sub, + updateUserId: request.user.sub, + }; + await this.surveyRepository.save(data, { data: request }); + setLogDataDiff(request, { before, after: data }); - return new HttpSuccess() - } + return new HttpSuccess(); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + } - /** - * API รายการผลสำรวจความคิดเห็นของ Admin - * - * @summary ผลสำรวจความคิดเห็นของ Admin - * - */ - @Get("/admin") - async GetSurveyAdmin( - @Query() year: number = new Date().getFullYear(), - @Query() keyword: string = "", - @Query("page") page: number = 1, - @Query("pageSize") pageSize: number = 10, - @Request() request: RequestWithUser - ) { - // await new permission().PermissionUpdate(request, "SYS_PROBATION"); - const start = new Date("01-01-" + year) - const end = new Date("12-31-" + year) + /** + * API รายการผลสำรวจความคิดเห็นของ Admin + * + * @summary ผลสำรวจความคิดเห็นของ Admin + * + */ + @Get("/admin") + async GetSurveyAdmin( + @Query() year: number = new Date().getFullYear(), + @Query() keyword: string = "", + @Query("page") page: number = 1, + @Query("pageSize") pageSize: number = 10, + @Request() request: RequestWithUser + ) { + try { + const start = new Date("01-01-" + year); + const end = new Date("12-31-" + year); - const searchKeyword = await (keyword ? keyword.trim() : null) + const searchKeyword = await (keyword ? keyword.trim() : null); - const [lists, total] = await AppDataSource.getRepository(Survey) - .createQueryBuilder("survey") - .leftJoinAndSelect("survey.personal", "personal") - .where(`survey.createdAt BETWEEN '${start.toISOString()}' AND '${end.toISOString()}'`) - .andWhere( - new Brackets(qb => { - qb.orWhere(searchKeyword ? `CONCAT(personal.prefixName, personal.firstName," ",personal.lastName) like '%${keyword}%'` : "1=1", { - keyword: `%${searchKeyword}%`, - }) - qb.orWhere(searchKeyword ? `CONCAT(personal.positionName, personal.positionLevelName) like '%${keyword}%'` : "1=1", { - keyword: `%${searchKeyword}%`, - }) - }) - ) - .orderBy("survey.createdAt", "DESC") - .skip((page - 1) * pageSize) - .take(pageSize) - .getManyAndCount() + const [lists, total] = await AppDataSource.getRepository(Survey) + .createQueryBuilder("survey") + .leftJoinAndSelect("survey.personal", "personal") + .where( + `survey.createdAt BETWEEN '${start.toISOString()}' AND '${end.toISOString()}'` + ) + .andWhere( + new Brackets((qb) => { + qb.orWhere( + searchKeyword + ? `CONCAT(personal.prefixName, personal.firstName," ",personal.lastName) like '%${keyword}%'` + : "1=1", + { + keyword: `%${searchKeyword}%`, + } + ); + qb.orWhere( + searchKeyword + ? `CONCAT(personal.positionName, personal.positionLevelName) like '%${keyword}%'` + : "1=1", + { + keyword: `%${searchKeyword}%`, + } + ); + }) + ) + .orderBy("survey.createdAt", "DESC") + .skip((page - 1) * pageSize) + .take(pageSize) + .getManyAndCount(); - const data = lists.map(item => { - return { - createdAt: item.createdAt, - personal_id: item.personal_id, - assign_id: item.assign_id, - answer1: item.answer1, - answer2: item.answer2, - answer3: item.answer3, - fullname: item.personal ? `${item.personal.prefixName}${item.personal.firstName} ${item.personal.lastName}` : "", - position: item.personal ? `${item.personal.positionName}${item.personal.positionLevelName}` : "", - } - }) + const data = lists.map((item) => { + return { + createdAt: item.createdAt, + personal_id: item.personal_id, + assign_id: item.assign_id, + answer1: item.answer1, + answer2: item.answer2, + answer3: item.answer3, + fullname: item.personal + ? `${item.personal.prefixName}${item.personal.firstName} ${item.personal.lastName}` + : "", + position: item.personal + ? `${item.personal.positionName}${item.personal.positionLevelName}` + : "", + }; + }); - return new HttpSuccess({ data, total: total }) - } + return new HttpSuccess({ data, total: total }); + } catch (error: any) { + if (error instanceof HttpError) { + throw error; + } else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error); + } + // await new permission().PermissionUpdate(request, "SYS_PROBATION"); + } }