This commit is contained in:
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 2025-03-26 14:35:09 +07:00
parent a4dfb3c87c
commit df74e0226e
13 changed files with 7057 additions and 5877 deletions

View file

@ -85,10 +85,7 @@ async function main() {
console.log( console.log(
`[APP] Application is running on: http://localhost:${APP_PORT}` `[APP] Application is running on: http://localhost:${APP_PORT}`
), ),
console.log(`[APP] Swagger on: http://localhost:${APP_PORT}/api-docs`), console.log(`[APP] Swagger on: http://localhost:${APP_PORT}/api-docs`)
console.log(
`[WS] WebSocket Server is running on ws://localhost:${APP_PORT}`
)
) )
); );
} }

View file

@ -22,7 +22,12 @@ import HttpStatusCode from "../interfaces/http-status";
import HttpError from "../interfaces/http-error"; import HttpError from "../interfaces/http-error";
import permission from "../interfaces/permission"; import permission from "../interfaces/permission";
import { RequestWithUser } from "../middlewares/user"; 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 { AppointDirector } from "../entities/AppointDirector";
import CallAPI from "../interfaces/call-api"; import CallAPI from "../interfaces/call-api";
@ -31,11 +36,12 @@ import CallAPI from "../interfaces/call-api";
@Security("bearerAuth") @Security("bearerAuth")
@Response( @Response(
HttpStatusCode.INTERNAL_SERVER_ERROR, HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง", "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง"
) )
export class AppointController extends Controller { export class AppointController extends Controller {
private appointRepository = AppDataSource.getRepository(Appoint); private appointRepository = AppDataSource.getRepository(Appoint);
private appointDirectorRepository = AppDataSource.getRepository(AppointDirector); private appointDirectorRepository =
AppDataSource.getRepository(AppointDirector);
/** /**
* API * API
@ -48,8 +54,21 @@ export class AppointController extends Controller {
@Query() keyword: string = "", @Query() keyword: string = "",
@Query("page") page: number = 1, @Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10, @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") // await new permission().PermissionList(request, "SYS_PROBATION")
// const _data = await new permission().PermissionOrgList(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) { // if (_data.child4 != undefined && _data.child4 != null && _data.child4[0] != null) {
// conditions.child4 = _data.child4 // 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}") @Get("list/{id}")
async GetListCommand(@Request() request: RequestWithUser, @Path() id: string) { async GetListCommand(
@Request() request: RequestWithUser,
@Path() id: string
) {
try {
const appoint = await this.appointRepository.find({ const appoint = await this.appointRepository.find({
relations: ["directors"], relations: ["directors"],
where: { profileId: id, status: "DONE" }, 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,7 +127,11 @@ export class AppointController extends Controller {
* *
*/ */
@Post("") @Post("")
async Create(@Request() request: RequestWithUser, @Body() requestBody: CreateAppoint) { async Create(
@Request() request: RequestWithUser,
@Body() requestBody: CreateAppoint
) {
try {
await new permission().PermissionCreate(request, "SYS_PROBATION"); await new permission().PermissionCreate(request, "SYS_PROBATION");
const data: any = { const data: any = {
@ -117,10 +141,17 @@ export class AppointController extends Controller {
createdFullName: request.user.name, createdFullName: request.user.name,
}; };
const before = null; const before = null;
const appoint = await this.appointRepository.save(data, { data: request }); const appoint = await this.appointRepository.save(data, {
data: request,
});
setLogDataDiff(request, { before, after: appoint }); 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,8 +162,14 @@ export class AppointController extends Controller {
*/ */
@Get("{id}") @Get("{id}")
async GetById(@Request() request: RequestWithUser, @Path() id: string) { async GetById(@Request() request: RequestWithUser, @Path() id: string) {
let _workflow = await new permission().Workflow(request, id, "SYS_PROBATION"); try {
if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION"); 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({ const appoint = await this.appointRepository.findOne({
select: ["id", "topic", "status", "profileId"], select: ["id", "topic", "status", "profileId"],
@ -141,6 +178,11 @@ export class AppointController extends Controller {
}); });
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,8 +195,9 @@ export class AppointController extends Controller {
async Update( async Update(
@Request() request: RequestWithUser, @Request() request: RequestWithUser,
@Body() requestBody: UpdateAppoint, @Body() requestBody: UpdateAppoint,
@Path() id: string, @Path() id: string
) { ) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION"); await new permission().PermissionUpdate(request, "SYS_PROBATION");
const appoint: any = await this.appointRepository.findOne({ const appoint: any = await this.appointRepository.findOne({
@ -162,7 +205,10 @@ export class AppointController extends Controller {
}); });
if (!appoint) { if (!appoint) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการแต่งตั้งคณะกรรมการฯ"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลการแต่งตั้งคณะกรรมการฯ"
);
} }
const before = appoint; const before = appoint;
@ -185,6 +231,11 @@ export class AppointController extends Controller {
setLogDataDiff(request, { before, after: appoint }); setLogDataDiff(request, { before, after: appoint });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -194,7 +245,11 @@ export class AppointController extends Controller {
* *
*/ */
@Delete("{id}") @Delete("{id}")
public async deleteRole(@Path() id: string, @Request() request: RequestWithUser) { public async deleteRole(
@Path() id: string,
@Request() request: RequestWithUser
) {
try {
await new permission().PermissionDelete(request, "SYS_PROBATION"); await new permission().PermissionDelete(request, "SYS_PROBATION");
await this.appointDirectorRepository.delete({ appointId: id }); await this.appointDirectorRepository.delete({ appointId: id });
@ -203,6 +258,11 @@ export class AppointController extends Controller {
if (!result) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); 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,7 +272,11 @@ export class AppointController extends Controller {
* *
*/ */
@Get("/committee/{profileId}") @Get("/committee/{profileId}")
async GetCheckById(@Request() request: RequestWithUser, @Path() profileId: string) { async GetCheckById(
@Request() request: RequestWithUser,
@Path() profileId: string
) {
try {
await new permission().PermissionGet(request, "SYS_PROBATION"); await new permission().PermissionGet(request, "SYS_PROBATION");
const directorId = await new CallAPI() const directorId = await new CallAPI()
@ -229,11 +293,16 @@ export class AppointController extends Controller {
{ {
directorId, directorId,
profileId, profileId,
}, }
) )
.orderBy("appoint.createdAt", "DESC") .orderBy("appoint.createdAt", "DESC")
.getOne(); .getOne();
const check = appoint ? true : false; const check = appoint ? true : false;
return new HttpSuccess(check); return new HttpSuccess(check);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
} }

View file

@ -91,6 +91,7 @@ export class AssignController extends Controller {
@Request() request: RequestWithUser, @Request() request: RequestWithUser,
@Body() requestBody: CreateAssign @Body() requestBody: CreateAssign
) { ) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION"); await new permission().PermissionUpdate(request, "SYS_PROBATION");
const person = await this.personalRepository.findOne({ const person = await this.personalRepository.findOne({
where: { where: {
@ -194,7 +195,9 @@ export class AssignController extends Controller {
updateFullName: request.user.name, updateFullName: request.user.name,
}) })
); );
await this.assignCompetencyRepository.save(competencise, { data: request }); await this.assignCompetencyRepository.save(competencise, {
data: request,
});
setLogDataDiff(request, { before, after: competencise }); setLogDataDiff(request, { before, after: competencise });
const competencyGroups = await requestBody.assign_competency_group.map( const competencyGroups = await requestBody.assign_competency_group.map(
@ -245,6 +248,11 @@ export class AssignController extends Controller {
setLogDataDiff(request, { before, after: directors }); setLogDataDiff(request, { before, after: directors });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -259,6 +267,7 @@ export class AssignController extends Controller {
@Request() request: RequestWithUser, @Request() request: RequestWithUser,
@Body() requestBody: CreateAssign @Body() requestBody: CreateAssign
) { ) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION"); await new permission().PermissionUpdate(request, "SYS_PROBATION");
const assign = await this.assignRepository.findOne({ const assign = await this.assignRepository.findOne({
@ -267,7 +276,10 @@ export class AssignController extends Controller {
let before = assign; let before = assign;
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const person = await this.personalRepository.findOne({ const person = await this.personalRepository.findOne({
@ -473,6 +485,11 @@ export class AssignController extends Controller {
}); });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -486,6 +503,7 @@ export class AssignController extends Controller {
@Request() request: RequestWithUser, @Request() request: RequestWithUser,
@Query() personal_id: string @Query() personal_id: string
) { ) {
try {
let _workflow = await new permission().Workflow( let _workflow = await new permission().Workflow(
request, request,
personal_id, personal_id,
@ -540,6 +558,11 @@ export class AssignController extends Controller {
); );
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,6 +576,7 @@ export class AssignController extends Controller {
@Request() request: RequestWithUser, @Request() request: RequestWithUser,
@Query() personal_id: string @Query() personal_id: string
) { ) {
try {
const lists = await this.assignRepository.find({ const lists = await this.assignRepository.find({
select: ["id", "round_no", "date_start", "date_finish"], select: ["id", "round_no", "date_start", "date_finish"],
where: { personal_id }, where: { personal_id },
@ -600,6 +624,11 @@ export class AssignController extends Controller {
); );
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,6 +643,7 @@ export class AssignController extends Controller {
@Query() isReport: boolean = false, @Query() isReport: boolean = false,
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
let _workflow = await new permission().Workflow( let _workflow = await new permission().Workflow(
request, request,
assign_id, assign_id,
@ -643,7 +673,10 @@ export class AssignController extends Controller {
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const profileData = await this.personalRepository.findOne({ const profileData = await this.personalRepository.findOne({
@ -775,8 +808,8 @@ export class AssignController extends Controller {
description: x.competency_description, description: x.competency_description,
})); }));
const competencyGroupData = await this.assignCompetencyGroupRepository.find( const competencyGroupData =
{ await this.assignCompetencyGroupRepository.find({
select: [ select: [
"competency_group_id", "competency_group_id",
"competency_group_level", "competency_group_level",
@ -785,8 +818,7 @@ export class AssignController extends Controller {
], ],
where: { assign_id }, where: { assign_id },
order: { createdAt: "ASC" }, order: { createdAt: "ASC" },
} });
);
const competency_groups = await competencyGroupData.map((x) => ({ const competency_groups = await competencyGroupData.map((x) => ({
id: x.competency_group_id, id: x.competency_group_id,
level: x.competency_group_level, level: x.competency_group_level,
@ -821,8 +853,9 @@ export class AssignController extends Controller {
} }
} }
const commanderData = await (director.find((x) => x.role == "commander") ?? const commanderData = await (director.find(
null); (x) => x.role == "commander"
) ?? null);
const commander = await (commanderData const commander = await (commanderData
? { ? {
...commanderData, ...commanderData,
@ -867,6 +900,11 @@ export class AssignController extends Controller {
commander, commander,
chairman, chairman,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -881,6 +919,7 @@ export class AssignController extends Controller {
@Query() isReport: boolean = false, @Query() isReport: boolean = false,
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
const assign = await this.assignRepository.findOne({ const assign = await this.assignRepository.findOne({
select: [ select: [
"id", "id",
@ -902,7 +941,10 @@ export class AssignController extends Controller {
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const profileData = await this.personalRepository.findOne({ const profileData = await this.personalRepository.findOne({
@ -1034,8 +1076,8 @@ export class AssignController extends Controller {
description: x.competency_description, description: x.competency_description,
})); }));
const competencyGroupData = await this.assignCompetencyGroupRepository.find( const competencyGroupData =
{ await this.assignCompetencyGroupRepository.find({
select: [ select: [
"competency_group_id", "competency_group_id",
"competency_group_level", "competency_group_level",
@ -1044,8 +1086,7 @@ export class AssignController extends Controller {
], ],
where: { assign_id }, where: { assign_id },
order: { createdAt: "ASC" }, order: { createdAt: "ASC" },
} });
);
const competency_groups = await competencyGroupData.map((x) => ({ const competency_groups = await competencyGroupData.map((x) => ({
id: x.competency_group_id, id: x.competency_group_id,
level: x.competency_group_level, level: x.competency_group_level,
@ -1080,8 +1121,9 @@ export class AssignController extends Controller {
} }
} }
const commanderData = await (director.find((x) => x.role == "commander") ?? const commanderData = await (director.find(
null); (x) => x.role == "commander"
) ?? null);
const commander = await (commanderData const commander = await (commanderData
? { ? {
...commanderData, ...commanderData,
@ -1126,5 +1168,10 @@ export class AssignController extends Controller {
commander, commander,
chairman, chairman,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
} }

View file

@ -2,6 +2,8 @@ import { Controller, Route, Security, Tags, Request, Get, Path } from "tsoa";
import { RequestWithUser } from "../middlewares/user"; import { RequestWithUser } from "../middlewares/user";
import { AppDataSource } from "../database/data-source"; import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success"; 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 CallAPI from "../interfaces/call-api";
import { AssignDirector } from "../entities/AssignDirector"; import { AssignDirector } from "../entities/AssignDirector";
@ -15,7 +17,11 @@ export class AssignPermissionsController extends Controller {
private assignRepository = AppDataSource.getRepository(Assign); private assignRepository = AppDataSource.getRepository(Assign);
@Get("{id}") @Get("{id}")
async GetAssignPermissions(@Request() request: RequestWithUser, @Path() id: string) { async GetAssignPermissions(
@Request() request: RequestWithUser,
@Path() id: string
) {
try {
const director = await this.assignDirector.find({ const director = await this.assignDirector.find({
where: { assign_id: id }, where: { assign_id: id },
}); });
@ -26,7 +32,8 @@ export class AssignPermissionsController extends Controller {
console.error("Error calling API:", error); console.error("Error calling API:", error);
}); });
const role = await director.find((e: any) => e.personal_id === personalId)?.role; const role = await director.find((e: any) => e.personal_id === personalId)
?.role;
const reportPersonId = await this.assignRepository.findOneBy({ const reportPersonId = await this.assignRepository.findOneBy({
id, id,
@ -65,5 +72,10 @@ export class AssignPermissionsController extends Controller {
}; };
return new HttpSuccess(response); return new HttpSuccess(response);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
} }

View file

@ -1,13 +1,28 @@
import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Post, Body } from "tsoa" import {
import HttpSuccess from "../interfaces/http-success" Controller,
import HttpStatusCode from "../interfaces/http-status" Route,
import { RequestWithUser } from "../middlewares/user" Security,
import { findEndDate } from "../interfaces/utils" 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") @Route("api/v1/probation/calculate")
@Tags("ฟอร์มมอบหมายงาน") @Tags("ฟอร์มมอบหมายงาน")
@Security("bearerAuth") @Security("bearerAuth")
@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") @Response(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง"
)
export class CalculateController extends Controller { export class CalculateController extends Controller {
/** /**
* API * API
@ -19,14 +34,20 @@ export class CalculateController extends Controller {
async AssignFinish( async AssignFinish(
@Body() @Body()
requestBody: { requestBody: {
month: number month: number;
start_date: Date start_date: Date;
}, },
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
const { month, start_date } = requestBody try {
const finish_date = findEndDate(month, start_date) 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);
}
} }
} }

View file

@ -1,28 +1,42 @@
import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Query } from "tsoa" import {
import { AppDataSource } from "../database/data-source" Controller,
import HttpSuccess from "../interfaces/http-success" Route,
import HttpStatusCode from "../interfaces/http-status" Security,
import HttpError from "../interfaces/http-error" Tags,
import { RequestWithUser } from "../middlewares/user" Request,
import { Knowledge, TypeKnowledge } from "../entities/Knowledge" SuccessResponse,
import { Skill, TypeSkill } from "../entities/Skill" Response,
import { MapKnowledgeSkill } from "../entities/MapKnowledgeSkill" Get,
import { Personal } from "../entities/Personal" Query,
import { Law } from "../entities/Law" } from "tsoa";
import { Assign } from "../entities/Assign" import { AppDataSource } from "../database/data-source";
import permission from "../interfaces/permission" 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") @Route("api/v1/probation/data-options")
@Tags("Data Options") @Tags("Data Options")
@Security("bearerAuth") @Security("bearerAuth")
@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") @Response(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง"
)
export class DataOptionController extends Controller { export class DataOptionController extends Controller {
private personalRepository = AppDataSource.getRepository(Personal) private personalRepository = AppDataSource.getRepository(Personal);
private knowledgeRepository = AppDataSource.getRepository(Knowledge) private knowledgeRepository = AppDataSource.getRepository(Knowledge);
private mapKnowledgeSkillRepository = AppDataSource.getRepository(MapKnowledgeSkill) private mapKnowledgeSkillRepository =
private skillRepository = AppDataSource.getRepository(Skill) AppDataSource.getRepository(MapKnowledgeSkill);
private lawRepository = AppDataSource.getRepository(Law) private skillRepository = AppDataSource.getRepository(Skill);
private assignRepository = AppDataSource.getRepository(Assign) private lawRepository = AppDataSource.getRepository(Law);
private assignRepository = AppDataSource.getRepository(Assign);
/** /**
* API list * API list
@ -32,12 +46,13 @@ export class DataOptionController extends Controller {
*/ */
@Get("knowledge") @Get("knowledge")
async GetKnowledge(@Query() personal_id: string) { async GetKnowledge(@Query() personal_id: string) {
try {
const person = await this.personalRepository.findOne({ const person = await this.personalRepository.findOne({
where: { personal_id }, where: { personal_id },
}) });
if (!person) { if (!person) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล");
} }
let result = await this.mapKnowledgeSkillRepository.findOne({ let result = await this.mapKnowledgeSkillRepository.findOne({
@ -46,7 +61,7 @@ export class DataOptionController extends Controller {
positionLevelName: person.positionLevelName, positionLevelName: person.positionLevelName,
active: 1, active: 1,
}, },
}) });
if (!result) { if (!result) {
// ถ้าตำแหน่งไม่ตรงหาจากระดับตำแหน่งแทนเพื่อให้ฟอร์มสามารถกรอกต่อได้ // ถ้าตำแหน่งไม่ตรงหาจากระดับตำแหน่งแทนเพื่อให้ฟอร์มสามารถกรอกต่อได้
@ -55,18 +70,21 @@ export class DataOptionController extends Controller {
positionLevelName: person.positionLevelName, positionLevelName: person.positionLevelName,
active: 1, active: 1,
}, },
}) });
} }
if (!result) { if (!result) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลความรู้ที่ตรงกับตำแหน่ง") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลความรู้ที่ตรงกับตำแหน่ง"
);
} }
const knowledges = await this.knowledgeRepository.find({ const knowledges = await this.knowledgeRepository.find({
where: { type: TypeKnowledge.PERFORMANCE, active: 1 }, where: { type: TypeKnowledge.PERFORMANCE, active: 1 },
}) });
const knowledge = knowledges.map(knowledge => ({ const knowledge = knowledges.map((knowledge) => ({
id: knowledge.id, id: knowledge.id,
title: knowledge.title, title: knowledge.title,
description: description:
@ -80,9 +98,13 @@ export class DataOptionController extends Controller {
? knowledge.level4 ? knowledge.level4
: knowledge.level5, : knowledge.level5,
level: result.knowlage_performance_level, level: result.knowlage_performance_level,
})) }));
return new HttpSuccess(knowledge);
return new HttpSuccess(knowledge) } catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -93,44 +115,61 @@ export class DataOptionController extends Controller {
*/ */
@Get("skill") @Get("skill")
async GetSkill(@Query() personal_id: string) { async GetSkill(@Query() personal_id: string) {
try {
const person = await this.personalRepository.findOne({ const person = await this.personalRepository.findOne({
where: { personal_id }, where: { personal_id },
}) });
if (!person) { if (!person) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
} }
let result = await this.mapKnowledgeSkillRepository.findOne({ let result = await this.mapKnowledgeSkillRepository.findOne({
select: ["skill_computer_level", "skill_english_level", "skill_information_level", "skill_resourse_level"], select: [
"skill_computer_level",
"skill_english_level",
"skill_information_level",
"skill_resourse_level",
],
where: { where: {
positionName: person.positionName, positionName: person.positionName,
positionLevelName: person.positionLevelName, positionLevelName: person.positionLevelName,
active: 1, active: 1,
}, },
}) });
if (!result) { if (!result) {
// ถ้าตำแหน่งไม่ตรงหาจากระดับตำแหน่งแทนเพื่อให้ฟอร์มสามารถกรอกต่อได้ // ถ้าตำแหน่งไม่ตรงหาจากระดับตำแหน่งแทนเพื่อให้ฟอร์มสามารถกรอกต่อได้
result = await this.mapKnowledgeSkillRepository.findOne({ result = await this.mapKnowledgeSkillRepository.findOne({
select: ["skill_computer_level", "skill_english_level", "skill_information_level", "skill_resourse_level"], select: [
"skill_computer_level",
"skill_english_level",
"skill_information_level",
"skill_resourse_level",
],
where: { where: {
positionLevelName: person.positionLevelName, positionLevelName: person.positionLevelName,
active: 1, active: 1,
}, },
}) });
} }
if (!result) { if (!result) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทักษะที่ตรงกับตำแหน่ง") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลทักษะที่ตรงกับตำแหน่ง"
);
} }
const computerData = await this.skillRepository.findOne({ const computerData = await this.skillRepository.findOne({
where: { type: TypeSkill.COMPUTER, active: 1 }, where: { type: TypeSkill.COMPUTER, active: 1 },
}) });
if (!computerData) { if (!computerData) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทักษะคอมพิวเตอร์") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลทักษะคอมพิวเตอร์"
);
} }
const computer = await { const computer = await {
id: computerData.id, id: computerData.id,
@ -146,14 +185,17 @@ export class DataOptionController extends Controller {
? computerData.level4 ? computerData.level4
: computerData.level5, : computerData.level5,
level: result.skill_computer_level, level: result.skill_computer_level,
} };
const englishData = await this.skillRepository.findOne({ const englishData = await this.skillRepository.findOne({
where: { type: TypeSkill.ENG, active: 1 }, where: { type: TypeSkill.ENG, active: 1 },
}) });
if (!englishData) { if (!englishData) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทักษะภาษาอังกฤษ") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลทักษะภาษาอังกฤษ"
);
} }
const english = await { const english = await {
@ -170,14 +212,14 @@ export class DataOptionController extends Controller {
? englishData.level4 ? englishData.level4
: englishData.level5, : englishData.level5,
level: result.skill_english_level, level: result.skill_english_level,
} };
const informationData = await this.skillRepository.findOne({ const informationData = await this.skillRepository.findOne({
where: { type: TypeSkill.INFORMATION, active: 1 }, where: { type: TypeSkill.INFORMATION, active: 1 },
}) });
if (!informationData) { if (!informationData) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
} }
const information = await { const information = await {
@ -194,13 +236,13 @@ export class DataOptionController extends Controller {
? informationData.level4 ? informationData.level4
: informationData.level5, : informationData.level5,
level: result.skill_information_level, level: result.skill_information_level,
} };
const resourseData = await this.skillRepository.findOne({ const resourseData = await this.skillRepository.findOne({
where: { type: TypeSkill.RESOURSE, active: 1 }, where: { type: TypeSkill.RESOURSE, active: 1 },
}) });
if (!resourseData) { if (!resourseData) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
} }
const resourse = await { const resourse = await {
@ -217,14 +259,19 @@ export class DataOptionController extends Controller {
? resourseData.level4 ? resourseData.level4
: resourseData.level5, : resourseData.level5,
level: result.skill_resourse_level, level: result.skill_resourse_level,
} };
return new HttpSuccess({ return new HttpSuccess({
computer, computer,
english, english,
information, information,
resourse, resourse,
}) });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -235,23 +282,29 @@ export class DataOptionController extends Controller {
*/ */
@Get("law") @Get("law")
async GetLaw(@Query() personal_id: string) { async GetLaw(@Query() personal_id: string) {
try {
const results = await this.lawRepository.find({ const results = await this.lawRepository.find({
select: ["id", "parent_id", "description", "status_select"], select: ["id", "parent_id", "description", "status_select"],
where: { where: {
active: 1, active: 1,
}, },
}) });
if (!results) { if (!results) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
} }
const result = await results.map(v => ({ const result = await results.map((v) => ({
...v, ...v,
checked: 0, checked: 0,
})) }));
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);
}
} }
/** /**
@ -261,9 +314,18 @@ export class DataOptionController extends Controller {
* *
*/ */
@Get("new-assign") @Get("new-assign")
async NewAssign(@Query() personal_id: string, @Request() request: RequestWithUser) { async NewAssign(
let _workflow = await new permission().Workflow(request, personal_id, "SYS_PROBATION") @Query() personal_id: string,
if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION") @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");
const person = await this.personalRepository.findOne({ const person = await this.personalRepository.findOne({
select: [ select: [
@ -282,28 +344,33 @@ export class DataOptionController extends Controller {
"updatedAt", "updatedAt",
], ],
where: { personal_id }, where: { personal_id },
}) });
if (!person) { if (!person) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
} }
const assign = await this.assignRepository.count({ const assign = await this.assignRepository.count({
where: { where: {
personal_id, personal_id,
}, },
}) });
const responsePerson = { const responsePerson = {
id: person.personal_id, id: person.personal_id,
...person, ...person,
} };
return new HttpSuccess({ return new HttpSuccess({
person: responsePerson, person: responsePerson,
assign_no: assign + 1, assign_no: assign + 1,
assign_month: 6, assign_month: 6,
}) });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
* API (USER) * API (USER)
@ -312,7 +379,11 @@ export class DataOptionController extends Controller {
* *
*/ */
@Get("new-assign-user") @Get("new-assign-user")
async NewAssignUser(@Query() personal_id: string, @Request() request: RequestWithUser) { async NewAssignUser(
@Query() personal_id: string,
@Request() request: RequestWithUser
) {
try {
const person = await this.personalRepository.findOne({ const person = await this.personalRepository.findOne({
select: [ select: [
"personal_id", "personal_id",
@ -330,27 +401,32 @@ export class DataOptionController extends Controller {
"updatedAt", "updatedAt",
], ],
where: { personal_id }, where: { personal_id },
}) });
if (!person) { if (!person) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
} }
const assign = await this.assignRepository.count({ const assign = await this.assignRepository.count({
where: { where: {
personal_id, personal_id,
}, },
}) });
const responsePerson = { const responsePerson = {
id: person.personal_id, id: person.personal_id,
...person, ...person,
} };
return new HttpSuccess({ return new HttpSuccess({
person: responsePerson, person: responsePerson,
assign_no: assign + 1, assign_no: assign + 1,
assign_month: 6, assign_month: 6,
}) });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
} }

View file

@ -53,6 +53,7 @@ export class EvaluateChairmanController extends Controller {
@Query() assign_id: string, @Query() assign_id: string,
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
let _workflow = await new permission().Workflow( let _workflow = await new permission().Workflow(
request, request,
assign_id, assign_id,
@ -78,7 +79,10 @@ export class EvaluateChairmanController extends Controller {
where: { id: assign_id }, where: { id: assign_id },
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const profile = await (assign.profile const profile = await (assign.profile
@ -192,6 +196,11 @@ export class EvaluateChairmanController extends Controller {
mentors, mentors,
chairman, chairman,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -206,6 +215,7 @@ export class EvaluateChairmanController extends Controller {
@Query() assign_id: string, @Query() assign_id: string,
@Query() evaluate_no?: string @Query() evaluate_no?: string
) { ) {
try {
await new permission().PermissionGet(request, "SYS_PROBATION"); await new permission().PermissionGet(request, "SYS_PROBATION");
// ต้องปรับเป็น id ของคนที่ access เข้ามา // ต้องปรับเป็น id ของคนที่ access เข้ามา
const director = await this.assignDirectorRepository.findOne({ const director = await this.assignDirectorRepository.findOne({
@ -251,7 +261,10 @@ export class EvaluateChairmanController extends Controller {
where: { id: assign_id }, where: { id: assign_id },
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const experimenteeData = await this.personalRepository.find({ const experimenteeData = await this.personalRepository.find({
@ -357,6 +370,11 @@ export class EvaluateChairmanController extends Controller {
assign, assign,
evaluate, evaluate,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -371,6 +389,7 @@ export class EvaluateChairmanController extends Controller {
@Body() requestBody: CreateEvaluateChairman, @Body() requestBody: CreateEvaluateChairman,
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION"); await new permission().PermissionUpdate(request, "SYS_PROBATION");
const director = await this.assignDirectorRepository.findOne({ const director = await this.assignDirectorRepository.findOne({
@ -391,7 +410,10 @@ export class EvaluateChairmanController extends Controller {
where: { id: assign_id }, where: { id: assign_id },
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const postData: any = await { const postData: any = await {
@ -446,6 +468,11 @@ export class EvaluateChairmanController extends Controller {
} }
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -461,6 +488,7 @@ export class EvaluateChairmanController extends Controller {
@Body() requestBody: CreateEvaluateChairman, @Body() requestBody: CreateEvaluateChairman,
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION"); await new permission().PermissionUpdate(request, "SYS_PROBATION");
let evaluate = await this.evaluateChairmanRepository.findOne({ let evaluate = await this.evaluateChairmanRepository.findOne({
@ -504,7 +532,8 @@ export class EvaluateChairmanController extends Controller {
requestBody.behavior_orther.text != "" requestBody.behavior_orther.text != ""
? Number(requestBody.behavior_orther.level) ? Number(requestBody.behavior_orther.level)
: 0; : 0;
evaluate.develop_orientation_score = requestBody.develop_orientation_score; evaluate.develop_orientation_score =
requestBody.develop_orientation_score;
evaluate.develop_self_learning_score = evaluate.develop_self_learning_score =
requestBody.develop_self_learning_score; requestBody.develop_self_learning_score;
evaluate.develop_training_seminar_score = evaluate.develop_training_seminar_score =
@ -539,5 +568,10 @@ export class EvaluateChairmanController extends Controller {
setLogDataDiff(request, { before, after: evaluate }); 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);
}
} }
} }

View file

@ -1,25 +1,46 @@
import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Post, Body, Query, Put } from "tsoa" import {
import HttpSuccess from "../interfaces/http-success" Controller,
import HttpStatusCode from "../interfaces/http-status" Route,
import { RequestWithUser } from "../middlewares/user" Security,
import { findEndDate, setLogDataDiff } from "../interfaces/utils" Tags,
import { AppDataSource } from "../database/data-source" Request,
import { AssignDirector } from "../entities/AssignDirector" SuccessResponse,
import HttpError from "../interfaces/http-error" Response,
import { Assign } from "../entities/Assign" Get,
import { CreateEvaluateCommander, EvaluateCommander } from "../entities/EvaluateCommander" Post,
import { Personal } from "../entities/Personal" Body,
import CallAPI from "../interfaces/call-api" Query,
import permission from "../interfaces/permission" 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") @Route("api/v1/probation/evaluate")
@Tags("แบบประเมินผล (ผู้บังคับบัญชา)") @Tags("แบบประเมินผล (ผู้บังคับบัญชา)")
@Security("bearerAuth") @Security("bearerAuth")
@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") @Response(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง"
)
export class EvaluateController extends Controller { export class EvaluateController extends Controller {
private assignDirectorRepository = AppDataSource.getRepository(AssignDirector) private assignDirectorRepository =
private assignRepository = AppDataSource.getRepository(Assign) AppDataSource.getRepository(AssignDirector);
private evaluateCommanderRepository = AppDataSource.getRepository(EvaluateCommander) private assignRepository = AppDataSource.getRepository(Assign);
private personalRepository = AppDataSource.getRepository(Personal) private evaluateCommanderRepository =
AppDataSource.getRepository(EvaluateCommander);
private personalRepository = AppDataSource.getRepository(Personal);
/** /**
* API () * API ()
@ -28,9 +49,18 @@ export class EvaluateController extends Controller {
* *
*/ */
@Get("create") @Get("create")
async CreateEvaluate(@Query() assign_id: string, @Request() request: RequestWithUser) { async CreateEvaluate(
let _workflow = await new permission().Workflow(request, assign_id, "SYS_PROBATION") @Query() assign_id: string,
if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION") @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({ const director = await this.assignDirectorRepository.findOne({
select: ["personal_id"], select: ["personal_id"],
@ -38,50 +68,70 @@ export class EvaluateController extends Controller {
assign_id, assign_id,
role: "commander", role: "commander",
}, },
}) });
if (!director) { if (!director) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล");
} }
const director_id = director.personal_id const director_id = director.personal_id;
const assign = await this.assignRepository.findOne({ const assign = await this.assignRepository.findOne({
relations: ["profile"], relations: ["profile"],
where: { id: assign_id }, where: { id: assign_id },
}) });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const profile = await (assign.profile const profile = await (assign.profile
? { ? {
...assign.profile, ...assign.profile,
id: assign.profile.personal_id, id: assign.profile.personal_id,
name: assign.profile.prefixName + assign.profile.firstName + " " + assign.profile.lastName, name:
assign.profile.prefixName +
assign.profile.firstName +
" " +
assign.profile.lastName,
Oc: assign.profile.organization, Oc: assign.profile.organization,
} }
: null) : null);
const evaluate_amount = await this.evaluateCommanderRepository.count({ const evaluate_amount = await this.evaluateCommanderRepository.count({
where: { where: {
assign_id, assign_id,
director_id, director_id,
}, },
}) });
const evaluate_no = await (evaluate_amount + 1) const evaluate_no = await (evaluate_amount + 1);
const start_date = evaluate_amount == 0 ? assign.date_start : findEndDate(evaluate_amount * 3, assign.date_start) const start_date =
evaluate_amount == 0
? assign.date_start
: findEndDate(evaluate_amount * 3, assign.date_start);
const commanderData = await this.assignDirectorRepository.findOne({ const commanderData = await this.assignDirectorRepository.findOne({
select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], select: [
"personal_id",
"dated",
"fullname",
"position",
"posType",
"posLevel",
],
where: { personal_id: director_id }, where: { personal_id: director_id },
}) });
if (!commanderData) { if (!commanderData) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้บังคับบัญชา") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลผู้บังคับบัญชา"
);
} }
const commander = await { const commander = await {
...commanderData, ...commanderData,
name: commanderData.fullname, name: commanderData.fullname,
label: `${commanderData.fullname} (${commanderData.position}${commanderData.posLevel})`, label: `${commanderData.fullname} (${commanderData.position}${commanderData.posLevel})`,
} };
return new HttpSuccess({ return new HttpSuccess({
person: profile, person: profile,
@ -90,7 +140,12 @@ export class EvaluateController extends Controller {
start_date: start_date, start_date: start_date,
end_date: findEndDate(3, start_date), end_date: findEndDate(3, start_date),
director: commander, director: commander,
}) });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -100,8 +155,13 @@ export class EvaluateController extends Controller {
* *
*/ */
@Get("") @Get("")
async GetEvaluate(@Request() request: RequestWithUser, @Query() assign_id: string, @Query() evaluate_no?: string) { async GetEvaluate(
await new permission().PermissionGet(request, "SYS_PROBATION") @Request() request: RequestWithUser,
@Query() assign_id: string,
@Query() evaluate_no?: string
) {
try {
await new permission().PermissionGet(request, "SYS_PROBATION");
// ต้องปรับเป็น id ของคนที่ access เข้ามา // ต้องปรับเป็น id ของคนที่ access เข้ามา
const director = await this.assignDirectorRepository.findOne({ const director = await this.assignDirectorRepository.findOne({
@ -110,12 +170,12 @@ export class EvaluateController extends Controller {
assign_id, assign_id,
role: "commander", role: "commander",
}, },
}) });
if (!director) { if (!director) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล");
} }
const director_id = director.personal_id const director_id = director.personal_id;
let evaluate: any = null let evaluate: any = null;
if (evaluate_no) { if (evaluate_no) {
evaluate = await this.evaluateCommanderRepository.findOne({ evaluate = await this.evaluateCommanderRepository.findOne({
where: { where: {
@ -123,31 +183,34 @@ export class EvaluateController extends Controller {
assign_id, assign_id,
no: evaluate_no, no: evaluate_no,
}, },
}) });
} else { } else {
evaluate = await this.evaluateCommanderRepository.find({ evaluate = await this.evaluateCommanderRepository.find({
where: { where: {
director_id, director_id,
assign_id, assign_id,
}, },
}) });
if (evaluate) if (evaluate)
evaluate = await evaluate.map((element: EvaluateCommander) => ({ evaluate = await evaluate.map((element: EvaluateCommander) => ({
...element, ...element,
no: Number(element.no), no: Number(element.no),
})) }));
} }
if (!evaluate) { if (!evaluate) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบประเมิน") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบประเมิน");
} }
const assign = await this.assignRepository.findOne({ const assign = await this.assignRepository.findOne({
where: { id: assign_id }, where: { id: assign_id },
}) });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
// const profile = await (assign.profile // const profile = await (assign.profile
@ -176,33 +239,53 @@ export class EvaluateController extends Controller {
// : findEndDate(evaluate_amount * 3, assign.date_start); // : findEndDate(evaluate_amount * 3, assign.date_start);
const directorData = await this.assignDirectorRepository.find({ const directorData = await this.assignDirectorRepository.find({
select: ["personal_id", "dated", "fullname", "position", "posType", "posLevel"], select: [
"personal_id",
"dated",
"fullname",
"position",
"posType",
"posLevel",
],
where: { personal_id: director_id }, where: { personal_id: director_id },
}) });
const directors = await directorData.map(element => ({ const directors = await directorData.map((element) => ({
...element, ...element,
name: element.fullname, name: element.fullname,
label: `${element.fullname} (${element.position}${element.posLevel})`, label: `${element.fullname} (${element.position}${element.posLevel})`,
})) }));
const experimenteeData = await this.personalRepository.find({ const experimenteeData = await this.personalRepository.find({
select: ["personal_id", "prefixName", "firstName", "lastName", "positionName", "positionLevelName", "organization"], select: [
"personal_id",
"prefixName",
"firstName",
"lastName",
"positionName",
"positionLevelName",
"organization",
],
where: { personal_id: assign.personal_id }, where: { personal_id: assign.personal_id },
}) });
const experimentee = await experimenteeData.map(element => ({ const experimentee = await experimenteeData.map((element) => ({
...element, ...element,
name: element.prefixName + element.firstName + " " + element.lastName, name: element.prefixName + element.firstName + " " + element.lastName,
Oc: element.organization, Oc: element.organization,
})) }));
return new HttpSuccess({ return new HttpSuccess({
experimentee: experimentee, experimentee: experimentee,
director: directors ? directors : null, director: directors ? directors : null,
assign, assign,
evaluate, evaluate,
}) });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -212,8 +295,13 @@ export class EvaluateController extends Controller {
* *
*/ */
@Post("") @Post("")
async PostData(@Query() assign_id: string, @Body() requestBody: CreateEvaluateCommander, @Request() request: RequestWithUser) { async PostData(
await new permission().PermissionUpdate(request, "SYS_PROBATION") @Query() assign_id: string,
@Body() requestBody: CreateEvaluateCommander,
@Request() request: RequestWithUser
) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION");
const director = await this.assignDirectorRepository.findOne({ const director = await this.assignDirectorRepository.findOne({
select: ["personal_id"], select: ["personal_id"],
@ -221,19 +309,22 @@ export class EvaluateController extends Controller {
assign_id, assign_id,
role: "commander", role: "commander",
}, },
}) });
if (!director) { if (!director) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล");
} }
const director_id = director.personal_id const director_id = director.personal_id;
const assign = await this.assignRepository.findOne({ const assign = await this.assignRepository.findOne({
relations: ["profile"], relations: ["profile"],
where: { id: assign_id }, where: { id: assign_id },
}) });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const postData: any = await { const postData: any = await {
@ -244,27 +335,34 @@ export class EvaluateController extends Controller {
date_start: requestBody.start_date, date_start: requestBody.start_date,
personal_id: assign.personal_id, personal_id: assign.personal_id,
achievement_other_desc: requestBody.achievement_other ? requestBody.achievement_other.text : "", achievement_other_desc: requestBody.achievement_other
achievement_other_level: requestBody.achievement_other ? Number(requestBody.achievement_other.level) : 0, ? 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_desc: requestBody.behavior_orther.text,
behavior_other_level: requestBody.behavior_orther.text != "" ? Number(requestBody.behavior_orther.level) : 0, behavior_other_level:
requestBody.behavior_orther.text != ""
? Number(requestBody.behavior_orther.level)
: 0,
createdUserId: request.user.sub, createdUserId: request.user.sub,
createdFullName: request.user.name, createdFullName: request.user.name,
updateUserId: request.user.sub, updateUserId: request.user.sub,
updateFullName: request.user.name, updateFullName: request.user.name,
} };
await this.evaluateCommanderRepository.save(postData, { await this.evaluateCommanderRepository.save(postData, {
data: request, data: request,
}) });
setLogDataDiff(request, { before: null, after: postData }) setLogDataDiff(request, { before: null, after: postData });
if (Number(requestBody.evaluate_no) < 2) { if (Number(requestBody.evaluate_no) < 2) {
// #noted cronjob // #noted cronjob
// แจ้งผู้บังคับบัญชาเข้ามาบันทึกผลทุก 3 เดือน 2 ครั้ง // แจ้งผู้บังคับบัญชาเข้ามาบันทึกผลทุก 3 เดือน 2 ครั้ง
var dateSend = await findEndDate(3, requestBody.start_date) var dateSend = await findEndDate(3, requestBody.start_date);
const nextNo = await (Number(requestBody.evaluate_no) + 1) const nextNo = await (Number(requestBody.evaluate_no) + 1);
await new CallAPI() await new CallAPI()
.PostData(request, "/placement/noti", { .PostData(request, "/placement/noti", {
subject: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`, subject: `ถึงกำหนดประเมินผลการทดลองปฏิบัติหน้าที่ราชการครั้งที่ ${nextNo} ${assign.profile.prefixName}${assign.profile.firstName} ${assign.profile.lastName}`,
@ -275,12 +373,17 @@ export class EvaluateController extends Controller {
isSendInbox: true, isSendInbox: true,
receiveDate: dateSend, receiveDate: dateSend,
}) })
.catch(error => { .catch((error) => {
console.error("Error calling API:", 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);
}
} }
/** /**
@ -296,54 +399,68 @@ export class EvaluateController extends Controller {
@Body() requestBody: CreateEvaluateCommander, @Body() requestBody: CreateEvaluateCommander,
@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.evaluateCommanderRepository.findOne({ let evaluate = await this.evaluateCommanderRepository.findOne({
where: { id: evaluate_id }, where: { id: evaluate_id },
}) });
const before = evaluate const before = evaluate;
if (!evaluate) { if (!evaluate) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมิน");
} }
evaluate.commander_dated = requestBody.commander_dated evaluate.commander_dated = requestBody.commander_dated;
evaluate.knowledge_level = requestBody.knowledge_level evaluate.knowledge_level = requestBody.knowledge_level;
evaluate.skill_level = requestBody.skill_level evaluate.skill_level = requestBody.skill_level;
evaluate.competency_level = requestBody.competency_level evaluate.competency_level = requestBody.competency_level;
evaluate.learn_level = requestBody.learn_level evaluate.learn_level = requestBody.learn_level;
evaluate.apply_level = requestBody.apply_level evaluate.apply_level = requestBody.apply_level;
evaluate.success_level = requestBody.success_level evaluate.success_level = requestBody.success_level;
evaluate.achievement_other_desc = requestBody.achievement_other ? requestBody.achievement_other.text : "" evaluate.achievement_other_desc = requestBody.achievement_other
evaluate.achievement_other_level = requestBody.achievement_other.text != "" ? Number(requestBody.achievement_other.level) : 0 ? 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.conduct1_level = requestBody.conduct1_level;
evaluate.conduct2_level = requestBody.conduct2_level evaluate.conduct2_level = requestBody.conduct2_level;
evaluate.conduct3_level = requestBody.conduct3_level evaluate.conduct3_level = requestBody.conduct3_level;
evaluate.conduct4_level = requestBody.conduct4_level evaluate.conduct4_level = requestBody.conduct4_level;
evaluate.moral1_level = requestBody.moral1_level evaluate.moral1_level = requestBody.moral1_level;
evaluate.moral2_level = requestBody.moral2_level evaluate.moral2_level = requestBody.moral2_level;
evaluate.moral3_level = requestBody.moral3_level evaluate.moral3_level = requestBody.moral3_level;
evaluate.discipline1_level = requestBody.discipline1_level evaluate.discipline1_level = requestBody.discipline1_level;
evaluate.discipline2_level = requestBody.discipline2_level evaluate.discipline2_level = requestBody.discipline2_level;
evaluate.discipline3_level = requestBody.discipline3_level evaluate.discipline3_level = requestBody.discipline3_level;
evaluate.discipline4_level = requestBody.discipline4_level evaluate.discipline4_level = requestBody.discipline4_level;
evaluate.discipline5_level = requestBody.discipline5_level evaluate.discipline5_level = requestBody.discipline5_level;
evaluate.behavior_other_desc = requestBody.behavior_orther.text evaluate.behavior_other_desc = requestBody.behavior_orther.text;
evaluate.behavior_other_level = requestBody.behavior_orther.text != "" ? Number(requestBody.behavior_orther.level) : 0 evaluate.behavior_other_level =
evaluate.behavior_strength_desc = requestBody.behavior_strength_desc requestBody.behavior_orther.text != ""
evaluate.behavior_improve_desc = requestBody.behavior_improve_desc ? Number(requestBody.behavior_orther.level)
evaluate.orientation = requestBody.orientation : 0;
evaluate.self_learning = requestBody.self_learning evaluate.behavior_strength_desc = requestBody.behavior_strength_desc;
evaluate.training_seminar = requestBody.training_seminar evaluate.behavior_improve_desc = requestBody.behavior_improve_desc;
evaluate.other_training = requestBody.other_training evaluate.orientation = requestBody.orientation;
evaluate.updateUserId = request.user.sub evaluate.self_learning = requestBody.self_learning;
evaluate.updateFullName = request.user.name 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 }) await this.evaluateCommanderRepository.save(evaluate, { data: request });
setLogDataDiff(request, { before, after: evaluate }) 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);
}
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,10 @@ import { Assign } from "../entities/Assign";
import { Personal } from "../entities/Personal"; import { Personal } from "../entities/Personal";
import CallAPI from "../interfaces/call-api"; import CallAPI from "../interfaces/call-api";
import { EvaluateChairman } from "../entities/EvaluateChairman"; import { EvaluateChairman } from "../entities/EvaluateChairman";
import { CreateEvaluateResult, EvaluateResult } from "../entities/EvaluateResult"; import {
CreateEvaluateResult,
EvaluateResult,
} from "../entities/EvaluateResult";
import permission from "../interfaces/permission"; import permission from "../interfaces/permission";
@Route("api/v1/probation/evaluate-result") @Route("api/v1/probation/evaluate-result")
@ -32,14 +35,17 @@ import permission from "../interfaces/permission";
@Security("bearerAuth") @Security("bearerAuth")
@Response( @Response(
HttpStatusCode.INTERNAL_SERVER_ERROR, HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง", "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง"
) )
export class EvaluateResultController extends Controller { export class EvaluateResultController extends Controller {
private assignDirectorRepository = AppDataSource.getRepository(AssignDirector); private assignDirectorRepository =
AppDataSource.getRepository(AssignDirector);
private assignRepository = AppDataSource.getRepository(Assign); private assignRepository = AppDataSource.getRepository(Assign);
private evaluateChairmanRepository = AppDataSource.getRepository(EvaluateChairman); private evaluateChairmanRepository =
AppDataSource.getRepository(EvaluateChairman);
private personalRepository = AppDataSource.getRepository(Personal); private personalRepository = AppDataSource.getRepository(Personal);
private evaluateResultRepository = AppDataSource.getRepository(EvaluateResult); private evaluateResultRepository =
AppDataSource.getRepository(EvaluateResult);
/** /**
* API * API
@ -48,16 +54,28 @@ export class EvaluateResultController extends Controller {
* *
*/ */
@Get("create") @Get("create")
async CreateEvaluate(@Query() assign_id: string, @Request() request: RequestWithUser) { async CreateEvaluate(
let _workflow = await new permission().Workflow(request, assign_id, "SYS_PROBATION"); @Query() assign_id: string,
if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION"); @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 assign = await this.assignRepository.findOne({ const assign = await this.assignRepository.findOne({
relations: ["profile"], relations: ["profile"],
where: { id: assign_id }, where: { id: assign_id },
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const profile = await (assign.profile const profile = await (assign.profile
@ -65,7 +83,10 @@ export class EvaluateResultController extends Controller {
...assign.profile, ...assign.profile,
id: assign.profile.personal_id, id: assign.profile.personal_id,
name: name:
assign.profile.prefixName + assign.profile.firstName + " " + assign.profile.lastName, assign.profile.prefixName +
assign.profile.firstName +
" " +
assign.profile.lastName,
Oc: assign.profile.organization, Oc: assign.profile.organization,
} }
: null); : null);
@ -76,7 +97,10 @@ export class EvaluateResultController extends Controller {
}); });
if (!directorData) { if (!directorData) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน"
);
} }
let mentors = []; let mentors = [];
@ -89,7 +113,10 @@ export class EvaluateResultController extends Controller {
personal_id: e.personal_id, personal_id: e.personal_id,
dated: e.dated, dated: e.dated,
name: e.fullname, name: e.fullname,
label: e.fullname + " " + (e.position ? `(${e.position}${e.posLevel})` : ""), label:
e.fullname +
" " +
(e.position ? `(${e.position}${e.posLevel})` : ""),
position: e.position, position: e.position,
posType: e.posType, posType: e.posType,
posLevel: e.posLevel, posLevel: e.posLevel,
@ -97,7 +124,9 @@ export class EvaluateResultController extends Controller {
} }
} }
const commanderData = await (directorData.find((x) => x.role == "commander") ?? null); const commanderData = await (directorData.find(
(x) => x.role == "commander"
) ?? null);
const commander = const commander =
commanderData != null commanderData != null
@ -117,7 +146,9 @@ export class EvaluateResultController extends Controller {
} }
: null; : null;
const chairmanData = await (directorData.find((x) => x.role == "chairman") ?? null); const chairmanData = await (directorData.find(
(x) => x.role == "chairman"
) ?? null);
const chairman = const chairman =
chairmanData != null chairmanData != null
? { ? {
@ -127,7 +158,9 @@ export class EvaluateResultController extends Controller {
label: label:
chairmanData.fullname + chairmanData.fullname +
" " + " " +
(chairmanData.position ? `(${chairmanData.position}${chairmanData.posLevel})` : ""), (chairmanData.position
? `(${chairmanData.position}${chairmanData.posLevel})`
: ""),
position: chairmanData.position, position: chairmanData.position,
posType: chairmanData.posType, posType: chairmanData.posType,
posLevel: chairmanData.posLevel, posLevel: chairmanData.posLevel,
@ -148,12 +181,17 @@ export class EvaluateResultController extends Controller {
}); });
if (!resultData) { if (!resultData) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการประเมินผล"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลการประเมินผล"
);
} }
const result = await Promise.all( const result = await Promise.all(
resultData.map(async (e) => { resultData.map(async (e) => {
const check = await this.evaluateResultRepository.count({ where: { assign_id, no: e.no } }); const check = await this.evaluateResultRepository.count({
where: { assign_id, no: e.no },
});
const develop_complete = const develop_complete =
e.develop_orientation_score > 0 && e.develop_orientation_score > 0 &&
@ -186,7 +224,7 @@ export class EvaluateResultController extends Controller {
start_date: startDate, start_date: startDate,
end_date: endDate, end_date: endDate,
}; };
}), })
); );
// const develop_complete = await (resultData.develop_orientation_score > 0 && // const develop_complete = await (resultData.develop_orientation_score > 0 &&
@ -210,6 +248,11 @@ export class EvaluateResultController extends Controller {
commander, commander,
chairman, chairman,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -222,8 +265,9 @@ export class EvaluateResultController extends Controller {
async GetEvaluate( async GetEvaluate(
@Request() request: RequestWithUser, @Request() request: RequestWithUser,
@Query() assign_id: string, @Query() assign_id: string,
@Query() evaluate_no?: string, @Query() evaluate_no?: string
) { ) {
try {
await new permission().PermissionGet(request, "SYS_PROBATION"); await new permission().PermissionGet(request, "SYS_PROBATION");
// ต้องปรับเป็น id ของคนที่ access เข้ามา // ต้องปรับเป็น id ของคนที่ access เข้ามา
@ -255,7 +299,10 @@ export class EvaluateResultController extends Controller {
where: { id: assign_id }, where: { id: assign_id },
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const experimenteeData = await this.personalRepository.findOne({ const experimenteeData = await this.personalRepository.findOne({
@ -281,10 +328,15 @@ export class EvaluateResultController extends Controller {
const experimentee = await { const experimentee = await {
...experimenteeData, ...experimenteeData,
name: name:
experimenteeData.prefixName + experimenteeData.firstName + " " + experimenteeData.lastName, experimenteeData.prefixName +
PositionLevel: experimenteeData.positionName + experimenteeData.positionLevelName, experimenteeData.firstName +
" " +
experimenteeData.lastName,
PositionLevel:
experimenteeData.positionName + experimenteeData.positionLevelName,
Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-", Department: splitOcAmount > 2 ? splitOc[splitOcAmount - 3] : "-",
OrganizationOrganization: splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-", OrganizationOrganization:
splitOcAmount > 1 ? splitOc[splitOcAmount - 2] : "-",
Oc: experimenteeData.orgRootName, Oc: experimenteeData.orgRootName,
}; };
@ -294,7 +346,10 @@ export class EvaluateResultController extends Controller {
}); });
if (!directorData) { if (!directorData) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลผู้ดูแล ผู้บังคับบัญชาและประธาน"
);
} }
let mentors = []; let mentors = [];
@ -307,7 +362,10 @@ export class EvaluateResultController extends Controller {
personal_id: e.personal_id, personal_id: e.personal_id,
dated: e.dated, dated: e.dated,
name: e.fullname, name: e.fullname,
label: e.fullname + " " + (e.position ? `(${e.position}${e.posLevel})` : ""), label:
e.fullname +
" " +
(e.position ? `(${e.position}${e.posLevel})` : ""),
position: e.position + e.posLevel, position: e.position + e.posLevel,
posType: e.posType, posType: e.posType,
posLevel: e.posLevel, posLevel: e.posLevel,
@ -343,7 +401,9 @@ export class EvaluateResultController extends Controller {
posType: evaluate.authority_type, posType: evaluate.authority_type,
posLevel: evaluate.authority_level, posLevel: evaluate.authority_level,
}; };
const chairmanData = await (directorData.find((x) => x.role == "chairman") ?? null); const chairmanData = await (directorData.find(
(x) => x.role == "chairman"
) ?? null);
const chairman = const chairman =
chairmanData != null chairmanData != null
? { ? {
@ -353,7 +413,9 @@ export class EvaluateResultController extends Controller {
label: label:
chairmanData.fullname + chairmanData.fullname +
" " + " " +
(chairmanData.position ? `(${chairmanData.position}${chairmanData.posLevel})` : ""), (chairmanData.position
? `(${chairmanData.position}${chairmanData.posLevel})`
: ""),
position: chairmanData.position + chairmanData.posLevel, position: chairmanData.position + chairmanData.posLevel,
posType: chairmanData.posType, posType: chairmanData.posType,
posLevel: chairmanData.posLevel, posLevel: chairmanData.posLevel,
@ -368,6 +430,11 @@ export class EvaluateResultController extends Controller {
assign, assign,
evaluate: evaluate ? evaluate : null, evaluate: evaluate ? evaluate : null,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -380,8 +447,9 @@ export class EvaluateResultController extends Controller {
async PostData( async PostData(
@Query() assign_id: string, @Query() assign_id: string,
@Body() requestBody: CreateEvaluateResult, @Body() requestBody: CreateEvaluateResult,
@Request() request: RequestWithUser, @Request() request: RequestWithUser
) { ) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION"); await new permission().PermissionUpdate(request, "SYS_PROBATION");
const director = await this.assignDirectorRepository.findOne({ const director = await this.assignDirectorRepository.findOne({
@ -402,7 +470,10 @@ export class EvaluateResultController extends Controller {
where: { id: assign_id }, where: { id: assign_id },
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const postData: any = await { const postData: any = await {
@ -412,7 +483,8 @@ export class EvaluateResultController extends Controller {
no: requestBody.evaluate_no, no: requestBody.evaluate_no,
personal_id: assign.personal_id, personal_id: assign.personal_id,
date_start: requestBody.start_date, date_start: requestBody.start_date,
expand_month: requestBody.pass_result == 3 ? Number(requestBody.expand_month) : 0, expand_month:
requestBody.pass_result == 3 ? Number(requestBody.expand_month) : 0,
createdUserId: request.user.sub, createdUserId: request.user.sub,
createdFullName: request.user.name, createdFullName: request.user.name,
@ -426,6 +498,11 @@ export class EvaluateResultController extends Controller {
setLogDataDiff(request, { before: null, after: postData }); setLogDataDiff(request, { before: null, after: postData });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -438,8 +515,9 @@ export class EvaluateResultController extends Controller {
async PatchData( async PatchData(
@Query() assign_id: string, @Query() assign_id: string,
@Query() evaluate_no: number | string, @Query() evaluate_no: number | string,
@Request() request: RequestWithUser, @Request() request: RequestWithUser
) { ) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION"); await new permission().PermissionUpdate(request, "SYS_PROBATION");
const assign = await this.assignRepository.findOne({ const assign = await this.assignRepository.findOne({
@ -447,7 +525,10 @@ export class EvaluateResultController extends Controller {
where: { id: assign_id }, where: { id: assign_id },
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const result = await this.evaluateResultRepository.findOne({ const result = await this.evaluateResultRepository.findOne({
@ -455,7 +536,10 @@ export class EvaluateResultController extends Controller {
}); });
if (!result) { if (!result) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผลการประเมิน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลผลการประเมิน"
);
} }
const personal = await this.personalRepository.findOne({ const personal = await this.personalRepository.findOne({
@ -494,6 +578,11 @@ export class EvaluateResultController extends Controller {
await this.personalRepository.save(personal, { data: request }); await this.personalRepository.save(personal, { data: request });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -507,8 +596,9 @@ export class EvaluateResultController extends Controller {
@Query() assign_id: string, @Query() assign_id: string,
@Query() evaluate_id: string, @Query() evaluate_id: string,
@Body() requestBody: CreateEvaluateResult, @Body() requestBody: CreateEvaluateResult,
@Request() request: RequestWithUser, @Request() request: RequestWithUser
) { ) {
try {
await new permission().PermissionUpdate(request, "SYS_PROBATION"); await new permission().PermissionUpdate(request, "SYS_PROBATION");
let evaluate = await this.evaluateResultRepository.findOne({ let evaluate = await this.evaluateResultRepository.findOne({
@ -545,7 +635,10 @@ export class EvaluateResultController extends Controller {
where: { id: assign_id }, where: { id: assign_id },
}); });
if (!assign) { if (!assign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลแบบมอบหมายงาน"); throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบข้อมูลแบบมอบหมายงาน"
);
} }
const personal = await this.personalRepository.findOne({ const personal = await this.personalRepository.findOne({
where: { personal_id: assign.personal_id }, where: { personal_id: assign.personal_id },
@ -584,5 +677,10 @@ export class EvaluateResultController extends Controller {
await this.personalRepository.save(personal, { data: request }); await this.personalRepository.save(personal, { data: request });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
} }

View file

@ -1,22 +1,37 @@
import { Controller, Post, Route, Security, Tags, Body, Request, SuccessResponse, Response, Get, Query } from "tsoa" import {
import { AppDataSource } from "../database/data-source" Controller,
import HttpSuccess from "../interfaces/http-success" Post,
import HttpStatusCode from "../interfaces/http-status" Route,
import HttpError from "../interfaces/http-error" Security,
import { RequestWithUser } from "../middlewares/user" Tags,
import { setLogDataDiff } from "../interfaces/utils" Body,
import { Personal, PostPersonal } from "../entities/Personal" Request,
import permission from "../interfaces/permission" SuccessResponse,
import { Assign } from "../entities/Assign" Response,
import { Brackets } from "typeorm" 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") @Route("api/v1/probation/personal")
@Tags("Personal") @Tags("Personal")
@Security("bearerAuth") @Security("bearerAuth")
@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") @Response(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง"
)
export class PersonalController extends Controller { export class PersonalController extends Controller {
private personalRepository = AppDataSource.getRepository(Personal) private personalRepository = AppDataSource.getRepository(Personal);
private assignRepository = AppDataSource.getRepository(Assign) private assignRepository = AppDataSource.getRepository(Assign);
/** /**
* API * API
@ -25,63 +40,91 @@ export class PersonalController extends Controller {
* *
*/ */
@Post("add") @Post("add")
async AddPersonal(@Body() requestBody: PostPersonal, @Request() request: RequestWithUser) { async AddPersonal(
await new permission().PermissionCreate(request, "SYS_PROBATION") @Body() requestBody: PostPersonal,
@Request() request: RequestWithUser
) {
try {
await new permission().PermissionCreate(request, "SYS_PROBATION");
const checkPersonal: number = await this.personalRepository.count({ const checkPersonal: number = await this.personalRepository.count({
where: { personal_id: requestBody.id }, where: { personal_id: requestBody.id },
}) });
if (checkPersonal > 0) { if (checkPersonal > 0) {
throw new HttpError(HttpStatusCode.BAD_REQUEST, "ผู้ทดลองปฏิบัติหน้าที่ราชการนี้มีอยู่แล้ว") throw new HttpError(
HttpStatusCode.BAD_REQUEST,
"ผู้ทดลองปฏิบัติหน้าที่ราชการนี้มีอยู่แล้ว"
);
} }
let organization = await (requestBody.orgChild4Name ? requestBody.orgChild4Name + " " : "") let organization = await (requestBody.orgChild4Name
organization += await (requestBody.orgChild3Name ? requestBody.orgChild3Name + " " : "") ? requestBody.orgChild4Name + " "
organization += await (requestBody.orgChild2Name ? requestBody.orgChild2Name + " " : "") : "");
organization += await (requestBody.orgChild1Name ? requestBody.orgChild1Name + " " : "") organization += await (requestBody.orgChild3Name
organization += await (requestBody.orgRootName ? requestBody.orgRootName : "") ? 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()) const personalData = Object.assign(new Personal());
personalData.personal_id = requestBody.id personalData.personal_id = requestBody.id;
personalData.order_number = requestBody.order_number ? requestBody.order_number : "" personalData.order_number = requestBody.order_number
personalData.probation_status = 1 ? requestBody.order_number
personalData.createdUserId = request.user.sub : "";
personalData.createdFullName = request.user.name personalData.probation_status = 1;
personalData.updateUserId = request.user.sub personalData.createdUserId = request.user.sub;
personalData.updateFullName = request.user.name personalData.createdFullName = request.user.name;
personalData.updateUserId = request.user.sub;
personalData.updateFullName = request.user.name;
personalData.idcard = requestBody.idcard personalData.idcard = requestBody.idcard;
personalData.prefixName = requestBody.prefix personalData.prefixName = requestBody.prefix;
personalData.firstName = requestBody.firstName personalData.firstName = requestBody.firstName;
personalData.lastName = requestBody.lastName personalData.lastName = requestBody.lastName;
personalData.isProbation = requestBody.isProbation ? 1 : 0 personalData.isProbation = requestBody.isProbation ? 1 : 0;
personalData.positionLevelName = requestBody.posLevelName ? requestBody.posLevelName : "" personalData.positionLevelName = requestBody.posLevelName
personalData.positionName = requestBody.position ? requestBody.position : "" ? requestBody.posLevelName
personalData.positionLineName = requestBody.posLineName : "";
personalData.positionTypeName = requestBody.posTypeName personalData.positionName = requestBody.position
personalData.posNo = requestBody.posNo ? requestBody.posNo : "" ? requestBody.position
personalData.orgRootName = requestBody.orgRootName : "";
personalData.organization = organization 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.root = requestBody.root;
personalData.child1 = requestBody.child1 personalData.child1 = requestBody.child1;
personalData.child2 = requestBody.child2 personalData.child2 = requestBody.child2;
personalData.child3 = requestBody.child3 personalData.child3 = requestBody.child3;
personalData.child4 = requestBody.child4 personalData.child4 = requestBody.child4;
personalData.rootDna = requestBody.rootDna personalData.rootDna = requestBody.rootDna;
personalData.child1Dna = requestBody.child1Dna personalData.child1Dna = requestBody.child1Dna;
personalData.child2Dna = requestBody.child2Dna personalData.child2Dna = requestBody.child2Dna;
personalData.child3Dna = requestBody.child3Dna personalData.child3Dna = requestBody.child3Dna;
personalData.child4Dna = requestBody.child4Dna personalData.child4Dna = requestBody.child4Dna;
const before = null const before = null;
const personal = await this.personalRepository.save(personalData, { const personal = await this.personalRepository.save(personalData, {
data: request, data: request,
}) });
setLogDataDiff(request, { before, after: personal }) 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);
}
} }
/** /**
@ -91,79 +134,130 @@ export class PersonalController extends Controller {
* *
*/ */
@Get("list") @Get("list")
async ListPersonal(@Query() status: string = "", @Query() keyword: string = "", @Query("page") page: number = 1, @Query("pageSize") pageSize: number = 10, @Request() request: RequestWithUser) { async ListPersonal(
await new permission().PermissionList(request, "SYS_PROBATION") @Query() status: string = "",
const _data = await new permission().PermissionOrgList(request, "SYS_PROBATION") @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 = {} const conditions: any = {};
if (status) { if (status) {
conditions.probation_status = status conditions.probation_status = status;
} }
if (_data.root != undefined && _data.root != null && _data.root[0] != null) { if (
conditions.root = _data.root _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) { if (
conditions.child1 = _data.child1 _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) { if (
conditions.child2 = _data.child2 _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) { if (
conditions.child3 = _data.child3 _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) { if (
conditions.child4 = _data.child4 _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) const [lists, total] = await AppDataSource.getRepository(Personal)
.createQueryBuilder("personal") .createQueryBuilder("personal")
.where(conditions) .where(conditions)
.andWhere( .andWhere(
new Brackets(qb => { new Brackets((qb) => {
qb.orWhere(searchKeyword ? `CONCAT(prefixName, firstName," ",lastName) like '%${keyword}%'` : "1=1", { qb.orWhere(
searchKeyword
? `CONCAT(prefixName, firstName," ",lastName) like '%${keyword}%'`
: "1=1",
{
keyword: `%${searchKeyword}%`, keyword: `%${searchKeyword}%`,
}) }
qb.orWhere(searchKeyword ? `positionName like '%${keyword}%'` : "1=1", { );
qb.orWhere(
searchKeyword ? `positionName like '%${keyword}%'` : "1=1",
{
keyword: `%${searchKeyword}%`, keyword: `%${searchKeyword}%`,
}) }
qb.orWhere(searchKeyword ? `positionLevelName like '%${keyword}%'` : "1=1", { );
qb.orWhere(
searchKeyword ? `positionLevelName like '%${keyword}%'` : "1=1",
{
keyword: `%${searchKeyword}%`, keyword: `%${searchKeyword}%`,
}) }
qb.orWhere(searchKeyword ? `organization like '%${keyword}%'` : "1=1", { );
qb.orWhere(
searchKeyword ? `organization like '%${keyword}%'` : "1=1",
{
keyword: `%${searchKeyword}%`, keyword: `%${searchKeyword}%`,
}) }
qb.orWhere(searchKeyword ? `order_number like '%${keyword}%'` : "1=1", { );
qb.orWhere(
searchKeyword ? `order_number like '%${keyword}%'` : "1=1",
{
keyword: `%${searchKeyword}%`, keyword: `%${searchKeyword}%`,
}) }
);
}) })
) )
.orderBy("updatedAt", "DESC") .orderBy("updatedAt", "DESC")
.skip((page - 1) * pageSize) .skip((page - 1) * pageSize)
.take(pageSize) .take(pageSize)
.getManyAndCount() .getManyAndCount();
if (!lists) { if (!lists) {
throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "ไม่สามารถแสดงข้อมูลได้") throw new HttpError(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"ไม่สามารถแสดงข้อมูลได้"
);
} }
let result: any = [] let result: any = [];
for (let i = 0; i < lists.length; i++) { for (let i = 0; i < lists.length; i++) {
const probation_no = await this.assignRepository.count({ const probation_no = await this.assignRepository.count({
where: { personal_id: lists[i].personal_id }, where: { personal_id: lists[i].personal_id },
}) });
await result.push({ await result.push({
personal_id: lists[i].personal_id, personal_id: lists[i].personal_id,
ordering: i + 1, ordering: i + 1,
name: lists[i].prefixName + lists[i].firstName + " " + lists[i].lastName, name:
lists[i].prefixName + lists[i].firstName + " " + lists[i].lastName,
prefixName: lists[i].prefixName, prefixName: lists[i].prefixName,
firstName: lists[i].firstName, firstName: lists[i].firstName,
lastName: lists[i].lastName, lastName: lists[i].lastName,
@ -175,7 +269,7 @@ export class PersonalController extends Controller {
probation_no: probation_no, probation_no: probation_no,
order_number: lists[i].order_number, order_number: lists[i].order_number,
probation_status: lists[i].probation_status, probation_status: lists[i].probation_status,
}) });
} }
// await Promise.all( // await Promise.all(
// lists.map(async (item, index) => { // lists.map(async (item, index) => {
@ -204,7 +298,12 @@ export class PersonalController extends Controller {
// }), // }),
// ); // );
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);
}
} }
/** /**
@ -214,20 +313,29 @@ export class PersonalController extends Controller {
* *
*/ */
@Get("") @Get("")
async GetPersonal(@Request() request: RequestWithUser, @Query() personal_id: string) { async GetPersonal(
let _workflow = await new permission().Workflow(request, personal_id, "SYS_PROBATION") @Request() request: RequestWithUser,
if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION") @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({ const person = await this.personalRepository.findOne({
where: { personal_id: personal_id }, where: { personal_id: personal_id },
}) });
if (!person) { if (!person) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล") throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคล");
} }
const probation_no = await this.assignRepository.count({ const probation_no = await this.assignRepository.count({
where: { personal_id: person.personal_id }, where: { personal_id: person.personal_id },
}) });
const result = await { const result = await {
personal_id: person.personal_id, personal_id: person.personal_id,
@ -239,8 +347,13 @@ export class PersonalController extends Controller {
probation_no: probation_no, probation_no: probation_no,
order_number: person.order_number, order_number: person.order_number,
probation_status: person.probation_status, 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);
}
} }
} }

View file

@ -70,6 +70,7 @@ export class ReportController extends Controller {
@Query() assign_id: string, @Query() assign_id: string,
@Query() evaluate_no: number = 1 @Query() evaluate_no: number = 1
) { ) {
try {
const evaluate = await this.evaluateChairmanRepository.findOne({ const evaluate = await this.evaluateChairmanRepository.findOne({
where: { assign_id, no: evaluate_no.toString() }, where: { assign_id, no: evaluate_no.toString() },
}); });
@ -125,6 +126,11 @@ export class ReportController extends Controller {
}; };
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);
}
} }
/** /**
@ -135,6 +141,7 @@ export class ReportController extends Controller {
*/ */
@Get("pass") @Get("pass")
async GetPass() { async GetPass() {
try {
const lists = await this.personalRepository.find({ const lists = await this.personalRepository.find({
where: { probation_status: 2 }, where: { probation_status: 2 },
}); });
@ -159,6 +166,11 @@ export class ReportController extends Controller {
); );
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);
}
} }
/** /**
@ -169,6 +181,7 @@ export class ReportController extends Controller {
*/ */
@Get("not-pass") @Get("not-pass")
async GetDataNotPass() { async GetDataNotPass() {
try {
const lists = await this.personalRepository.find({ const lists = await this.personalRepository.find({
where: { probation_status: 3 }, where: { probation_status: 3 },
}); });
@ -193,6 +206,11 @@ export class ReportController extends Controller {
); );
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);
}
} }
/** /**
@ -204,12 +222,18 @@ export class ReportController extends Controller {
@Get("expand") @Get("expand")
async GetDataExpand() { async GetDataExpand() {
try {
const data = await this.personalRepository.find({ const data = await this.personalRepository.find({
select: ["personal_id"], select: ["personal_id"],
where: { probation_status: 7 }, 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,6 +248,7 @@ export class ReportController extends Controller {
@Body() requestBody: { command_no: string }, @Body() requestBody: { command_no: string },
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
const personal = await this.personalRepository.findOne({ const personal = await this.personalRepository.findOne({
where: { personal_id }, where: { personal_id },
}); });
@ -261,6 +286,11 @@ export class ReportController extends Controller {
}); });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -275,6 +305,7 @@ export class ReportController extends Controller {
@Body() reqBody: { status: number }, @Body() reqBody: { status: number },
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
const personal = await this.personalRepository.findOne({ const personal = await this.personalRepository.findOne({
where: { personal_id }, where: { personal_id },
}); });
@ -292,6 +323,11 @@ export class ReportController extends Controller {
setLogDataDiff(request, { before, after: personal }); 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);
}
} }
/** /**
@ -302,6 +338,7 @@ export class ReportController extends Controller {
*/ */
@Get("form-record") @Get("form-record")
async GetDataFormRecord(@Query() id: string) { async GetDataFormRecord(@Query() id: string) {
try {
const evaluate = await this.evaluateAssessorRepository.findOne({ const evaluate = await this.evaluateAssessorRepository.findOne({
where: { id }, where: { id },
}); });
@ -356,7 +393,10 @@ export class ReportController extends Controller {
const outputData = await this.assignOutputRepository.findOne({ const outputData = await this.assignOutputRepository.findOne({
select: ["output_desc"], select: ["output_desc"],
where: { id: Number(element.output_id), assign_id: element.assign_id }, where: {
id: Number(element.output_id),
assign_id: element.assign_id,
},
}); });
await evaluate_expect_level.push({ await evaluate_expect_level.push({
title: outputData?.output_desc ?? "-", title: outputData?.output_desc ?? "-",
@ -604,6 +644,11 @@ export class ReportController extends Controller {
evaluate: evaluateData, evaluate: evaluateData,
}; };
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);
}
} }
/** /**
@ -617,6 +662,7 @@ export class ReportController extends Controller {
@Query() id: string, @Query() id: string,
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
const evaluate = await this.evaluateCommanderRepository.findOne({ const evaluate = await this.evaluateCommanderRepository.findOne({
where: { id }, where: { id },
}); });
@ -872,6 +918,11 @@ export class ReportController extends Controller {
assign, assign,
evaluate: evaluateData, evaluate: evaluateData,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -885,6 +936,7 @@ export class ReportController extends Controller {
@Query() id: string, @Query() id: string,
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
try {
const evaluate = await this.evaluateChairmanRepository.findOne({ const evaluate = await this.evaluateChairmanRepository.findOne({
where: { id }, where: { id },
}); });
@ -1152,11 +1204,13 @@ export class ReportController extends Controller {
}) })
); );
const mentorData = await (director.find((x) => x.role == "mentor") ?? null); const mentorData = await (director.find((x) => x.role == "mentor") ??
null);
const mentor = mentorData != null ? mentorData : null; const mentor = mentorData != null ? mentorData : null;
const commanderData = await (director.find((x) => x.role == "commander") ?? const commanderData = await (director.find(
null); (x) => x.role == "commander"
) ?? null);
const commander = commanderData != null ? commanderData : null; const commander = commanderData != null ? commanderData : null;
const chairmanData = await (director.find((x) => x.role == "chairman") ?? const chairmanData = await (director.find((x) => x.role == "chairman") ??
@ -1171,6 +1225,11 @@ export class ReportController extends Controller {
assign, assign,
evaluate: evaluateData, evaluate: evaluateData,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
@Post("command11/officer/report/excecute") @Post("command11/officer/report/excecute")
@ -1195,8 +1254,11 @@ export class ReportController extends Controller {
}[]; }[];
} }
) { ) {
await new CallAPI() try {
.PostData(request, "/org/command/excexute/salary-probation", { await new CallAPI().PostData(
request,
"/org/command/excexute/salary-probation",
{
data: body.refIds.map((v) => ({ data: body.refIds.map((v) => ({
profileId: v.refId, profileId: v.refId,
commandId: v.commandId, commandId: v.commandId,
@ -1212,8 +1274,9 @@ export class ReportController extends Controller {
commandName: v.commandName, commandName: v.commandName,
remark: v.remark, remark: v.remark,
})), })),
}) }
.then(async (res) => { );
const lists = await this.personalRepository.find({ const lists = await this.personalRepository.find({
where: { where: {
probation_status: 8, probation_status: 8,
@ -1226,10 +1289,15 @@ export class ReportController extends Controller {
await this.personalRepository.save(list); await this.personalRepository.save(list);
}) })
); );
})
.catch(() => {});
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") @Post("command11/officer/report")
public async command11( public async command11(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@ -1238,6 +1306,7 @@ export class ReportController extends Controller {
refIds: string[]; refIds: string[];
} }
) { ) {
try {
const lists = await this.personalRepository.find({ const lists = await this.personalRepository.find({
where: { probation_status: 2, personal_id: In(body.refIds) }, where: { probation_status: 2, personal_id: In(body.refIds) },
}); });
@ -1249,7 +1318,13 @@ export class ReportController extends Controller {
); );
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") @Post("command11/officer/report/delete")
public async command11Delete( public async command11Delete(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@ -1258,6 +1333,7 @@ export class ReportController extends Controller {
refIds: string[]; refIds: string[];
} }
) { ) {
try {
const lists = await this.personalRepository.find({ const lists = await this.personalRepository.find({
where: { probation_status: 8, personal_id: In(body.refIds) }, where: { probation_status: 8, personal_id: In(body.refIds) },
}); });
@ -1269,6 +1345,11 @@ export class ReportController extends Controller {
); );
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") @Post("command12/officer/report/excecute")
@ -1293,8 +1374,11 @@ export class ReportController extends Controller {
}[]; }[];
} }
) { ) {
await new CallAPI() try {
.PostData(request, "/org/command/excexute/salary-probation-leave", { await new CallAPI().PostData(
request,
"/org/command/excexute/salary-probation-leave",
{
data: body.refIds.map((v) => ({ data: body.refIds.map((v) => ({
profileId: v.refId, profileId: v.refId,
commandId: v.commandId, commandId: v.commandId,
@ -1311,8 +1395,9 @@ export class ReportController extends Controller {
commandName: v.commandName, commandName: v.commandName,
remark: v.remark, remark: v.remark,
})), })),
}) }
.then(async (res) => { );
const lists = await this.personalRepository.find({ const lists = await this.personalRepository.find({
where: { where: {
probation_status: 8, probation_status: 8,
@ -1325,10 +1410,15 @@ export class ReportController extends Controller {
await this.personalRepository.save(list); await this.personalRepository.save(list);
}) })
); );
})
.catch(() => {});
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") @Post("command12/officer/report")
public async command12( public async command12(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@ -1337,6 +1427,7 @@ export class ReportController extends Controller {
refIds: string[]; refIds: string[];
} }
) { ) {
try {
const lists = await this.personalRepository.find({ const lists = await this.personalRepository.find({
where: { probation_status: 3, personal_id: In(body.refIds) }, where: { probation_status: 3, personal_id: In(body.refIds) },
}); });
@ -1347,7 +1438,13 @@ export class ReportController extends Controller {
}) })
); );
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/delete") @Post("command12/officer/report/delete")
public async command12Delete( public async command12Delete(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@ -1356,6 +1453,7 @@ export class ReportController extends Controller {
refIds: string[]; refIds: string[];
} }
) { ) {
try {
const lists = await this.personalRepository.find({ const lists = await this.personalRepository.find({
where: { probation_status: 8, personal_id: In(body.refIds) }, where: { probation_status: 8, personal_id: In(body.refIds) },
}); });
@ -1366,6 +1464,11 @@ export class ReportController extends Controller {
}) })
); );
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("command10/officer/report/excecute") @Post("command10/officer/report/excecute")
@ -1395,6 +1498,7 @@ export class ReportController extends Controller {
}[]; }[];
} }
) { ) {
try {
const lists = await this.appointRepository.find({ const lists = await this.appointRepository.find({
where: { id: In(body.refIds.map((x) => x.refId)) }, where: { id: In(body.refIds.map((x) => x.refId)) },
}); });
@ -1406,7 +1510,13 @@ export class ReportController extends Controller {
}) })
); );
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("command10/officer/report") @Post("command10/officer/report")
public async command10( public async command10(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@ -1415,6 +1525,7 @@ export class ReportController extends Controller {
refIds: string[]; refIds: string[];
} }
) { ) {
try {
const lists = await this.appointRepository.find({ const lists = await this.appointRepository.find({
where: { id: In(body.refIds) }, where: { id: In(body.refIds) },
}); });
@ -1425,7 +1536,13 @@ export class ReportController extends Controller {
}) })
); );
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("command10/officer/report/delete") @Post("command10/officer/report/delete")
public async command10Delete( public async command10Delete(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@ -1434,6 +1551,7 @@ export class ReportController extends Controller {
refIds: string[]; refIds: string[];
} }
) { ) {
try {
const lists = await this.appointRepository.find({ const lists = await this.appointRepository.find({
where: { id: In(body.refIds) }, where: { id: In(body.refIds) },
}); });
@ -1444,6 +1562,11 @@ export class ReportController extends Controller {
}) })
); );
return new HttpSuccess(); 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}") @Get("command10/appoints/{refId}")
@ -1451,6 +1574,7 @@ export class ReportController extends Controller {
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@Path() refId: string @Path() refId: string
) { ) {
try {
const lists = await this.AppointDirectorRepository.find({ const lists = await this.AppointDirectorRepository.find({
where: { appointId: refId }, where: { appointId: refId },
order: { createdAt: "ASC" }, order: { createdAt: "ASC" },
@ -1468,6 +1592,11 @@ export class ReportController extends Controller {
}) })
); );
return new HttpSuccess(directors); return new HttpSuccess(directors);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
@Get("report1") @Get("report1")
@ -1490,7 +1619,7 @@ export class ReportController extends Controller {
status7: number; status7: number;
}; };
} }
try {
const rootNode = await new CallAPI() const rootNode = await new CallAPI()
.PostData(req, "/org/find/node-all", { nodeId: nodeId, node: node }) .PostData(req, "/org/find/node-all", { nodeId: nodeId, node: node })
.catch((error) => { .catch((error) => {
@ -1552,7 +1681,9 @@ export class ReportController extends Controller {
} }
if (status >= 1 && status <= 7) { if (status >= 1 && status <= 7) {
(resultTrue[rootDnaId] as { [key: string]: any })[`status${status}`]++; (resultTrue[rootDnaId] as { [key: string]: any })[
`status${status}`
]++;
} }
}); });
listsRootFalse.forEach((item) => { listsRootFalse.forEach((item) => {
@ -1574,7 +1705,9 @@ export class ReportController extends Controller {
} }
if (status >= 1 && status <= 7) { if (status >= 1 && status <= 7) {
(resultFalse[rootDnaId] as { [key: string]: any })[`status${status}`]++; (resultFalse[rootDnaId] as { [key: string]: any })[
`status${status}`
]++;
} }
}); });
const resultTruePass = Object.values(resultTrue).reduce( const resultTruePass = Object.values(resultTrue).reduce(
@ -1628,24 +1761,60 @@ export class ReportController extends Controller {
0 0
); );
const sumPass = const sumPass =
Object.values(resultTrue).reduce((sum, { status2 }) => sum + status2, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status2 }) => sum + status2, 0); (sum, { status2 }) => sum + status2,
0
) +
Object.values(resultFalse).reduce(
(sum, { status2 }) => sum + status2,
0
);
const sumExtand = const sumExtand =
Object.values(resultTrue).reduce((sum, { status7 }) => sum + status7, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status7 }) => sum + status7, 0); (sum, { status7 }) => sum + status7,
0
) +
Object.values(resultFalse).reduce(
(sum, { status7 }) => sum + status7,
0
);
const sumSuspension = "-"; const sumSuspension = "-";
const sumChangePos = const sumChangePos =
Object.values(resultTrue).reduce((sum, { status4 }) => sum + status4, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status4 }) => sum + status4, 0); (sum, { status4 }) => sum + status4,
0
) +
Object.values(resultFalse).reduce(
(sum, { status4 }) => sum + status4,
0
);
const sumResign = const sumResign =
Object.values(resultTrue).reduce((sum, { status5 }) => sum + status5, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status5 }) => sum + status5, 0); (sum, { status5 }) => sum + status5,
0
) +
Object.values(resultFalse).reduce(
(sum, { status5 }) => sum + status5,
0
);
const sumDeceased = const sumDeceased =
Object.values(resultTrue).reduce((sum, { status6 }) => sum + status6, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status6 }) => sum + status6, 0); (sum, { status6 }) => sum + status6,
0
) +
Object.values(resultFalse).reduce(
(sum, { status6 }) => sum + status6,
0
);
const sumNotPass = const sumNotPass =
Object.values(resultTrue).reduce((sum, { status3 }) => sum + status3, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status3 }) => sum + status3, 0); (sum, { status3 }) => sum + status3,
0
) +
Object.values(resultFalse).reduce(
(sum, { status3 }) => sum + status3,
0
);
const sumResultTrue = Object.values(resultTrue).reduce( const sumResultTrue = Object.values(resultTrue).reduce(
(total, { status2, status7, status4, status5, status6, status3 }) => { (total, { status2, status7, status4, status5, status6, status3 }) => {
return ( return (
@ -1663,7 +1832,12 @@ export class ReportController extends Controller {
0 0
); );
const sumAll = const sumAll =
sumPass + sumExtand + sumChangePos + sumResign + sumDeceased + sumNotPass; sumPass +
sumExtand +
sumChangePos +
sumResign +
sumDeceased +
sumNotPass;
const nowDate = Extension.ToThaiNumber( const nowDate = Extension.ToThaiNumber(
Extension.ToThaiShortDate(new Date()) Extension.ToThaiShortDate(new Date())
); );
@ -1708,7 +1882,8 @@ export class ReportController extends Controller {
resultTrueDeceased: resultTrueDeceased.toString(), resultTrueDeceased: resultTrueDeceased.toString(),
resultTrueNotPass: resultTrueNotPass.toString(), resultTrueNotPass: resultTrueNotPass.toString(),
topic2: "หน่วยงานระดับสำนักงานเขต", topic2: "หน่วยงานระดับสำนักงานเขต",
resultFalseProbation: Object.keys(resultFalse).map((rootDnaId, index) => { resultFalseProbation: Object.keys(resultFalse).map(
(rootDnaId, index) => {
const { const {
status2, status2,
status7, status7,
@ -1718,7 +1893,8 @@ export class ReportController extends Controller {
status3, status3,
rootName, rootName,
} = resultFalse[rootDnaId]; } = resultFalse[rootDnaId];
const sum = status2 + status7 + status4 + status5 + status6 + status3; const sum =
status2 + status7 + status4 + status5 + status6 + status3;
return { return {
rowNo: (index + 1).toString(), rowNo: (index + 1).toString(),
rootName: rootName.toString(), rootName: rootName.toString(),
@ -1731,7 +1907,8 @@ export class ReportController extends Controller {
notPass: status3.toString(), notPass: status3.toString(),
total: sum.toString(), total: sum.toString(),
}; };
}), }
),
resultFalsePass: resultFalsePass.toString(), resultFalsePass: resultFalsePass.toString(),
resultFalseExtand: resultFalseExtand.toString(), resultFalseExtand: resultFalseExtand.toString(),
resultFalseSuspension: "-", resultFalseSuspension: "-",
@ -1755,6 +1932,11 @@ export class ReportController extends Controller {
reportName: "xlsx-report", reportName: "xlsx-report",
data: formattedData, data: formattedData,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
@Get("report2") @Get("report2")
@ -1765,6 +1947,7 @@ export class ReportController extends Controller {
@Query("startDate") startDate?: Date, @Query("startDate") startDate?: Date,
@Query("endDate") endDate?: Date @Query("endDate") endDate?: Date
) { ) {
try {
let personal = null; let personal = null;
let result: Array<any> = []; let result: Array<any> = [];
switch (node) { switch (node) {
@ -1951,11 +2134,10 @@ export class ReportController extends Controller {
}) })
.catch((errr) => {}); .catch((errr) => {});
const evaluateComman = await this.evaluateCommanderRepository.findOne( const evaluateComman =
{ await this.evaluateCommanderRepository.findOne({
where: { assign_id: assign.id ?? "" }, where: { assign_id: assign.id ?? "" },
} });
);
return { return {
no: Extension.ToThaiNumber(x.no.toString()), no: Extension.ToThaiNumber(x.no.toString()),
@ -1992,7 +2174,9 @@ export class ReportController extends Controller {
orientation: orientation:
evaluateComman && evaluateComman?.orientation == 1 ? "☑" : "☐", evaluateComman && evaluateComman?.orientation == 1 ? "☑" : "☐",
learning: learning:
evaluateComman && evaluateComman?.self_learning == 1 ? "☑" : "☐", evaluateComman && evaluateComman?.self_learning == 1
? "☑"
: "☐",
seminar: seminar:
evaluateComman && evaluateComman?.training_seminar == 1 evaluateComman && evaluateComman?.training_seminar == 1
? "☑" ? "☑"
@ -2015,6 +2199,11 @@ export class ReportController extends Controller {
data: result, data: result,
}, },
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
@Get("report3") @Get("report3")
@ -2038,6 +2227,7 @@ export class ReportController extends Controller {
}; };
} }
try {
const rootNode = await new CallAPI() const rootNode = await new CallAPI()
.PostData(req, "/org/find/node-all", { nodeId: nodeId, node: node }) .PostData(req, "/org/find/node-all", { nodeId: nodeId, node: node })
.catch((error) => { .catch((error) => {
@ -2099,7 +2289,9 @@ export class ReportController extends Controller {
} }
if (status >= 1 && status <= 7) { if (status >= 1 && status <= 7) {
(resultTrue[rootDnaId] as { [key: string]: any })[`status${status}`]++; (resultTrue[rootDnaId] as { [key: string]: any })[
`status${status}`
]++;
} }
}); });
listsRootFalse.forEach((item) => { listsRootFalse.forEach((item) => {
@ -2121,7 +2313,9 @@ export class ReportController extends Controller {
} }
if (status >= 1 && status <= 7) { if (status >= 1 && status <= 7) {
(resultFalse[rootDnaId] as { [key: string]: any })[`status${status}`]++; (resultFalse[rootDnaId] as { [key: string]: any })[
`status${status}`
]++;
} }
}); });
const resultTruePass = Object.values(resultTrue).reduce( const resultTruePass = Object.values(resultTrue).reduce(
@ -2175,24 +2369,60 @@ export class ReportController extends Controller {
0 0
); );
const sumPass = const sumPass =
Object.values(resultTrue).reduce((sum, { status2 }) => sum + status2, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status2 }) => sum + status2, 0); (sum, { status2 }) => sum + status2,
0
) +
Object.values(resultFalse).reduce(
(sum, { status2 }) => sum + status2,
0
);
const sumExtand = const sumExtand =
Object.values(resultTrue).reduce((sum, { status7 }) => sum + status7, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status7 }) => sum + status7, 0); (sum, { status7 }) => sum + status7,
0
) +
Object.values(resultFalse).reduce(
(sum, { status7 }) => sum + status7,
0
);
const sumSuspension = "-"; const sumSuspension = "-";
const sumChangePos = const sumChangePos =
Object.values(resultTrue).reduce((sum, { status4 }) => sum + status4, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status4 }) => sum + status4, 0); (sum, { status4 }) => sum + status4,
0
) +
Object.values(resultFalse).reduce(
(sum, { status4 }) => sum + status4,
0
);
const sumResign = const sumResign =
Object.values(resultTrue).reduce((sum, { status5 }) => sum + status5, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status5 }) => sum + status5, 0); (sum, { status5 }) => sum + status5,
0
) +
Object.values(resultFalse).reduce(
(sum, { status5 }) => sum + status5,
0
);
const sumDeceased = const sumDeceased =
Object.values(resultTrue).reduce((sum, { status6 }) => sum + status6, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status6 }) => sum + status6, 0); (sum, { status6 }) => sum + status6,
0
) +
Object.values(resultFalse).reduce(
(sum, { status6 }) => sum + status6,
0
);
const sumNotPass = const sumNotPass =
Object.values(resultTrue).reduce((sum, { status3 }) => sum + status3, 0) + Object.values(resultTrue).reduce(
Object.values(resultFalse).reduce((sum, { status3 }) => sum + status3, 0); (sum, { status3 }) => sum + status3,
0
) +
Object.values(resultFalse).reduce(
(sum, { status3 }) => sum + status3,
0
);
const sumResultTrue = Object.values(resultTrue).reduce( const sumResultTrue = Object.values(resultTrue).reduce(
(total, { status2, status7, status4, status5, status6, status3 }) => { (total, { status2, status7, status4, status5, status6, status3 }) => {
return ( return (
@ -2210,7 +2440,12 @@ export class ReportController extends Controller {
0 0
); );
const sumAll = const sumAll =
sumPass + sumExtand + sumChangePos + sumResign + sumDeceased + sumNotPass; sumPass +
sumExtand +
sumChangePos +
sumResign +
sumDeceased +
sumNotPass;
const nowDate = Extension.ToThaiNumber( const nowDate = Extension.ToThaiNumber(
Extension.ToThaiShortDate(new Date()) Extension.ToThaiShortDate(new Date())
); );
@ -2256,7 +2491,8 @@ export class ReportController extends Controller {
resultTrueDeceased: resultTrueDeceased.toString(), resultTrueDeceased: resultTrueDeceased.toString(),
resultTrueNotPass: resultTrueNotPass.toString(), resultTrueNotPass: resultTrueNotPass.toString(),
topic2: "หน่วยงานระดับสำนักงานเขต", topic2: "หน่วยงานระดับสำนักงานเขต",
resultFalseProbation: Object.keys(resultFalse).map((rootDnaId, index) => { resultFalseProbation: Object.keys(resultFalse).map(
(rootDnaId, index) => {
const { const {
status2, status2,
status7, status7,
@ -2266,7 +2502,8 @@ export class ReportController extends Controller {
status3, status3,
rootName, rootName,
} = resultFalse[rootDnaId]; } = resultFalse[rootDnaId];
const sum = status2 + status7 + status4 + status5 + status6 + status3; const sum =
status2 + status7 + status4 + status5 + status6 + status3;
return { return {
rowNo: (index + 1).toString(), rowNo: (index + 1).toString(),
rootName: rootName.toString(), rootName: rootName.toString(),
@ -2279,7 +2516,8 @@ export class ReportController extends Controller {
notPass: status3.toString(), notPass: status3.toString(),
total: sum.toString(), total: sum.toString(),
}; };
}), }
),
resultFalsePass: resultFalsePass.toString(), resultFalsePass: resultFalsePass.toString(),
resultFalseExtand: resultFalseExtand.toString(), resultFalseExtand: resultFalseExtand.toString(),
resultFalseSuspension: "-", resultFalseSuspension: "-",
@ -2303,5 +2541,10 @@ export class ReportController extends Controller {
reportName: "xlsx-report", reportName: "xlsx-report",
data: formattedData, data: formattedData,
}); });
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
} }

View file

@ -1,23 +1,38 @@
import { Controller, Route, Security, Tags, Request, SuccessResponse, Response, Get, Post, Body, Query } from "tsoa" import {
import HttpSuccess from "../interfaces/http-success" Controller,
import HttpStatusCode from "../interfaces/http-status" Route,
import HttpError from "../interfaces/http-error" Security,
import { RequestWithUser } from "../middlewares/user" Tags,
import { setLogDataDiff } from "../interfaces/utils" Request,
import { Survey } from "../entities/Survey" SuccessResponse,
import { Assign } from "../entities/Assign" Response,
import { AppDataSource } from "../database/data-source" Get,
import CallAPI from "../interfaces/call-api" Post,
import permission from "../interfaces/permission" Body,
import { Brackets } from "typeorm" 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") @Route("api/v1/probation/survey")
@Tags("Survey") @Tags("Survey")
@Security("bearerAuth") @Security("bearerAuth")
@Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง") @Response(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง"
)
export class SurveyController extends Controller { export class SurveyController extends Controller {
private surveyRepository = AppDataSource.getRepository(Survey) private surveyRepository = AppDataSource.getRepository(Survey);
private assignRepository = AppDataSource.getRepository(Assign) private assignRepository = AppDataSource.getRepository(Assign);
/** /**
* API * API
@ -27,26 +42,36 @@ export class SurveyController extends Controller {
*/ */
@Get("") @Get("")
async GetSurvey(@Request() request: RequestWithUser) { async GetSurvey(@Request() request: RequestWithUser) {
const personalId = await new CallAPI().GetData(request, "/org/profile/keycloak").catch(error => { try {
console.error("Error calling API:", error) const personalId = await new CallAPI().GetData(
}) request,
"/org/profile/keycloak"
);
const dataAssign = await this.assignRepository.findOne({ const dataAssign = await this.assignRepository.findOne({
select: ["id"], select: ["id"],
where: { personal_id: personalId }, where: { personal_id: personalId },
order: { date_start: "DESC" }, order: { date_start: "DESC" },
}) });
if (!dataAssign) { if (!dataAssign) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบผลการประเมินการทดลองปฏิบัติหน้าที่ราชการนี้") throw new HttpError(
HttpStatusCode.NOT_FOUND,
"ไม่พบผลการประเมินการทดลองปฏิบัติหน้าที่ราชการนี้"
);
} }
const assign_id = dataAssign.id const assign_id = dataAssign.id;
const data = await this.surveyRepository.findOne({ const data = await this.surveyRepository.findOne({
where: { where: {
assign_id, assign_id,
}, },
}) });
return new HttpSuccess({ data: data, assignId: 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);
}
} }
/** /**
@ -56,23 +81,34 @@ export class SurveyController extends Controller {
* *
*/ */
@Post("") @Post("")
async PostSurvey(@Query() assign_id: string, @Body() requestBody: any, @Request() request: RequestWithUser) { async PostSurvey(
const personalId = await new CallAPI().GetData(request, "/org/profile/keycloak").catch(error => { @Query() assign_id: string,
console.error("Error calling API:", error) @Body() requestBody: any,
}) @Request() request: RequestWithUser
) {
try {
const personalId = await new CallAPI().GetData(
request,
"/org/profile/keycloak"
);
const before = null const before = null;
const data = await { const data = await {
...requestBody, ...requestBody,
personal_id: personalId, personal_id: personalId,
assign_id, assign_id,
createdUserId: request.user.sub, createdUserId: request.user.sub,
updateUserId: request.user.sub, updateUserId: request.user.sub,
} };
await this.surveyRepository.save(data, { data: request }) await this.surveyRepository.save(data, { data: request });
setLogDataDiff(request, { before, after: data }) 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);
}
} }
/** /**
@ -89,32 +125,44 @@ export class SurveyController extends Controller {
@Query("pageSize") pageSize: number = 10, @Query("pageSize") pageSize: number = 10,
@Request() request: RequestWithUser @Request() request: RequestWithUser
) { ) {
// await new permission().PermissionUpdate(request, "SYS_PROBATION"); try {
const start = new Date("01-01-" + year) const start = new Date("01-01-" + year);
const end = new Date("12-31-" + 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) const [lists, total] = await AppDataSource.getRepository(Survey)
.createQueryBuilder("survey") .createQueryBuilder("survey")
.leftJoinAndSelect("survey.personal", "personal") .leftJoinAndSelect("survey.personal", "personal")
.where(`survey.createdAt BETWEEN '${start.toISOString()}' AND '${end.toISOString()}'`) .where(
`survey.createdAt BETWEEN '${start.toISOString()}' AND '${end.toISOString()}'`
)
.andWhere( .andWhere(
new Brackets(qb => { new Brackets((qb) => {
qb.orWhere(searchKeyword ? `CONCAT(personal.prefixName, personal.firstName," ",personal.lastName) like '%${keyword}%'` : "1=1", { qb.orWhere(
searchKeyword
? `CONCAT(personal.prefixName, personal.firstName," ",personal.lastName) like '%${keyword}%'`
: "1=1",
{
keyword: `%${searchKeyword}%`, keyword: `%${searchKeyword}%`,
}) }
qb.orWhere(searchKeyword ? `CONCAT(personal.positionName, personal.positionLevelName) like '%${keyword}%'` : "1=1", { );
qb.orWhere(
searchKeyword
? `CONCAT(personal.positionName, personal.positionLevelName) like '%${keyword}%'`
: "1=1",
{
keyword: `%${searchKeyword}%`, keyword: `%${searchKeyword}%`,
}) }
);
}) })
) )
.orderBy("survey.createdAt", "DESC") .orderBy("survey.createdAt", "DESC")
.skip((page - 1) * pageSize) .skip((page - 1) * pageSize)
.take(pageSize) .take(pageSize)
.getManyAndCount() .getManyAndCount();
const data = lists.map(item => { const data = lists.map((item) => {
return { return {
createdAt: item.createdAt, createdAt: item.createdAt,
personal_id: item.personal_id, personal_id: item.personal_id,
@ -122,11 +170,21 @@ export class SurveyController extends Controller {
answer1: item.answer1, answer1: item.answer1,
answer2: item.answer2, answer2: item.answer2,
answer3: item.answer3, answer3: item.answer3,
fullname: item.personal ? `${item.personal.prefixName}${item.personal.firstName} ${item.personal.lastName}` : "", fullname: item.personal
position: item.personal ? `${item.personal.positionName}${item.personal.positionLevelName}` : "", ? `${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");
} }
} }