Merge branch 'develop'

This commit is contained in:
Warunee Tamkoo 2025-03-15 19:14:56 +07:00
commit bc2b1ca42f
7 changed files with 1460 additions and 1174 deletions

View file

@ -46,36 +46,45 @@ export class DirectorController {
@Query("pageSize") pageSize: number = 10, @Query("pageSize") pageSize: number = 10,
@Query("keyword") keyword?: string, @Query("keyword") keyword?: string,
) { ) {
await new permission().PermissionList(request, "SYS_EVA_INFO"); try {
const directors = await AppDataSource.getRepository(Director) await new permission().PermissionList(request, "SYS_EVA_INFO");
.createQueryBuilder("director") const directors = await AppDataSource.getRepository(Director)
.andWhere( .createQueryBuilder("director")
new Brackets((qb) => { .andWhere(
qb.where( new Brackets((qb) => {
keyword != null && keyword != "" qb.where(
? "CONCAT(director.prefix, director.firstName, ' ', director.lastName) LIKE :keyword" keyword != null && keyword != ""
: "1=1", ? "CONCAT(director.prefix, director.firstName, ' ', director.lastName) LIKE :keyword"
{ : "1=1",
keyword: `%${keyword}%`, {
}, keyword: `%${keyword}%`,
) },
.orWhere(keyword != null && keyword != "" ? "director.position LIKE :keyword" : "1=1", { )
keyword: `%${keyword}%`, .orWhere(
}) keyword != null && keyword != "" ? "director.position LIKE :keyword" : "1=1",
.orWhere(keyword != null && keyword != "" ? "director.email LIKE :keyword" : "1=1", { {
keyword: `%${keyword}%`, keyword: `%${keyword}%`,
}) },
.orWhere(keyword != null && keyword != "" ? "director.phone LIKE :keyword" : "1=1", { )
keyword: `%${keyword}%`, .orWhere(keyword != null && keyword != "" ? "director.email LIKE :keyword" : "1=1", {
}); keyword: `%${keyword}%`,
}), })
) .orWhere(keyword != null && keyword != "" ? "director.phone LIKE :keyword" : "1=1", {
.orderBy("director.createdAt", "DESC") keyword: `%${keyword}%`,
.skip((page - 1) * pageSize) });
.take(pageSize) }),
.getMany(); )
.orderBy("director.createdAt", "DESC")
.skip((page - 1) * pageSize)
.take(pageSize)
.getMany();
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("admin") @Get("admin")
@ -85,34 +94,43 @@ export class DirectorController {
@Query("pageSize") pageSize: number = 10, @Query("pageSize") pageSize: number = 10,
@Query("keyword") keyword?: string, @Query("keyword") keyword?: string,
) { ) {
const directors = await AppDataSource.getRepository(Director) try {
.createQueryBuilder("director") const directors = await AppDataSource.getRepository(Director)
.andWhere( .createQueryBuilder("director")
new Brackets((qb) => { .andWhere(
qb.where( new Brackets((qb) => {
keyword != null && keyword != "" qb.where(
? "CONCAT(director.prefix, director.firstName, ' ', director.lastName) LIKE :keyword" keyword != null && keyword != ""
: "1=1", ? "CONCAT(director.prefix, director.firstName, ' ', director.lastName) LIKE :keyword"
{ : "1=1",
keyword: `%${keyword}%`, {
}, keyword: `%${keyword}%`,
) },
.orWhere(keyword != null && keyword != "" ? "director.position LIKE :keyword" : "1=1", { )
keyword: `%${keyword}%`, .orWhere(
}) keyword != null && keyword != "" ? "director.position LIKE :keyword" : "1=1",
.orWhere(keyword != null && keyword != "" ? "director.email LIKE :keyword" : "1=1", { {
keyword: `%${keyword}%`, keyword: `%${keyword}%`,
}) },
.orWhere(keyword != null && keyword != "" ? "director.phone LIKE :keyword" : "1=1", { )
keyword: `%${keyword}%`, .orWhere(keyword != null && keyword != "" ? "director.email LIKE :keyword" : "1=1", {
}); keyword: `%${keyword}%`,
}), })
) .orWhere(keyword != null && keyword != "" ? "director.phone LIKE :keyword" : "1=1", {
.orderBy("director.createdAt", "DESC") keyword: `%${keyword}%`,
.skip((page - 1) * pageSize) });
.take(pageSize) }),
.getMany(); )
return new HttpSuccess(directors); .orderBy("director.createdAt", "DESC")
.skip((page - 1) * pageSize)
.take(pageSize)
.getMany();
return new HttpSuccess(directors);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -123,13 +141,19 @@ export class DirectorController {
*/ */
@Get("{id}") @Get("{id}")
async one(@Path() id: string, @Request() request: RequestWithUser) { async one(@Path() id: string, @Request() request: RequestWithUser) {
let _workflow = await new permission().Workflow(request, id, "SYS_EVA_INFO"); try {
if (_workflow == false) await new permission().PermissionGet(request, "SYS_EVA_INFO"); let _workflow = await new permission().Workflow(request, id, "SYS_EVA_INFO");
const director = await this.directorRepository.findOne({ where: { id } }); if (_workflow == false) await new permission().PermissionGet(request, "SYS_EVA_INFO");
if (!director) { const director = await this.directorRepository.findOne({ where: { id } });
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found."); if (!director) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
}
return new HttpSuccess(director);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
return new HttpSuccess(director);
} }
/** /**
@ -140,27 +164,33 @@ export class DirectorController {
*/ */
@Post() @Post()
async save(@Body() requestBody: CreateDirector, @Request() request: RequestWithUser) { async save(@Body() requestBody: CreateDirector, @Request() request: RequestWithUser) {
await new permission().PermissionCreate(request, "SYS_EVA_INFO"); try {
let directorDup = await this.directorRepository.findOne({ await new permission().PermissionCreate(request, "SYS_EVA_INFO");
where: { firstName: requestBody.firstName, lastName: requestBody.lastName }, let directorDup = await this.directorRepository.findOne({
}); where: { firstName: requestBody.firstName, lastName: requestBody.lastName },
if (directorDup != null) { });
throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อกรรมการนี้มีอยู่ในระบบแล้ว"); if (directorDup != null) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อกรรมการนี้มีอยู่ในระบบแล้ว");
}
const director = Object.assign(new Director(), requestBody);
director.createdUserId = request.user.sub;
director.createdFullName = request.user.name;
director.createdAt = new Date();
director.lastUpdateUserId = request.user.sub;
director.lastUpdateFullName = request.user.name;
director.lastUpdatedAt = new Date();
const before = null;
await this.directorRepository.save(director, { data: request });
setLogDataDiff(request, { before, after: director });
return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
const director = Object.assign(new Director(), requestBody);
director.createdUserId = request.user.sub;
director.createdFullName = request.user.name;
director.createdAt = new Date();
director.lastUpdateUserId = request.user.sub;
director.lastUpdateFullName = request.user.name;
director.lastUpdatedAt = new Date();
const before = null;
await this.directorRepository.save(director, { data: request });
setLogDataDiff(request, { before, after: director });
return new HttpSuccess();
} }
/** /**
@ -171,25 +201,31 @@ export class DirectorController {
*/ */
@Put("{id}") @Put("{id}")
async update(@Path() id: string, @Body() u: CreateDirector, @Request() request: RequestWithUser) { async update(@Path() id: string, @Body() u: CreateDirector, @Request() request: RequestWithUser) {
await new permission().PermissionUpdate(request, "SYS_EVA_INFO"); try {
let directorDup = await this.directorRepository.findOne({ await new permission().PermissionUpdate(request, "SYS_EVA_INFO");
where: { firstName: u.firstName, lastName: u.lastName, id: Not(id) }, let directorDup = await this.directorRepository.findOne({
}); where: { firstName: u.firstName, lastName: u.lastName, id: Not(id) },
if (directorDup != null) { });
throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อกรรมการนี้มีอยู่ในระบบแล้ว"); if (directorDup != null) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ชื่อกรรมการนี้มีอยู่ในระบบแล้ว");
}
let director = await this.directorRepository.findOneBy({ id });
if (!director) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
}
const before = structuredClone(directorDup);
director.lastUpdateUserId = request.user.sub;
director.lastUpdateFullName = request.user.name;
director.lastUpdatedAt = new Date();
this.directorRepository.merge(director, u);
await this.directorRepository.save(director, { data: request });
setLogDataDiff(request, { before, after: director });
return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
let director = await this.directorRepository.findOneBy({ id });
if (!director) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
}
const before = structuredClone(directorDup);
director.lastUpdateUserId = request.user.sub;
director.lastUpdateFullName = request.user.name;
director.lastUpdatedAt = new Date();
this.directorRepository.merge(director, u);
await this.directorRepository.save(director, { data: request });
setLogDataDiff(request, { before, after: director });
return new HttpSuccess();
} }
/** /**
@ -200,12 +236,18 @@ export class DirectorController {
*/ */
@Delete("{id}") @Delete("{id}")
async remove(id: string, @Request() request: RequestWithUser) { async remove(id: string, @Request() request: RequestWithUser) {
await new permission().PermissionDelete(request, "SYS_EVA_INFO"); try {
let director = await this.directorRepository.findOneBy({ id }); await new permission().PermissionDelete(request, "SYS_EVA_INFO");
if (!director) { let director = await this.directorRepository.findOneBy({ id });
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found."); if (!director) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
}
await this.directorRepository.remove(director, { data: request });
return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
await this.directorRepository.remove(director, { data: request });
return new HttpSuccess();
} }
} }

View file

@ -23,6 +23,8 @@ import {
} from "../services/storage"; } from "../services/storage";
import { AppDataSource } from "../database/data-source"; import { AppDataSource } from "../database/data-source";
import { Evaluation } from "../entities/Evaluation"; import { Evaluation } from "../entities/Evaluation";
import HttpError from "../interfaces/http-error";
import HttpStatusCode from "../interfaces/http-status";
@Route("api/v1/evaluation/document") @Route("api/v1/evaluation/document")
@Tags("document") @Tags("document")
@ -58,9 +60,15 @@ export class DocumentController extends Controller {
}, },
]) ])
public async getFile(@Path() volume: string, @Path() id: string) { public async getFile(@Path() volume: string, @Path() id: string) {
const list = await listFile(["ระบบประเมิน", volume, id]); try {
if (!list) throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถสร้างแฟ้มได้"); const list = await listFile(["ระบบประเมิน", volume, id]);
return list; if (!list) throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถสร้างแฟ้มได้");
return list;
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -97,9 +105,15 @@ export class DocumentController extends Controller {
downloadUrl: "https://.../...", // Presigned Download URL 7 Days Exp downloadUrl: "https://.../...", // Presigned Download URL 7 Days Exp
}) })
public async getFileDownload(@Path() id: string, @Path() volume: string, @Path() file: string) { public async getFileDownload(@Path() id: string, @Path() volume: string, @Path() file: string) {
const data = await downloadFile(["ระบบประเมิน", volume, id], file); try {
if (!data) throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถสร้างแฟ้มได้"); const data = await downloadFile(["ระบบประเมิน", volume, id], file);
return data; if (!data) throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถสร้างแฟ้มได้");
return data;
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -194,64 +208,73 @@ export class DocumentController extends Controller {
replace?: boolean; replace?: boolean;
}, },
) { ) {
const path = ["ระบบประเมิน", volume]; try {
const path = ["ระบบประเมิน", volume];
if (!(await createFolder(path, id, true))) { if (!(await createFolder(path, id, true))) {
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถสร้างแฟ้มได้"); throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถสร้างแฟ้มได้");
}
const list = await listFile(["ระบบประเมิน", volume, id]);
if (!list || !Array.isArray(list)) {
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถสร้างแฟ้มได้");
}
let used: string[] = [];
const evaluation = AppDataSource.getRepository(Evaluation);
let author = await evaluation.findOne({
where: { id },
});
let fileList = !body.replace
? body.fileList.map(({ fileName, ...props }) => {
const dotIndex = fileName.lastIndexOf(".");
const originalName =
dotIndex !== -1 && !fileName.startsWith(".") ? fileName.slice(0, dotIndex) : fileName;
const extension =
dotIndex !== -1 && !fileName.startsWith(".") ? fileName.slice(dotIndex) : "";
let i = 1;
while (
list.findIndex((v) => v.fileName === fileName) !== -1 ||
used.includes(fileName)
) {
fileName = `${originalName} (${i++})`;
if (dotIndex !== -1) fileName += extension;
}
if (author) {
props.author = `${author.prefix}${author.fullName}`;
} else {
props.author = "ไม่พบข้อมูล";
}
used.push(fileName);
return { fileName: fileName, ...props };
})
: body.fileList;
const map = fileList.map(async ({ fileName, ...props }) => [
fileName,
await createFile([...path, id], fileName, props),
]);
const result = await Promise.all(map).catch((e) =>
console.error(`Storage Service Error: ${e}`),
);
if (!result || result.some((v) => !v[1])) {
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถอัปโหลดไฟล์ได้");
}
return Object.fromEntries(result);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
const list = await listFile(["ระบบประเมิน", volume, id]);
if (!list || !Array.isArray(list)) {
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถสร้างแฟ้มได้");
}
let used: string[] = [];
const evaluation = AppDataSource.getRepository(Evaluation);
let author = await evaluation.findOne({
where: { id },
});
let fileList = !body.replace
? body.fileList.map(({ fileName, ...props }) => {
const dotIndex = fileName.lastIndexOf(".");
const originalName =
dotIndex !== -1 && !fileName.startsWith(".") ? fileName.slice(0, dotIndex) : fileName;
const extension =
dotIndex !== -1 && !fileName.startsWith(".") ? fileName.slice(dotIndex) : "";
let i = 1;
while (list.findIndex((v) => v.fileName === fileName) !== -1 || used.includes(fileName)) {
fileName = `${originalName} (${i++})`;
if (dotIndex !== -1) fileName += extension;
}
if(author){
props.author = `${author.prefix}${author.fullName}`;
}else{
props.author = "ไม่พบข้อมูล";
}
used.push(fileName);
return { fileName: fileName, ...props };
})
: body.fileList;
const map = fileList.map(async ({ fileName, ...props }) => [
fileName,
await createFile([...path, id], fileName, props),
]);
const result = await Promise.all(map).catch((e) =>
console.error(`Storage Service Error: ${e}`),
);
if (!result || result.some((v) => !v[1])) {
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถอัปโหลดไฟล์ได้");
}
return Object.fromEntries(result);
} }
/** /**
@ -276,13 +299,19 @@ export class DocumentController extends Controller {
metadata?: { [key: string]: unknown }; metadata?: { [key: string]: unknown };
}, },
) { ) {
const props = body; try {
const result = await updateFile(["ระบบประเมิน", volume, id], file, props); const props = body;
const result = await updateFile(["ระบบประเมิน", volume, id], file, props);
if (!result) { if (!result) {
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถอัปโหลดไฟล์ได้"); throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถอัปโหลดไฟล์ได้");
}
return this.setStatus(HttpStatus.NO_CONTENT);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
return this.setStatus(HttpStatus.NO_CONTENT);
} }
/** /**
@ -293,12 +322,18 @@ export class DocumentController extends Controller {
*/ */
@Delete("{volume}/{id}") @Delete("{volume}/{id}")
public async deleteFolder(@Path() volume: string, @Path() id: string) { public async deleteFolder(@Path() volume: string, @Path() id: string) {
const result = await deleteFolder(["ระบบประเมิน", volume], id); try {
const result = await deleteFolder(["ระบบประเมิน", volume], id);
if (!result) { if (!result) {
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถอัปโหลดไฟล์ได้"); throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถอัปโหลดไฟล์ได้");
}
return this.setStatus(HttpStatus.NO_CONTENT);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
return this.setStatus(HttpStatus.NO_CONTENT);
} }
/** /**
@ -310,11 +345,17 @@ export class DocumentController extends Controller {
*/ */
@Delete("{volume}/{id}/{file}") @Delete("{volume}/{id}/{file}")
public async deleteFile(@Path() volume: string, @Path() id: string, @Path() file: string) { public async deleteFile(@Path() volume: string, @Path() id: string, @Path() file: string) {
const result = await deleteFile(["ระบบประเมิน", volume, id], file); try {
const result = await deleteFile(["ระบบประเมิน", volume, id], file);
if (!result) { if (!result) {
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถอัปโหลดไฟล์ได้"); throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์ ไม่สามารถอัปโหลดไฟล์ได้");
}
return this.setStatus(HttpStatus.NO_CONTENT);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
return this.setStatus(HttpStatus.NO_CONTENT);
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -47,23 +47,29 @@ export class MeetingController {
@Query("pageSize") pageSize: number = 10, @Query("pageSize") pageSize: number = 10,
@Query("keyword") keyword?: string, @Query("keyword") keyword?: string,
) { ) {
await new permission().PermissionList(request, "SYS_EVA_INFO"); try {
const meetings = await AppDataSource.getRepository(Meeting) await new permission().PermissionList(request, "SYS_EVA_INFO");
.createQueryBuilder("meeting") const meetings = await AppDataSource.getRepository(Meeting)
.andWhere( .createQueryBuilder("meeting")
new Brackets((qb) => { .andWhere(
qb.where(keyword != null && keyword != "" ? "meeting.title LIKE :keyword" : "1=1", { new Brackets((qb) => {
keyword: `%${keyword}%`, qb.where(keyword != null && keyword != "" ? "meeting.title LIKE :keyword" : "1=1", {
}).orWhere(keyword != null && keyword != "" ? "meeting.round LIKE :keyword" : "1=1", { keyword: `%${keyword}%`,
keyword: `%${keyword}%`, }).orWhere(keyword != null && keyword != "" ? "meeting.round LIKE :keyword" : "1=1", {
}); keyword: `%${keyword}%`,
}), });
) }),
.orderBy("meeting.createdAt", "DESC") )
.skip((page - 1) * pageSize) .orderBy("meeting.createdAt", "DESC")
.take(pageSize) .skip((page - 1) * pageSize)
.getMany(); .take(pageSize)
return new HttpSuccess(meetings); .getMany();
return new HttpSuccess(meetings);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
@Get("admin") @Get("admin")
@ -73,22 +79,28 @@ export class MeetingController {
@Query("pageSize") pageSize: number = 10, @Query("pageSize") pageSize: number = 10,
@Query("keyword") keyword?: string, @Query("keyword") keyword?: string,
) { ) {
const meetings = await AppDataSource.getRepository(Meeting) try {
.createQueryBuilder("meeting") const meetings = await AppDataSource.getRepository(Meeting)
.andWhere( .createQueryBuilder("meeting")
new Brackets((qb) => { .andWhere(
qb.where(keyword != null && keyword != "" ? "meeting.title LIKE :keyword" : "1=1", { new Brackets((qb) => {
keyword: `%${keyword}%`, qb.where(keyword != null && keyword != "" ? "meeting.title LIKE :keyword" : "1=1", {
}).orWhere(keyword != null && keyword != "" ? "meeting.round LIKE :keyword" : "1=1", { keyword: `%${keyword}%`,
keyword: `%${keyword}%`, }).orWhere(keyword != null && keyword != "" ? "meeting.round LIKE :keyword" : "1=1", {
}); keyword: `%${keyword}%`,
}), });
) }),
.orderBy("meeting.createdAt", "DESC") )
.skip((page - 1) * pageSize) .orderBy("meeting.createdAt", "DESC")
.take(pageSize) .skip((page - 1) * pageSize)
.getMany(); .take(pageSize)
return new HttpSuccess(meetings); .getMany();
return new HttpSuccess(meetings);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -99,13 +111,19 @@ export class MeetingController {
*/ */
@Get("{id}") @Get("{id}")
async one(@Path() id: string, @Request() request: RequestWithUser) { async one(@Path() id: string, @Request() request: RequestWithUser) {
let _workflow = await new permission().Workflow(request, id, "SYS_EVA_INFO"); try {
if (_workflow == false) await new permission().PermissionGet(request, "SYS_EVA_INFO"); let _workflow = await new permission().Workflow(request, id, "SYS_EVA_INFO");
const meeting = await this.meetingRepository.findOne({ where: { id } }); if (_workflow == false) await new permission().PermissionGet(request, "SYS_EVA_INFO");
if (!meeting) { const meeting = await this.meetingRepository.findOne({ where: { id } });
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found."); if (!meeting) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
}
return new HttpSuccess(meeting);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
return new HttpSuccess(meeting);
} }
/** /**
@ -116,20 +134,26 @@ export class MeetingController {
*/ */
@Post() @Post()
async save(@Body() requestBody: CreateMeeting, @Request() request: RequestWithUser) { async save(@Body() requestBody: CreateMeeting, @Request() request: RequestWithUser) {
await new permission().PermissionCreate(request, "SYS_EVA_INFO"); try {
const meeting = Object.assign(new Meeting(), requestBody); await new permission().PermissionCreate(request, "SYS_EVA_INFO");
meeting.createdUserId = request.user.sub; const meeting = Object.assign(new Meeting(), requestBody);
meeting.createdFullName = request.user.name; meeting.createdUserId = request.user.sub;
meeting.createdAt = new Date(); meeting.createdFullName = request.user.name;
meeting.lastUpdateUserId = request.user.sub; meeting.createdAt = new Date();
meeting.lastUpdateFullName = request.user.name; meeting.lastUpdateUserId = request.user.sub;
meeting.lastUpdatedAt = new Date(); meeting.lastUpdateFullName = request.user.name;
const before = null; meeting.lastUpdatedAt = new Date();
const before = null;
await this.meetingRepository.save(meeting, { data: request }); await this.meetingRepository.save(meeting, { data: request });
setLogDataDiff(request, { before, after: meeting }); setLogDataDiff(request, { before, after: meeting });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -140,20 +164,26 @@ export class MeetingController {
*/ */
@Put("{id}") @Put("{id}")
async update(@Path() id: string, @Body() u: CreateMeeting, @Request() request: RequestWithUser) { async update(@Path() id: string, @Body() u: CreateMeeting, @Request() request: RequestWithUser) {
await new permission().PermissionUpdate(request, "SYS_EVA_INFO"); try {
let meeting = await this.meetingRepository.findOneBy({ id }); await new permission().PermissionUpdate(request, "SYS_EVA_INFO");
if (!meeting) { let meeting = await this.meetingRepository.findOneBy({ id });
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found."); if (!meeting) {
} throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
const before = structuredClone(meeting); }
meeting.lastUpdateUserId = request.user.sub; const before = structuredClone(meeting);
meeting.lastUpdateFullName = request.user.name; meeting.lastUpdateUserId = request.user.sub;
meeting.lastUpdatedAt = new Date(); meeting.lastUpdateFullName = request.user.name;
this.meetingRepository.merge(meeting, u); meeting.lastUpdatedAt = new Date();
await this.meetingRepository.save(meeting, { data: request }); this.meetingRepository.merge(meeting, u);
setLogDataDiff(request, { before, after: meeting }); await this.meetingRepository.save(meeting, { data: request });
setLogDataDiff(request, { before, after: meeting });
return new HttpSuccess(); return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -164,12 +194,18 @@ export class MeetingController {
*/ */
@Delete("{id}") @Delete("{id}")
async remove(id: string, @Request() request: RequestWithUser) { async remove(id: string, @Request() request: RequestWithUser) {
await new permission().PermissionDelete(request, "SYS_EVA_INFO"); try {
let meeting = await this.meetingRepository.findOneBy({ id }); await new permission().PermissionDelete(request, "SYS_EVA_INFO");
if (!meeting) { let meeting = await this.meetingRepository.findOneBy({ id });
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found."); if (!meeting) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found.");
}
await this.meetingRepository.remove(meeting, { data: request });
return new HttpSuccess();
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
await this.meetingRepository.remove(meeting, { data: request });
return new HttpSuccess();
} }
} }

View file

@ -58,70 +58,90 @@ export class ReoportController {
* *
*/ */
@Get() @Get()
async sumaryEvaluationReport(@Query("year") year?: string, @Query("rootid") rootId?: string, @Query("nameOrg") nameOrg?: string) { async sumaryEvaluationReport(
@Query("year") year?: string,
@Query("rootid") rootId?: string,
@Query("nameOrg") nameOrg?: string,
) {
try {
const yearInAD = year ? year : null;
const yearInBE = yearInAD ? (parseInt(yearInAD) - 543).toString() : null;
const yearInAD = year?year:null; let evaluation = [];
const yearInBE = yearInAD ? (parseInt(yearInAD) - 543).toString() : null; evaluation = await AppDataSource.getRepository(Evaluation)
.createQueryBuilder("evaluation")
.where("evaluation.evaluationResult NOT IN (:...evaluationResults)", {
evaluationResults: ["PENDING"],
})
.andWhere(yearInBE && yearInBE != null ? "YEAR(createdAt) = :year" : "1=1", {
year: yearInBE,
})
.andWhere("evaluation.orgRootId = :rootId", { rootId: rootId })
.andWhere("evaluation.step = :step", { step: "DONE" })
.getMany();
let evaluation = []; const groupedData = evaluation.reduce((acc: any, item) => {
evaluation = await AppDataSource.getRepository(Evaluation) const key = item.root;
.createQueryBuilder("evaluation") if (!acc[key]) {
.where('evaluation.evaluationResult NOT IN (:...evaluationResults)', { evaluationResults: ['PENDING'] }) acc[key] = {
.andWhere( yearInBE && yearInBE != null? 'YEAR(createdAt) = :year': "1=1", { year: yearInBE }) agency: item.root && item.root != "" ? item.root : "-",
.andWhere('evaluation.orgRootId = :rootId',{ rootId: rootId }) submitter: 0,
.andWhere('evaluation.step = :step', { step: 'DONE' }) passCount: 0,
.getMany(); notPassCount: 0,
};
}
if (item.evaluationResult === "PASS") {
acc[key].passCount++;
} else if (item.evaluationResult === "NOTPASS") {
acc[key].notPassCount++;
}
return acc;
}, {});
const groupedData = evaluation.reduce((acc:any, item) => { const result = Object.values(groupedData).map((item: any) => ({
const key = item.root; ...item,
if (!acc[key]) { submitter: Extension.ToThaiNumber((item.passCount + item.notPassCount).toString()),
acc[key] = { passCount: Extension.ToThaiNumber(item.passCount.toString()),
agency: item.root && item.root != "" ? item.root: "-", notPassCount: Extension.ToThaiNumber(item.notPassCount.toString()),
submitter: 0, }));
passCount: 0,
notPassCount: 0,
};
}
if (item.evaluationResult === 'PASS') {
acc[key].passCount++;
} else if (item.evaluationResult === 'NOTPASS') {
acc[key].notPassCount++;
}
return acc;
}, {});
const result = Object.values(groupedData).map((item: any) => ({ const submitter = Object.values(groupedData).reduce((acc: number, item: any) => {
...item , return acc + item.passCount + item.notPassCount;
submitter: Extension.ToThaiNumber((item.passCount + item.notPassCount).toString()), }, 0);
passCount: Extension.ToThaiNumber(item.passCount.toString()),
notPassCount: Extension.ToThaiNumber(item.notPassCount.toString()),
}));
const submitter = Object.values(groupedData).reduce((acc: number, item: any) => { const sumPass = Object.values(groupedData).reduce((acc: number, item: any) => {
return acc + item.passCount + item.notPassCount; return acc + item.passCount;
}, 0); }, 0);
const sumPass = Object.values(groupedData).reduce((acc: number, item: any) => { const sumNotPass = Object.values(groupedData).reduce((acc: number, item: any) => {
return acc + item.passCount; return acc + item.notPassCount;
}, 0); }, 0);
const sumNotPass = Object.values(groupedData).reduce((acc: number, item: any) => { return new HttpSuccess({
return acc + item.notPassCount; template: "summary-evaluation",
}, 0); reportName: "xlsx-report",
data: {
return new HttpSuccess({ year: year
template: "summary-evaluation", ? Extension.ToThaiNumber(year.toString())
reportName: "xlsx-report", : Extension.ToThaiNumber(new Date().getFullYear().toString()),
data: { date: Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date())),
year: year?Extension.ToThaiNumber(year.toString()):Extension.ToThaiNumber(new Date().getFullYear().toString()), mainAgency:
date: Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date())), rootId && result.length > 0
mainAgency: rootId && result.length > 0?result[0].agency: rootId && result.length === 0 ? '':'หน่วยงานทั้งหมด', ? result[0].agency
list: result, : rootId && result.length === 0
total: Extension.ToThaiNumber(submitter.toString()), ? ""
sumPass: Extension.ToThaiNumber(sumPass.toString()), : "หน่วยงานทั้งหมด",
sumNotPass: Extension.ToThaiNumber(sumNotPass.toString()), list: result,
}, total: Extension.ToThaiNumber(submitter.toString()),
}); sumPass: Extension.ToThaiNumber(sumPass.toString()),
sumNotPass: Extension.ToThaiNumber(sumNotPass.toString()),
},
});
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
}
} }
/** /**
@ -133,313 +153,318 @@ export class ReoportController {
*/ */
@Get("check-spec-report/{id}") @Get("check-spec-report/{id}")
async checkSpecGetReport(@Request() request: RequestWithUser, @Path() id: string) { async checkSpecGetReport(@Request() request: RequestWithUser, @Path() id: string) {
const evaluation = await AppDataSource.getRepository(Evaluation) try {
.createQueryBuilder("evaluation") const evaluation = await AppDataSource.getRepository(Evaluation)
.leftJoin("evaluation.education", "education") .createQueryBuilder("evaluation")
.leftJoin("evaluation.certificate", "certificate") .leftJoin("evaluation.education", "education")
.leftJoin("evaluation.salaries", "salaries") .leftJoin("evaluation.certificate", "certificate")
.leftJoin("evaluation.training", "training") .leftJoin("evaluation.salaries", "salaries")
.leftJoin("evaluation.assessment", "assessment") .leftJoin("evaluation.training", "training")
.where("evaluation.id = :id", { id }) .leftJoin("evaluation.assessment", "assessment")
.select([ .where("evaluation.id = :id", { id })
"evaluation.id", .select([
"evaluation.userId", "evaluation.id",
"evaluation.subject", "evaluation.userId",
"evaluation.isEducationalQft", "evaluation.subject",
"evaluation.isGovermantServiceHtr", "evaluation.isEducationalQft",
"evaluation.isOperatingExp", "evaluation.isGovermantServiceHtr",
"evaluation.isMinPeriodOfTenure", "evaluation.isOperatingExp",
"evaluation.isHaveSpecificQft", "evaluation.isMinPeriodOfTenure",
"evaluation.isHaveProLicense", "evaluation.isHaveSpecificQft",
"evaluation.isHaveMinPeriodOrHoldPos", "evaluation.isHaveProLicense",
"evaluation.type", "evaluation.isHaveMinPeriodOrHoldPos",
"evaluation.prefix", "evaluation.type",
"evaluation.fullName", "evaluation.prefix",
"evaluation.position", "evaluation.fullName",
"evaluation.posNo", "evaluation.position",
"evaluation.oc", "evaluation.posNo",
"evaluation.salary", "evaluation.oc",
"evaluation.positionLevel", "evaluation.salary",
"evaluation.birthDate", "evaluation.positionLevel",
"evaluation.govAge", "evaluation.birthDate",
"evaluation.experience", "evaluation.govAge",
"evaluation.experience",
"education.educationLevel", "education.educationLevel",
"education.institute", "education.institute",
"education.isDate", "education.isDate",
"education.startDate", "education.startDate",
"education.endDate", "education.endDate",
"education.finishDate", "education.finishDate",
"education.isEducation", "education.isEducation",
"education.degree", "education.degree",
"education.field", "education.field",
"education.fundName", "education.fundName",
"education.gpa", "education.gpa",
"education.country", "education.country",
"education.other", "education.other",
"education.duration", "education.duration",
"education.durationYear", "education.durationYear",
"certificate.certificateType", "certificate.certificateType",
"certificate.issuer", "certificate.issuer",
"certificate.certificateNo", "certificate.certificateNo",
"certificate.issueDate", "certificate.issueDate",
"certificate.expireDate", "certificate.expireDate",
"salaries.date", "salaries.date",
"salaries.amount", "salaries.amount",
"salaries.positionSalaryAmount", "salaries.positionSalaryAmount",
"salaries.mouthSalaryAmount", "salaries.mouthSalaryAmount",
"salaries.position", "salaries.position",
"salaries.posNo", "salaries.posNo",
"salaries.salaryClass", "salaries.salaryClass",
"salaries.salaryRef", "salaries.salaryRef",
"salaries.refCommandNo", "salaries.refCommandNo",
"salaries.refCommandDate", "salaries.refCommandDate",
"salaries.salaryStatus", "salaries.salaryStatus",
"training.name", "training.name",
"training.topic", "training.topic",
"training.startDate", "training.startDate",
"training.endDate", "training.endDate",
"training.yearly", "training.yearly",
"training.place", "training.place",
"training.duration", "training.duration",
"training.department", "training.department",
"training.numberOrder", "training.numberOrder",
"training.dateOrder", "training.dateOrder",
"assessment.date", "assessment.date",
"assessment.point1Total", "assessment.point1Total",
"assessment.point1", "assessment.point1",
"assessment.point2Total", "assessment.point2Total",
"assessment.point2", "assessment.point2",
"assessment.pointSumTotal", "assessment.pointSumTotal",
"assessment.pointSum", "assessment.pointSum",
]) ])
.getOne(); .getOne();
if (!evaluation) { if (!evaluation) {
return "ไม่พบข้อมูล"; return "ไม่พบข้อมูล";
} }
let root: any; let root: any;
let dateStart: any; let dateStart: any;
let dateRetireLaw: any; let dateRetireLaw: any;
let org: any; let org: any;
let commanderFullname: any; let commanderFullname: any;
let commanderPosition: any; let commanderPosition: any;
let commanderRootName: any; let commanderRootName: any;
let commanderOrg: any; let commanderOrg: any;
let commanderAboveFullname: any; let commanderAboveFullname: any;
let commanderAbovePosition: any; let commanderAbovePosition: any;
let commanderAboveRootName: any; let commanderAboveRootName: any;
let commanderAboveOrg: any; let commanderAboveOrg: any;
if (!evaluation.userId) { if (!evaluation.userId) {
return "ไม่พบข้อมูลผู้ขอประเมิน"; return "ไม่พบข้อมูลผู้ขอประเมิน";
} }
await new CallAPI() await new CallAPI()
.GetData(request, `/org/profile/keycloak/commander/${evaluation.userId}`) .GetData(request, `/org/profile/keycloak/commander/${evaluation.userId}`)
.then(async (x) => { .then(async (x) => {
(root = x.root), (root = x.root),
(dateStart = x.dateStart), (dateStart = x.dateStart),
(dateRetireLaw = x.dateRetireLaw), (dateRetireLaw = x.dateRetireLaw),
(org = x.org), (org = x.org),
(commanderFullname = x.commanderFullname), (commanderFullname = x.commanderFullname),
(commanderPosition = x.commanderPosition), (commanderPosition = x.commanderPosition),
(commanderRootName = x.commanderRootName), (commanderRootName = x.commanderRootName),
(commanderOrg = x.commanderOrg), (commanderOrg = x.commanderOrg),
(commanderAboveFullname = x.commanderAboveFullname), (commanderAboveFullname = x.commanderAboveFullname),
(commanderAbovePosition = x.commanderAbovePosition), (commanderAbovePosition = x.commanderAbovePosition),
(commanderAboveRootName = x.commanderAboveRootName), (commanderAboveRootName = x.commanderAboveRootName),
(commanderAboveOrg = x.commanderAboveOrg); (commanderAboveOrg = x.commanderAboveOrg);
}) })
.catch(); .catch();
const evaluationOld = await this.evaluationRepository.find({ const evaluationOld = await this.evaluationRepository.find({
where: { where: {
id: Not(id), id: Not(id),
userId: evaluation.userId, userId: evaluation.userId,
step: "DONE", step: "DONE",
}, },
}); });
let subjectOld = let subjectOld =
evaluationOld.length > 0 ? evaluationOld.map((x) => x.subject).join(", ") : "ไม่มี"; evaluationOld.length > 0 ? evaluationOld.map((x) => x.subject).join(", ") : "ไม่มี";
let thaiYear: number = new Date().getFullYear() + 543; let thaiYear: number = new Date().getFullYear() + 543;
let years = { let years = {
lastTwoYear: Extension.ToThaiNumber((thaiYear - 2).toString()), lastTwoYear: Extension.ToThaiNumber((thaiYear - 2).toString()),
lastOneYear: Extension.ToThaiNumber((thaiYear - 1).toString()), lastOneYear: Extension.ToThaiNumber((thaiYear - 1).toString()),
currentYear: Extension.ToThaiNumber(thaiYear.toString()), currentYear: Extension.ToThaiNumber(thaiYear.toString()),
}; };
const dataEvaluation = { const dataEvaluation = {
isEducationalQft: evaluation.isEducationalQft, isEducationalQft: evaluation.isEducationalQft,
isGovermantServiceHtr: evaluation.isGovermantServiceHtr, isGovermantServiceHtr: evaluation.isGovermantServiceHtr,
isOperatingExp: evaluation.isOperatingExp, isOperatingExp: evaluation.isOperatingExp,
isMinPeriodOfTenure: evaluation.isMinPeriodOfTenure, isMinPeriodOfTenure: evaluation.isMinPeriodOfTenure,
isHaveSpecificQft: evaluation.isHaveSpecificQft, isHaveSpecificQft: evaluation.isHaveSpecificQft,
isHaveProLicense: evaluation.isHaveProLicense, isHaveProLicense: evaluation.isHaveProLicense,
isHaveMinPeriodOrHoldPos: evaluation.isHaveMinPeriodOrHoldPos, isHaveMinPeriodOrHoldPos: evaluation.isHaveMinPeriodOrHoldPos,
type: evaluation.type, type: evaluation.type,
prefix: evaluation.prefix, prefix: evaluation.prefix,
fullName: fullName: evaluation.fullName ? `${evaluation.fullName}` : "-",
evaluation.prefix && evaluation.fullName position: evaluation.position ? evaluation.position : "-",
? `${evaluation.prefix}${evaluation.fullName}` posNo: evaluation.posNo ? Extension.ToThaiNumber(evaluation.posNo) : "-",
oc: evaluation.oc ? evaluation.oc : "-",
org: org ? org : "-", //สังกัด
root: root ? root : "-", //หน่วยงาน
salary: evaluation.salary ? Extension.ToThaiNumber(evaluation.salary) : "-",
positionLevel: evaluation.positionLevel ? evaluation.positionLevel : "-",
birthDate:
evaluation.birthDate != null && evaluation.birthDate != ""
? Extension.ToThaiNumber(
Extension.ToThaiShortDate_noPrefix(new Date(evaluation.birthDate)),
)
: "-",
govAge: evaluation.govAge != null ? Extension.ToThaiNumber(evaluation.govAge) : "-",
experience: evaluation.experience ? evaluation.experience : "-",
dateStart: dateStart
? Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date(dateStart)))
: "-", : "-",
position: evaluation.position ? evaluation.position : "-", dateRetireLaw: dateRetireLaw
posNo: evaluation.posNo ? Extension.ToThaiNumber(evaluation.posNo) : "-", ? Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date(dateRetireLaw)))
oc: evaluation.oc ? evaluation.oc : "-",
org: org ? org : "-", //สังกัด
root: root ? root : "-", //หน่วยงาน
salary: evaluation.salary ? Extension.ToThaiNumber(evaluation.salary) : "-",
positionLevel: evaluation.positionLevel ? evaluation.positionLevel : "-",
birthDate:
evaluation.birthDate != null && evaluation.birthDate != ""
? Extension.ToThaiNumber(
Extension.ToThaiShortDate_noPrefix(new Date(evaluation.birthDate)),
)
: "-", : "-",
govAge: evaluation.govAge != null ? Extension.ToThaiNumber(evaluation.govAge) : "-", subject: evaluation.subject != null ? evaluation.subject : "-",
experience: evaluation.experience ? evaluation.experience : "-", subjectOld: subjectOld,
dateStart: dateStart educations:
? Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date(dateStart))) evaluation.education.length > 0
: "-", ? evaluation.education.map((education) => ({
dateRetireLaw: dateRetireLaw educationLevel: education.educationLevel
? Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date(dateRetireLaw))) ? Extension.ToThaiNumber(education.educationLevel)
: "-", : "-",
subject: evaluation.subject != null ? evaluation.subject : "-", institute: education.institute ? Extension.ToThaiNumber(education.institute) : "-",
subjectOld: subjectOld, finishYear: education.finishDate
educations: ? Extension.ToThaiNumber(
evaluation.education.length > 0 Extension.ToThaiYear(education.finishDate.getFullYear()).toString(),
? evaluation.education.map((education) => ({ )
educationLevel: education.educationLevel : "-",
? Extension.ToThaiNumber(education.educationLevel) isDate: education.isDate,
: "-", startDate: education.startDate,
institute: education.institute ? Extension.ToThaiNumber(education.institute) : "-", endDate: education.endDate,
finishYear: education.finishDate finishDate: education.finishDate
? Extension.ToThaiNumber( ? Extension.ToThaiNumber(
Extension.ToThaiYear(education.finishDate.getFullYear()).toString(), Extension.ToThaiShortDate(education.finishDate).toString(),
) )
: "-", : "-",
isDate: education.isDate, isEducation: education.isEducation,
startDate: education.startDate, degree: education.degree ? Extension.ToThaiNumber(education.degree) : "-",
endDate: education.endDate, field: education.field ? Extension.ToThaiNumber(education.field) : "-",
finishDate: education.finishDate fundName: education.fundName,
? Extension.ToThaiNumber(Extension.ToThaiShortDate(education.finishDate).toString()) gpa: education.gpa,
: "-", country: education.country,
isEducation: education.isEducation, other: education.other,
degree: education.degree ? Extension.ToThaiNumber(education.degree) : "-", duration: education.duration,
field: education.field ? Extension.ToThaiNumber(education.field) : "-", durationYear: education.durationYear,
fundName: education.fundName, }))
gpa: education.gpa, : [
country: education.country, {
other: education.other, educationLevel: "-",
duration: education.duration, institute: "-",
durationYear: education.durationYear, finishYear: "-",
})) finishDate: "-",
: [ degree: "-",
{ field: "-",
educationLevel: "-", },
institute: "-", ],
finishYear: "-", certificates:
finishDate: "-", evaluation.certificate.length > 0
degree: "-", ? evaluation.certificate.map((certificate) => ({
field: "-", certificateType: certificate.certificateType
}, ? Extension.ToThaiNumber(certificate.certificateType)
], : "-",
certificates: issuer: certificate.issuer ? Extension.ToThaiNumber(certificate.issuer) : "-",
evaluation.certificate.length > 0 certificateNo: certificate.certificateNo
? evaluation.certificate.map((certificate) => ({ ? Extension.ToThaiNumber(certificate.certificateNo)
certificateType: certificate.certificateType : "-",
? Extension.ToThaiNumber(certificate.certificateType) issueDate: certificate.issueDate,
: "-", expireDate: certificate.expireDate,
issuer: certificate.issuer ? Extension.ToThaiNumber(certificate.issuer) : "-", }))
certificateNo: certificate.certificateNo : [
? Extension.ToThaiNumber(certificate.certificateNo) {
: "-", certificateType: "-",
issueDate: certificate.issueDate, issuer: "-",
expireDate: certificate.expireDate, certificateNo: "-",
})) issueDate: "-",
: [ expireDate: "-",
{ },
certificateType: "-", ],
issuer: "-", salaries:
certificateNo: "-", evaluation.salaries.length > 0
issueDate: "-", ? evaluation.salaries.map((salaries) => ({
expireDate: "-", date: salaries.date
}, ? Extension.ToThaiNumber(Extension.ToThaiShortDate_noPrefix(salaries.date))
], : "-",
salaries: amount: salaries.amount
evaluation.salaries.length > 0 ? Extension.ToThaiNumber(salaries.amount.toLocaleString())
? evaluation.salaries.map((salaries) => ({ : "-",
date: salaries.date position: salaries.position ? Extension.ToThaiNumber(salaries.position) : "-",
? Extension.ToThaiNumber(Extension.ToThaiShortDate_noPrefix(salaries.date)) positionSalaryAmount: salaries.positionSalaryAmount,
: "-", mouthSalaryAmount: salaries.mouthSalaryAmount,
amount: salaries.amount posNo: salaries.posNo,
? Extension.ToThaiNumber(salaries.amount.toLocaleString()) salaryClass: salaries.salaryClass,
: "-", salaryRef: salaries.salaryRef,
position: salaries.position ? Extension.ToThaiNumber(salaries.position) : "-", refCommandNo: salaries.refCommandNo,
positionSalaryAmount: salaries.positionSalaryAmount, refCommandDate: salaries.refCommandDate,
mouthSalaryAmount: salaries.mouthSalaryAmount, salaryStatus: salaries.salaryStatus,
posNo: salaries.posNo, }))
salaryClass: salaries.salaryClass, : [
salaryRef: salaries.salaryRef, {
refCommandNo: salaries.refCommandNo, date: "-",
refCommandDate: salaries.refCommandDate, amount: "-",
salaryStatus: salaries.salaryStatus, position: "-",
})) },
: [ ],
{ trainings:
date: "-", evaluation.training.length > 0
amount: "-", ? evaluation.training.map((training) => ({
position: "-", name: training.name ? Extension.ToThaiNumber(training.name) : "-",
}, topic: training.topic ? Extension.ToThaiNumber(training.topic) : "-",
], startDate: training.startDate
trainings: ? Extension.ToThaiNumber(Extension.ToThaiShortDate_noPrefix(training.startDate))
evaluation.training.length > 0 : "-",
? evaluation.training.map((training) => ({ endDate: training.endDate
name: training.name ? Extension.ToThaiNumber(training.name) : "-", ? Extension.ToThaiNumber(Extension.ToThaiShortDate_noPrefix(training.endDate))
topic: training.topic ? Extension.ToThaiNumber(training.topic) : "-", : "-",
startDate: training.startDate yearly: training.yearly ? Extension.ToThaiNumber(training.yearly.toString()) : "-",
? Extension.ToThaiNumber(Extension.ToThaiShortDate_noPrefix(training.startDate)) place: training.place,
: "-", duration: training.duration,
endDate: training.endDate department: training.department,
? Extension.ToThaiNumber(Extension.ToThaiShortDate_noPrefix(training.endDate)) numberOrder: training.numberOrder,
: "-", dateOrder: training.dateOrder,
yearly: training.yearly ? Extension.ToThaiNumber(training.yearly.toString()) : "-", }))
place: training.place, : [
duration: training.duration, {
department: training.department, name: "-",
numberOrder: training.numberOrder, topic: "-",
dateOrder: training.dateOrder, yearly: "-",
})) },
: [ ],
{ assessments: evaluation.assessment.map((assessment) => ({
name: "-", date: assessment.date,
topic: "-", point1Total: assessment.point1Total,
yearly: "-", point1: assessment.point1,
}, point2Total: assessment.point2Total,
], point2: assessment.point2,
assessments: evaluation.assessment.map((assessment) => ({ pointSumTotal: assessment.pointSumTotal,
date: assessment.date, pointSum: assessment.pointSum,
point1Total: assessment.point1Total, })),
point1: assessment.point1, commanderFullname: commanderFullname ? commanderFullname : "-",
point2Total: assessment.point2Total, commanderPosition: commanderPosition ? commanderPosition : "-",
point2: assessment.point2, commanderRootName: commanderRootName ? commanderRootName : "-",
pointSumTotal: assessment.pointSumTotal, commanderOrg: commanderOrg ? commanderOrg : "-",
pointSum: assessment.pointSum, commanderAboveFullname: commanderAboveFullname ? commanderAboveFullname : "-",
})), commanderAbovePosition: commanderAbovePosition ? commanderAbovePosition : "-",
commanderFullname: commanderFullname ? commanderFullname : "-", commanderAboveRootName: commanderAboveRootName ? commanderAboveRootName : "-",
commanderPosition: commanderPosition ? commanderPosition : "-", commanderAboveOrg: commanderAboveOrg ? commanderAboveOrg : "-",
commanderRootName: commanderRootName ? commanderRootName : "-", years: years,
commanderOrg: commanderOrg ? commanderOrg : "-", };
commanderAboveFullname: commanderAboveFullname ? commanderAboveFullname : "-",
commanderAbovePosition: commanderAbovePosition ? commanderAbovePosition : "-",
commanderAboveRootName: commanderAboveRootName ? commanderAboveRootName : "-",
commanderAboveOrg: commanderAboveOrg ? commanderAboveOrg : "-",
years: years,
};
if (!dataEvaluation) { if (!dataEvaluation) {
return "ไม่พบข้อมูล"; return "ไม่พบข้อมูล";
}
return new HttpSuccess(dataEvaluation);
} catch (error: any) {
if (error instanceof HttpError) {
throw error;
} else throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, error);
} }
return new HttpSuccess(dataEvaluation);
} }
} }

View file

@ -51,6 +51,7 @@ export const AppDataSource = new DataSource({
password: process.env.DB_PASSWORD, password: process.env.DB_PASSWORD,
connectorPackage: "mysql2", connectorPackage: "mysql2",
synchronize: false, synchronize: false,
// timezone: "Z", // "Z" = UTC
logging: ["query", "error"], logging: ["query", "error"],
entities: entities:
process.env.NODE_ENV !== "production" process.env.NODE_ENV !== "production"

View file

@ -184,12 +184,34 @@ class CheckAuth {
}); });
} }
public async checkOrg(token: any, keycloakId: string) { public async checkOrg(token: any, keycloakId: string) {
const redisClient = await this.redis.createClient({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
});
const getAsync = promisify(redisClient.get).bind(redisClient);
try { try {
// Validate required environment variables
const REDIS_HOST = process.env.REDIS_HOST;
const REDIS_PORT = process.env.REDIS_PORT ? Number(process.env.REDIS_PORT) : 6379;
if (!REDIS_HOST) {
throw new Error("REDIS_HOST is not set in environment variables");
}
console.log(`[REDIS] Connecting to Redis at ${REDIS_HOST}:${REDIS_PORT}`);
// Create Redis client
const redisClient = this.redis.createClient({
socket: {
host: REDIS_HOST,
port: REDIS_PORT,
},
});
redisClient.on("error", (err: any) => {
console.error("[REDIS] Connection error:", err.message);
});
await redisClient.connect();
console.log("[REDIS] Connected successfully!");
const getAsync = promisify(redisClient.get).bind(redisClient);
let reply = await getAsync("org_" + keycloakId); let reply = await getAsync("org_" + keycloakId);
if (reply != null) { if (reply != null) {
reply = JSON.parse(reply); reply = JSON.parse(reply);