hrms-api-org/src/controllers/ProfileEmployeeController.ts

6198 lines
255 KiB
TypeScript
Raw Normal View History

import {
Controller,
Post,
Put,
Delete,
Route,
Security,
Tags,
Body,
Path,
Request,
SuccessResponse,
Response,
Get,
Query,
Example,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
2025-10-22 14:23:28 +07:00
import HttpStatusCode from "../interfaces/http-status";
2024-06-18 12:08:03 +07:00
import { Brackets, Double, In, IsNull, Like, Not } from "typeorm";
import { OrgRevision } from "../entities/OrgRevision";
2024-07-19 11:08:47 +07:00
import {
calculateRetireDate,
calculateRetireLaw,
removeProfileInOrganize,
} from "../interfaces/utils";
import { EmployeePosMaster } from "../entities/EmployeePosMaster";
import {
ProfileEmployee,
CreateProfileEmployee,
UpdateProfileEmployee,
ProfileEmployeeHistory,
2024-06-07 03:05:57 +07:00
UpdatePositionTempProfileEmployee,
UpdateInformationProfileEmployee,
} from "../entities/ProfileEmployee";
import { EmployeePosLevel } from "../entities/EmployeePosLevel";
import { EmployeePosType } from "../entities/EmployeePosType";
import { RequestWithUser } from "../middlewares/user";
import { Province } from "../entities/Province";
import { District } from "../entities/District";
import { SubDistrict } from "../entities/SubDistrict";
2024-05-24 15:57:29 +07:00
import { ProfileCertificate } from "../entities/ProfileCertificate";
import { ProfileTraining } from "../entities/ProfileTraining";
import { ProfileDiscipline } from "../entities/ProfileDiscipline";
import { ProfileEducation } from "../entities/ProfileEducation";
import { ProfileSalary } from "../entities/ProfileSalary";
import { ProfileFamilyCouple } from "../entities/ProfileFamilyCouple";
import { ProfileFamilyMother } from "../entities/ProfileFamilyMother";
import { ProfileFamilyFather } from "../entities/ProfileFamilyFather";
2024-05-23 15:28:49 +07:00
import Extension from "../interfaces/extension";
import { OrgRoot } from "../entities/OrgRoot";
import { OrgChild1 } from "../entities/OrgChild1";
import { OrgChild2 } from "../entities/OrgChild2";
import { OrgChild3 } from "../entities/OrgChild3";
import { OrgChild4 } from "../entities/OrgChild4";
import { ProfileEmployeeInformationHistory } from "../entities/ProfileEmployeeInformationHistory";
import {
ProfileEmployeeEmployment,
CreateEmploymentProfileEmployee,
UpdateEmploymentProfileEmployee,
} from "../entities/ProfileEmployeeEmployment";
import { ProfileEmployeeEmploymentHistory } from "../entities/ProfileEmployeeEmploymentHistory";
import CallAPI from "../interfaces/call-api";
2024-07-12 14:04:00 +07:00
import { ProfileInsignia } from "../entities/ProfileInsignia";
import { ProfileLeave } from "../entities/ProfileLeave";
import permission from "../interfaces/permission";
2024-09-30 13:18:02 +07:00
import axios from "axios";
2024-11-06 10:32:02 +07:00
import { Position } from "../entities/Position";
2025-02-18 23:02:38 +07:00
import { EmployeePosition } from "../entities/EmployeePosition";
import { deleteUser } from "../keycloak";
2025-03-26 15:23:18 +07:00
import { PermissionProfile } from "../entities/PermissionProfile";
2025-04-05 19:21:50 +07:00
import { ProfileSalaryHistory } from "../entities/ProfileSalaryHistory";
2025-05-02 09:39:53 +07:00
import { ProfileAbility } from "../entities/ProfileAbility";
import { ProfileActposition } from "../entities/ProfileActposition";
import { ProfileAssessment } from "../entities/ProfileAssessment";
import { ProfileAssistance } from "../entities/ProfileAssistance";
import { ProfileChangeName } from "../entities/ProfileChangeName";
import { ProfileChildren } from "../entities/ProfileChildren";
import { ProfileDuty } from "../entities/ProfileDuty";
2025-09-08 00:10:59 +07:00
import { getTopDegrees } from "../services/PositionService";
import { ProfileLeaveService } from "../services/ProfileLeaveService";
@Route("api/v1/org/profile-employee")
@Tags("ProfileEmployee")
@Security("bearerAuth")
@Response(
HttpStatus.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
@SuccessResponse(HttpStatus.OK, "สำเร็จ")
export class ProfileEmployeeController extends Controller {
2024-03-21 10:41:18 +07:00
private orgRevisionRepo = AppDataSource.getRepository(OrgRevision);
private posMasterRepo = AppDataSource.getRepository(EmployeePosMaster);
private profileRepo = AppDataSource.getRepository(ProfileEmployee);
private profileHistoryRepo = AppDataSource.getRepository(ProfileEmployeeHistory);
2024-03-21 10:41:18 +07:00
private posLevelRepo = AppDataSource.getRepository(EmployeePosLevel);
private posTypeRepo = AppDataSource.getRepository(EmployeePosType);
private provinceRepository = AppDataSource.getRepository(Province);
private districtRepository = AppDataSource.getRepository(District);
private subDistrict = AppDataSource.getRepository(SubDistrict);
2024-05-24 15:57:29 +07:00
private certificateRepository = AppDataSource.getRepository(ProfileCertificate);
private profileFamilyCoupleRepository = AppDataSource.getRepository(ProfileFamilyCouple);
private profileFamilyMotherRepository = AppDataSource.getRepository(ProfileFamilyMother);
private profileFamilyFatherRepository = AppDataSource.getRepository(ProfileFamilyFather);
private trainingRepository = AppDataSource.getRepository(ProfileTraining);
private disciplineRepository = AppDataSource.getRepository(ProfileDiscipline);
2025-01-08 14:15:28 +07:00
private salaryRepo = AppDataSource.getRepository(ProfileSalary);
2025-04-05 19:21:50 +07:00
private salaryHistoryRepo = AppDataSource.getRepository(ProfileSalaryHistory);
private orgRootRepository = AppDataSource.getRepository(OrgRoot);
private child1Repository = AppDataSource.getRepository(OrgChild1);
private child2Repository = AppDataSource.getRepository(OrgChild2);
private child3Repository = AppDataSource.getRepository(OrgChild3);
private child4Repository = AppDataSource.getRepository(OrgChild4);
private informationHistoryRepository = AppDataSource.getRepository(
ProfileEmployeeInformationHistory,
);
private employmentRepository = AppDataSource.getRepository(ProfileEmployeeEmployment);
private employmentHistoryRepository = AppDataSource.getRepository(
ProfileEmployeeEmploymentHistory,
);
2025-01-06 23:58:24 +07:00
private profileEducationRepo = AppDataSource.getRepository(ProfileEducation);
2024-07-12 14:04:00 +07:00
private profileInsigniaRepo = AppDataSource.getRepository(ProfileInsignia);
private profileLeaveRepository = AppDataSource.getRepository(ProfileLeave);
2024-11-06 10:32:02 +07:00
private positionRepository = AppDataSource.getRepository(Position);
2025-02-18 23:02:38 +07:00
private employeePositionRepository = AppDataSource.getRepository(EmployeePosition);
2025-03-26 15:23:18 +07:00
private permissionProflileRepository = AppDataSource.getRepository(PermissionProfile);
2025-05-02 09:39:53 +07:00
private profileChildrenRepository = AppDataSource.getRepository(ProfileChildren);
private changeNameRepository = AppDataSource.getRepository(ProfileChangeName);
private profileActpositionRepo = AppDataSource.getRepository(ProfileActposition);
private dutyRepository = AppDataSource.getRepository(ProfileDuty);
private profileAssessmentsRepository = AppDataSource.getRepository(ProfileAssessment);
private profileAbilityRepo = AppDataSource.getRepository(ProfileAbility);
private profileAssistanceRepository = AppDataSource.getRepository(ProfileAssistance);
2024-11-06 10:32:02 +07:00
// Services
private profileLeaveService = new ProfileLeaveService();
/**
* report
*
* @summary report
*
* @param {string} id Id
*/
@Get("kp7-short/{id}")
async kp7ShortById(@Path() id: string, @Request() req: RequestWithUser) {
const orgRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
const profile = await this.profileRepo.findOne({
relations: [
"profileSalary",
"profileEducations",
"current_holders",
"current_holders.orgRoot",
"current_holders.orgChild1",
"current_holders.orgChild2",
"current_holders.orgChild3",
"current_holders.orgChild4",
],
where: { id: id },
2024-09-05 09:36:53 +07:00
order: {
profileSalary: {
commandDateAffect: "DESC",
2024-09-26 18:11:59 +07:00
},
},
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_EMP");
2024-11-15 09:29:24 +07:00
if (_workflow == false && req.user.sub != profile.keycloak)
2024-10-22 08:20:45 +07:00
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profile.id);
2024-09-26 18:11:59 +07:00
let ImgUrl: any;
if (profile?.avatar != null && profile?.avatarName != null) {
2024-09-30 13:18:02 +07:00
// await new CallAPI()
// .GetData(req, `/salary/file/${profile?.avatar}/${profile?.avatarName}`)
// .then(async (x) => {
// ImgUrl = x.downloadUrl;
// })
// .catch();
let req_: any = req;
const token_ = "Bearer " + req_.headers.authorization.replace("Bearer ", "");
const url = process.env.API_URL + `/salary/file/${profile?.avatar}/${profile?.avatarName}`;
try {
const response_ = await axios.get(url, {
headers: {
Authorization: `${token_}`,
"Content-Type": "application/json",
api_key: process.env.API_KEY,
},
});
ImgUrl = response_.data.downloadUrl;
2024-10-04 15:35:14 +07:00
} catch {}
2024-09-23 11:48:10 +07:00
}
const province = await this.provinceRepository.findOneBy({
id: profile.registrationProvinceId,
});
const district = await this.districtRepository.findOneBy({
id: profile.registrationDistrictId,
});
const subDistrict = await this.subDistrict.findOneBy({ id: profile.registrationSubDistrictId });
const root =
profile.current_holders == null ||
profile.current_holders.length == 0 ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot;
const child1 =
profile.current_holders == null ||
profile.current_holders.length == 0 ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1;
const child2 =
profile.current_holders == null ||
profile.current_holders.length == 0 ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2;
const child3 =
profile.current_holders == null ||
profile.current_holders.length == 0 ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3;
const child4 =
profile.current_holders == null ||
profile.current_holders.length == 0 ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4;
2024-05-24 01:11:47 +07:00
let _regisAddres =
profile && profile.registrationAddress != null ? profile.registrationAddress : "";
let _subDistrict =
subDistrict && subDistrict.name != null ? `\r\nตำบล/แขวง ${province?.name}` : "";
let _district = district && district.name != null ? `\r\nเขต/อำเภอ ${district?.name}` : "";
let _province = province && province.name != null ? `\r\nจังหวัด ${province?.name}` : "";
let registrationZipCode =
profile && profile.registrationZipCode != null
? ` รหัสไปรษณีย์ ${profile.registrationZipCode}`
: "";
2025-04-05 19:21:50 +07:00
2025-04-04 09:52:59 +07:00
let _root = root?.orgRootName;
2025-04-05 19:21:50 +07:00
let _child1 = child1?.orgChild1Name;
let _child2 = child2?.orgChild2Name;
let _child3 = child3?.orgChild3Name;
let _child4 = child4?.orgChild4Name;
2025-01-13 14:40:07 +07:00
const salary_raw = await this.salaryRepo.find({
// select: [
// "commandDateAffect",
// "posNo",
// "positionType",
// "positionLevel",
// "positionSalaryAmount",
// "commandNo",
// "amount",
// "remark",
// "positionName",
// "orgRoot",
// "orgChild1",
// "orgChild2",
// "orgChild3",
// "orgChild4",
// "positionCee",
// "positionExecutive",
// ],
where: {
profileEmployeeId: id,
commandCode: In(["1", "2", "3", "4", "8", "10", "11", "12", "15", "16"]),
},
order: { order: "ASC" },
2025-01-13 14:40:07 +07:00
});
const salarys =
salary_raw.length > 1
? salary_raw.slice(1).map((item) => ({
date: item.commandDateAffect
? Extension.ToThaiNumber(Extension.ToThaiShortDate(item.commandDateAffect))
: null,
position: Extension.ToThaiNumber(
Extension.ToThaiNumber(
`${item.positionName != null ? item.positionName : "-"} ${item.positionType == null ? item.positionCee ?? "" : (item.positionType == "อำนวยการ" || item.positionType == "บริหาร" ? item.positionType : "") + item.positionLevel}`,
),
),
posNo: item.posNo != null ? Extension.ToThaiNumber(item.posNo) : "",
orgRoot: item.orgRoot != null ? Extension.ToThaiNumber(item.orgRoot) : "",
orgChild1: item.orgChild1 != null ? Extension.ToThaiNumber(item.orgChild1) : "",
orgChild2: item.orgChild2 != null ? Extension.ToThaiNumber(item.orgChild2) : "",
orgChild3: item.orgChild3 != null ? Extension.ToThaiNumber(item.orgChild3) : "",
orgChild4: item.orgChild4 != null ? Extension.ToThaiNumber(item.orgChild4) : "",
positionCee: item.positionCee != null ? Extension.ToThaiNumber(item.positionCee) : "",
positionExecutive:
item.positionExecutive != null ? Extension.ToThaiNumber(item.positionExecutive) : "",
2025-01-13 14:40:07 +07:00
}))
: [
{
date: "-",
position: "-",
posNo: "-",
orgRoot: null,
orgChild1: null,
orgChild2: null,
orgChild3: null,
orgChild4: null,
positionCee: null,
2025-01-13 14:40:07 +07:00
positionExecutive: null,
},
];
2025-01-06 23:58:24 +07:00
const educations = await this.profileEducationRepo.find({
2024-09-05 09:36:53 +07:00
select: ["startDate", "endDate", "educationLevel", "degree", "field", "institute"],
where: { profileEmployeeId: id },
2025-01-06 23:58:24 +07:00
order: { level: "ASC" },
2024-09-05 09:36:53 +07:00
});
2024-11-14 18:03:56 +07:00
const Education =
educations && educations.length > 0
? educations.map((item) => ({
institute: item.institute ? item.institute : "-",
date:
item.startDate && item.endDate
? `${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate))} - ${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate))}`
: "-",
degree: item.degree && item.field ? `${item.degree} ${item.field}` : "-",
}))
: [
{
institute: "-",
date: "-",
degree: "-",
},
];
2024-09-05 09:36:53 +07:00
const mapData = {
// Id: profile.id,
fullName: `${profile?.prefix}${profile?.firstName} ${profile?.lastName}`,
prefix: profile.prefix != null ? profile.prefix : null,
firstName: profile.firstName != null ? profile.firstName : null,
lastName: profile.lastName != null ? profile.lastName : null,
2025-01-13 14:40:07 +07:00
citizenId: profile.citizenId != null ? Extension.ToThaiNumber(profile.citizenId) : "",
dateOfBirth:
2024-05-24 01:11:47 +07:00
profile.birthDate != null
? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear2(profile.birthDate))
2025-01-13 14:40:07 +07:00
: "",
dateRetire:
2024-05-24 01:11:47 +07:00
profile.dateRetire != null
? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear2(profile.dateRetire))
2025-01-13 14:40:07 +07:00
: "",
salaryAmount:
2025-01-14 18:49:41 +07:00
profile.amount != null ? Extension.ToThaiNumber(profile.amount.toLocaleString()) : "",
registrationAddress: Extension.ToThaiNumber(
2024-11-06 10:32:02 +07:00
`${_regisAddres}${_subDistrict}${_district}${_province}${registrationZipCode}`,
),
2025-01-14 18:49:41 +07:00
date:
salary_raw.length > 0 && salary_raw[0].commandDateAffect != null
? Extension.ToThaiNumber(Extension.ToThaiShortDate(salary_raw[0].commandDateAffect))
2025-01-13 14:40:07 +07:00
: "",
positionName: profile.position != null ? profile.position : "",
appointText:
profile.dateAppoint != null
? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear(profile.dateAppoint))
2025-01-13 14:40:07 +07:00
: "",
posNo:
salary_raw.length > 0 && salary_raw[0].posNo != null
? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].posNo))
: "",
position:
salary_raw.length > 0 && salary_raw[0].positionName != null
? Extension.ToThaiNumber(
Extension.ToThaiNumber(
`${salary_raw[0].positionName != null ? salary_raw[0].positionName : "-"} ${salary_raw[0].positionType == null ? salary_raw[0].positionCee ?? "" : (salary_raw[0].positionType == "อำนวยการ" || salary_raw[0].positionType == "บริหาร" ? salary_raw[0].positionType : "") + salary_raw[0].positionLevel}`,
),
)
2025-01-13 14:40:07 +07:00
: "",
positionCee:
salary_raw.length > 0 && salary_raw[0].positionCee != null
? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].positionCee))
2025-01-13 14:40:07 +07:00
: "",
positionExecutive:
salary_raw.length > 0 && salary_raw[0].positionExecutive != null
? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].positionExecutive))
: "",
org: `${
salary_raw.length > 0 && salary_raw[0].orgChild4 && salary_raw[0].orgChild4 != "-"
? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgChild4)) + " "
: ""
}${
salary_raw.length > 0 && salary_raw[0].orgChild3 && salary_raw[0].orgChild3 != "-"
? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgChild3)) + " "
: ""
}${
salary_raw.length > 0 && salary_raw[0].orgChild2 && salary_raw[0].orgChild2 != "-"
? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgChild2)) + " "
: ""
}${
salary_raw.length > 0 && salary_raw[0].orgChild1 && salary_raw[0].orgChild1 != "-"
? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgChild1)) + " "
: ""
}${
salary_raw.length > 0 && salary_raw[0].orgRoot && salary_raw[0].orgRoot != "-"
? Extension.ToThaiNumber(Extension.ToThaiNumber(salary_raw[0].orgRoot))
: ""
}`,
2025-04-05 19:21:50 +07:00
ocFullPath:
(_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root),
educations: Education,
2025-01-13 14:40:07 +07:00
salarys: salarys.map((item) => {
return {
...item,
org: `${item.orgChild4 && item.orgChild4 != "-" ? item.orgChild4 + " " : ""}${item.orgChild3 && item.orgChild3 != "-" ? item.orgChild3 + " " : ""}${item.orgChild2 && item.orgChild2 != "-" ? item.orgChild2 + " " : ""}${item.orgChild1 && item.orgChild1 != "-" ? item.orgChild1 + " " : ""}${item.orgRoot && item.orgRoot != "-" ? item.orgRoot + " " : ""}`,
};
}),
2024-12-26 22:23:12 +07:00
url: ImgUrl ? ImgUrl : `${process.env.VITE_URL_MGT}`,
};
return new HttpSuccess({
template: "kp7",
reportName: "docx-report",
data: mapData,
});
}
2024-05-24 15:57:29 +07:00
/**
2024-07-12 14:04:00 +07:00
* ..1 ()
*
* @summary ..1 ()
*
* @param {string} id Id
2024-05-24 15:57:29 +07:00
*/
2025-05-02 09:39:53 +07:00
@Get("old/{id}")
public async getKk1Employee(@Path() id: string, @Request() req: RequestWithUser) {
2024-05-24 15:57:29 +07:00
const profiles = await this.profileRepo.findOne({
2024-10-30 20:30:50 +07:00
relations: ["currentSubDistrict", "currentDistrict", "currentProvince", "profileAvatars"],
order: {
2024-10-31 12:53:45 +07:00
profileAvatars: { createdAt: "ASC" },
2024-10-30 20:30:50 +07:00
},
2024-05-24 15:57:29 +07:00
where: { id: id },
});
2024-09-23 11:48:10 +07:00
if (!profiles) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
2024-11-15 09:29:24 +07:00
let ImgUrl: any = null;
2024-10-30 20:30:50 +07:00
let _ImgUrl: any = [];
2024-09-26 18:11:59 +07:00
if (profiles?.avatar != null && profiles?.avatarName != null) {
2024-09-30 13:18:02 +07:00
// await new CallAPI()
// .GetData(req, `/salary/file/${profiles?.avatar}/${profiles?.avatarName}`)
// .then(async (x) => {
// ImgUrl = x.downloadUrl;
// })
// .catch();
2024-11-15 09:29:24 +07:00
2024-09-30 13:18:02 +07:00
let req_: any = req;
const token_ = "Bearer " + req_.headers.authorization.replace("Bearer ", "");
2024-10-30 20:30:50 +07:00
await Promise.all(
await profiles.profileAvatars.slice(-7).map(async (x, i) => {
if (x == null) {
_ImgUrl[i] = null;
} else {
const url = process.env.API_URL + `/salary/file/${x?.avatar}/${x?.avatarName}`;
try {
const response_ = await axios.get(url, {
headers: {
Authorization: `${token_}`,
"Content-Type": "application/json",
api_key: process.env.API_KEY,
},
});
_ImgUrl[i] = response_.data.downloadUrl;
} catch {}
}
}),
);
2024-09-30 13:18:02 +07:00
const url = process.env.API_URL + `/salary/file/${profiles?.avatar}/${profiles?.avatarName}`;
try {
const response_ = await axios.get(url, {
headers: {
Authorization: `${token_}`,
"Content-Type": "application/json",
api_key: process.env.API_KEY,
},
});
ImgUrl = response_.data.downloadUrl;
2024-10-04 15:35:14 +07:00
} catch {}
2024-09-23 11:48:10 +07:00
}
2024-05-24 15:57:29 +07:00
const profileOc = await this.profileRepo.findOne({
relations: [
"current_holders",
"current_holders.orgRoot",
"current_holders.orgChild1",
"current_holders.orgChild2",
"current_holders.orgChild3",
"current_holders.orgChild4",
],
where: { id: id },
});
if (!profileOc) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const orgRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
const profileFamilyCouple = await this.profileFamilyCoupleRepository.findOne({
where: { profileEmployeeId: id },
2024-07-12 14:04:00 +07:00
select: ["couplePrefix", "coupleFirstName", "coupleLastName", "coupleLastNameOld"],
order: { lastUpdatedAt: "DESC" },
2024-05-24 15:57:29 +07:00
});
const profileFamilyMother = await this.profileFamilyMotherRepository.findOne({
where: { profileEmployeeId: id },
2024-05-24 15:57:29 +07:00
select: ["motherPrefix", "motherFirstName", "motherLastName"],
2024-07-12 14:04:00 +07:00
order: { lastUpdatedAt: "DESC" },
2024-05-24 15:57:29 +07:00
});
const profileFamilyFather = await this.profileFamilyFatherRepository.findOne({
where: { profileEmployeeId: id },
2024-05-24 15:57:29 +07:00
select: ["fatherPrefix", "fatherFirstName", "fatherLastName"],
2024-07-12 14:04:00 +07:00
order: { lastUpdatedAt: "DESC" },
2024-05-24 15:57:29 +07:00
});
const root =
profileOc.current_holders == null ||
profileOc.current_holders.length == 0 ||
profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot;
const child1 =
profileOc.current_holders == null ||
profileOc.current_holders.length == 0 ||
profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1;
const child2 =
profileOc.current_holders == null ||
profileOc.current_holders.length == 0 ||
profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2;
const child3 =
profileOc.current_holders == null ||
profileOc.current_holders.length == 0 ||
profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3;
const child4 =
profileOc.current_holders == null ||
profileOc.current_holders.length == 0 ||
profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4;
// Construct org path
2025-04-04 10:07:34 +07:00
let _root = root?.orgRootName;
2025-04-05 19:21:50 +07:00
let _child1 = child1?.orgChild1Name;
let _child2 = child2?.orgChild2Name;
let _child3 = child3?.orgChild3Name;
let _child4 = child4?.orgChild4Name;
2024-05-24 15:57:29 +07:00
const cert_raw = await this.certificateRepository.find({
2024-05-24 15:57:29 +07:00
where: { profileEmployeeId: id },
select: ["certificateType", "issuer", "certificateNo", "issueDate"],
order: { createdAt: "ASC" },
2024-05-24 15:57:29 +07:00
});
const certs =
cert_raw.length > 0
2024-11-06 10:32:02 +07:00
? cert_raw.slice(-2).map((item) => ({
2024-09-26 18:11:59 +07:00
CertificateType: item.certificateType ?? null,
Issuer: item.issuer ?? null,
CertificateNo: Extension.ToThaiNumber(item.certificateNo) ?? null,
IssueDate: Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.issueDate)) ?? null,
}))
: [
{
CertificateType: "-",
Issuer: "-",
CertificateNo: "-",
IssueDate: "-",
},
];
const training_raw = await this.trainingRepository.find({
2024-05-24 15:57:29 +07:00
select: ["startDate", "endDate", "place", "department"],
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
2024-05-24 15:57:29 +07:00
});
const trainings =
training_raw.length > 0
? training_raw.slice(-2).map((item) => ({
2024-09-26 18:11:59 +07:00
Institute: item.department ?? "",
Start:
item.startDate == null
? ""
: Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate)),
End:
item.endDate == null
? ""
: Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate)),
Date:
item.startDate && item.endDate
? `${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate))} - ${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate))}`
: "",
Level: "",
Degree: item.name,
Field: "",
}))
: [
{
Institute: "-",
Start: "-",
End: "-",
Date: "-",
Level: "-",
Degree: "-",
Field: "-",
},
];
2024-05-24 15:57:29 +07:00
const discipline_raw = await this.disciplineRepository.find({
2024-05-24 15:57:29 +07:00
select: ["refCommandDate", "refCommandNo", "detail"],
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
2024-05-24 15:57:29 +07:00
});
const disciplines =
discipline_raw.length > 0
? discipline_raw.slice(-2).map((item) => ({
2024-09-26 18:11:59 +07:00
DisciplineYear:
Extension.ToThaiNumber(new Date(item.refCommandDate).getFullYear().toString()) ??
null,
DisciplineDetail: item.detail ?? null,
2025-05-01 13:35:54 +07:00
RefNo: item.refCommandNo ? Extension.ToThaiNumber(item.refCommandNo) : null,
2024-09-26 18:11:59 +07:00
}))
: [
{
DisciplineYear: "-",
DisciplineDetail: "-",
RefNo: "-",
},
];
2024-05-24 15:57:29 +07:00
2025-01-06 23:58:24 +07:00
const education_raw = await this.profileEducationRepo.find({
2024-05-24 15:57:29 +07:00
select: ["startDate", "endDate", "educationLevel", "degree", "field", "institute"],
where: { profileEmployeeId: id },
// order: { lastUpdatedAt: "DESC" },
2025-01-06 23:58:24 +07:00
order: { level: "ASC" },
2024-05-24 15:57:29 +07:00
});
const educations =
education_raw.length > 0
? education_raw.slice(-2).map((item) => ({
2024-09-26 18:11:59 +07:00
Institute: item.institute,
Start:
item.startDate == null
? ""
: Extension.ToThaiNumber(new Date(item.startDate).getFullYear().toString()),
End:
item.endDate == null
? ""
: Extension.ToThaiNumber(new Date(item.endDate).getFullYear().toString()),
Date:
item.startDate && item.endDate
? `${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate))} - ${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate))}`
: "",
Level: item.educationLevel ?? "",
Degree: item.degree ? `${item.degree} ${item.field ? item.field : ""}` : "",
Field: item.field ?? "-",
}))
: [
{
Institute: "-",
Start: "-",
End: "-",
Date: "-",
Level: "-",
Degree: "-",
Field: "-",
},
];
2025-01-08 14:15:28 +07:00
const salary_raw = await this.salaryRepo.find({
2024-05-24 15:57:29 +07:00
select: [
"commandDateAffect",
"positionName",
2024-05-24 15:57:29 +07:00
"posNo",
"positionType",
"positionLevel",
"positionSalaryAmount",
"commandNo",
2024-07-12 14:04:00 +07:00
"amount",
"remark",
2024-05-24 15:57:29 +07:00
],
where: { profileEmployeeId: id },
2024-09-26 18:11:59 +07:00
order: { order: "ASC" },
2024-05-24 15:57:29 +07:00
});
const salarys =
salary_raw.length > 0
? salary_raw.map((item) => ({
SalaryDate: item.commandDateAffect
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
2024-09-26 18:11:59 +07:00
: null,
Position: item.positionName != null ? Extension.ToThaiNumber(item.positionName) : null,
2024-09-26 18:11:59 +07:00
PosNo: item.posNo != null ? Extension.ToThaiNumber(item.posNo) : null,
Salary:
item.amount != null ? Extension.ToThaiNumber(item.amount.toLocaleString()) : null,
Rank: item.positionLevel != null ? Extension.ToThaiNumber(item.positionLevel) : null,
RefAll: item.remark ? Extension.ToThaiNumber(item.remark) : null,
2024-09-26 18:11:59 +07:00
PositionLevel:
item.positionLevel != null ? Extension.ToThaiNumber(item.positionLevel) : null,
PositionType: item.positionType ?? null,
PositionAmount:
item.positionSalaryAmount == null
? null
: Extension.ToThaiNumber(item.positionSalaryAmount.toLocaleString()),
FullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`,
2025-04-05 19:21:50 +07:00
OcFullPath:
(_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root),
2024-09-26 18:11:59 +07:00
}))
: [
{
SalaryDate: "-",
Position: "-",
PosNo: "-",
Salary: "-",
Rank: "-",
RefAll: "-",
PositionLevel: "-",
PositionType: "-",
PositionAmount: "-",
FullName: "-",
OcFullPath: "-",
},
];
2024-07-12 14:04:00 +07:00
const insignia_raw = await this.profileInsigniaRepo.find({
2024-07-12 14:04:00 +07:00
relations: {
insignia: {
insigniaType: true,
},
},
where: { profileEmployeeId: id },
order: { receiveDate: "ASC" },
});
const insignias =
insignia_raw.length > 0
? insignia_raw.map((item) => ({
2024-09-26 18:11:59 +07:00
ReceiveDate: item.receiveDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.receiveDate))
: "",
InsigniaName: item.insignia.name,
InsigniaShortName: item.insignia.shortName,
InsigniaTypeName: item.insignia.insigniaType.name,
No: item.no ? Extension.ToThaiNumber(item.no) : "",
Issue: item.issue ? item.issue : "",
VolumeNo: item.volumeNo ? Extension.ToThaiNumber(item.volumeNo) : "",
Volume: item.volume ? Extension.ToThaiNumber(item.volume) : "",
Section: item.section ? Extension.ToThaiNumber(item.section) : "",
Page: item.page ? Extension.ToThaiNumber(item.page) : "",
RefCommandDate: item.refCommandDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.refCommandDate))
: "",
}))
: [
{
ReceiveDate: "-",
InsigniaName: "-",
InsigniaShortName: "-",
InsigniaTypeName: "-",
No: "-",
Issue: "-",
VolumeNo: "-",
Volume: "-",
Section: "-",
Page: "-",
RefCommandDate: "-",
},
];
2024-07-12 14:04:00 +07:00
const leave_raw = await this.profileLeaveRepository.find({
2024-07-12 14:04:00 +07:00
relations: { leaveType: true },
where: { profileEmployeeId: id },
order: { dateLeaveStart: "ASC" },
});
const leaves =
leave_raw.length > 0
? leave_raw.map((item) => ({
2024-09-26 18:11:59 +07:00
LeaveTypeName: item.leaveType.name,
DateLeaveStart: item.dateLeaveStart
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateLeaveStart))
: "",
LeaveDays: item.leaveDays ? Extension.ToThaiNumber(item.leaveDays.toString()) : "",
}))
: [
{
LeaveTypeName: "-",
DateLeaveStart: "-",
LeaveDays: "-",
},
];
2024-07-12 14:04:00 +07:00
2024-11-06 10:32:02 +07:00
const data = {
fullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`,
prefix: profiles?.prefix != null ? profiles.prefix : "",
firstName: profiles?.firstName != null ? profiles.firstName : "",
lastName: profiles?.lastName != null ? profiles.lastName : "",
2025-04-05 19:21:50 +07:00
ocFullPath:
(_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root),
2024-11-06 10:32:02 +07:00
birthDate: profiles?.birthDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.birthDate))
: "",
retireDate:
profiles.dateRetireLaw != null
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateRetireLaw))
: "",
appointDate: profiles?.dateAppoint
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateAppoint))
: "",
citizenId:
profiles.citizenId != null ? Extension.ToThaiNumber(profiles.citizenId.toString()) : "",
fatherFullName:
profileFamilyFather?.fatherPrefix ||
profileFamilyFather?.fatherFirstName ||
profileFamilyFather?.fatherLastName
? `${profileFamilyFather?.fatherPrefix ?? ""}${profileFamilyFather?.fatherFirstName ?? ""} ${profileFamilyFather?.fatherLastName ?? ""}`.trim()
: null,
motherFullName:
profileFamilyMother?.motherPrefix ||
profileFamilyMother?.motherFirstName ||
profileFamilyMother?.motherLastName
? `${profileFamilyMother?.motherPrefix ?? ""}${profileFamilyMother?.motherFirstName ?? ""} ${profileFamilyMother?.motherLastName ?? ""}`.trim()
: null,
coupleFullName:
profileFamilyCouple?.couplePrefix ||
profileFamilyCouple?.coupleFirstName ||
profileFamilyCouple?.coupleLastNameOld
? `${profileFamilyCouple?.couplePrefix ?? ""}${profileFamilyCouple?.coupleFirstName ?? ""} ${profileFamilyCouple?.coupleLastName ?? ""}`.trim()
: null,
coupleLastNameOld: profileFamilyCouple?.coupleLastNameOld ?? null,
currentAddress:
profiles.currentAddress != null ? Extension.ToThaiNumber(profiles.currentAddress) : "",
currentSubDistrict:
profiles.currentSubDistrict != null
? Extension.ToThaiNumber(profiles.currentSubDistrict.name)
: "",
currentDistrict:
profiles.currentDistrict != null
? Extension.ToThaiNumber(profiles.currentDistrict.name)
: "",
currentProvince:
profiles.currentProvince != null
? Extension.ToThaiNumber(profiles.currentProvince.name)
: "",
2025-04-05 19:21:50 +07:00
telephone: profiles.telephoneNumber != null ? Extension.ToThaiNumber(profiles.phone) : "",
2024-12-26 22:23:12 +07:00
url: ImgUrl ? ImgUrl : `${process.env.VITE_URL_MGT}`,
2024-11-06 10:32:02 +07:00
url1: _ImgUrl[0] ? _ImgUrl[0] : null,
yearUpload1: profiles.profileAvatars[0]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[0].createdAt))
: null,
url2: _ImgUrl[1] ? _ImgUrl[1] : null,
yearUpload2: profiles.profileAvatars[1]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[1].createdAt))
: null,
url3: _ImgUrl[2] ? _ImgUrl[2] : null,
yearUpload3: profiles.profileAvatars[2]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[2].createdAt))
: null,
url4: _ImgUrl[3] ? _ImgUrl[3] : null,
yearUpload4: profiles.profileAvatars[3]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[3].createdAt))
: null,
url5: _ImgUrl[4] ? _ImgUrl[4] : null,
yearUpload5: profiles.profileAvatars[4]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[4].createdAt))
: null,
url6: _ImgUrl[5] ? _ImgUrl[5] : null,
yearUpload6: profiles.profileAvatars[5]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[5].createdAt))
: null,
url7: _ImgUrl[6] ? _ImgUrl[6] : null,
yearUpload7: profiles.profileAvatars[6]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[6].createdAt))
: null,
insignias,
leaves,
certs,
trainings,
disciplines,
educations,
salarys,
};
return new HttpSuccess({
template: "kk1-emp",
reportName: "docx-report",
data: data,
});
2024-05-24 15:57:29 +07:00
}
2025-05-02 09:39:53 +07:00
/**
* ..1 ()
*
* @summary ..1 ()
*
* @param {string} id Id
*/
@Get("kk1/{id}")
public async getKk1new(@Path() id: string, @Request() req: RequestWithUser) {
const profiles = await this.profileRepo.findOne({
relations: [
"currentSubDistrict",
"currentDistrict",
"currentProvince",
"registrationSubDistrict",
"registrationDistrict",
"registrationProvince",
"profileAvatars",
"current_holders",
"current_holders.orgRoot",
"current_holders.orgChild1",
"current_holders.orgChild2",
"current_holders.orgChild3",
"current_holders.orgChild4",
],
order: {
profileAvatars: { createdAt: "ASC" },
},
where: { id: id },
});
if (!profiles) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
let ImgUrl: any = null;
let _ImgUrl: any = [];
if (profiles?.avatar != null && profiles?.avatarName != null) {
let req_: any = req;
const token_ = "Bearer " + req_.headers.authorization.replace("Bearer ", "");
await Promise.all(
await profiles.profileAvatars.slice(-7).map(async (x, i) => {
if (x == null) {
_ImgUrl[i] = null;
} else {
const url = process.env.API_URL + `/salary/file/${x?.avatar}/${x?.avatarName}`;
try {
const response_ = await axios.get(url, {
headers: {
Authorization: `${token_}`,
"Content-Type": "application/json",
api_key: process.env.API_KEY,
},
});
_ImgUrl[i] = response_.data.downloadUrl;
} catch {}
}
}),
);
const url = process.env.API_URL + `/salary/file/${profiles?.avatar}/${profiles?.avatarName}`;
try {
const response_ = await axios.get(url, {
headers: {
Authorization: `${token_}`,
"Content-Type": "application/json",
api_key: process.env.API_KEY,
},
});
ImgUrl = response_.data.downloadUrl;
} catch {}
}
const orgRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
const profileFamilyCouple = await this.profileFamilyCoupleRepository.findOne({
where: { profileEmployeeId: id },
select: ["couplePrefix", "coupleFirstName", "coupleLastName", "coupleLastNameOld"],
order: { lastUpdatedAt: "DESC" },
});
const profileFamilyMother = await this.profileFamilyMotherRepository.findOne({
where: { profileEmployeeId: id },
select: ["motherPrefix", "motherFirstName", "motherLastName"],
order: { lastUpdatedAt: "DESC" },
});
const profileFamilyFather = await this.profileFamilyFatherRepository.findOne({
where: { profileEmployeeId: id },
select: ["fatherPrefix", "fatherFirstName", "fatherLastName"],
order: { lastUpdatedAt: "DESC" },
});
const root =
profiles.current_holders == null ||
profiles.current_holders.length == 0 ||
profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot;
const child1 =
profiles.current_holders == null ||
profiles.current_holders.length == 0 ||
profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1;
const child2 =
profiles.current_holders == null ||
profiles.current_holders.length == 0 ||
profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2;
const child3 =
profiles.current_holders == null ||
profiles.current_holders.length == 0 ||
profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3;
const child4 =
profiles.current_holders == null ||
profiles.current_holders.length == 0 ||
profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null
? null
: profiles.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4;
// Construct org path
let _root = root?.orgRootName;
let _child1 = child1?.orgChild1Name;
let _child2 = child2?.orgChild2Name;
let _child3 = child3?.orgChild3Name;
let _child4 = child4?.orgChild4Name;
const cert_raw = await this.certificateRepository.find({
where: { profileEmployeeId: id },
select: ["certificateType", "issuer", "certificateNo", "issueDate"],
order: { createdAt: "ASC" },
});
const certs =
cert_raw.length > 0
? cert_raw.map((item) => ({
certificateType: item.certificateType ?? null,
issuer: item.issuer ?? null,
certificateNo: item.certificateNo ? Extension.ToThaiNumber(item.certificateNo) : null,
issueDate: item.issueDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.issueDate))
: null,
expireDate: item.expireDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.expireDate))
: null,
issueToExpireDate: item.issueDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.issueDate))
: "" + item.expireDate
? " - " + Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.expireDate))
: null,
}))
: [
{
certificateType: "-",
issuer: "-",
certificateNo: "-",
issueDate: "-",
expireDate: "-",
issueToExpireDate: "-",
},
];
const training_raw = await this.trainingRepository.find({
select: ["place", "department", "name", "duration"],
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const trainings =
training_raw.length > 0
? training_raw.map((item) => ({
institute: item.department ?? "",
degree: item.name ? Extension.ToThaiNumber(item.name) : "",
place: item.place ? Extension.ToThaiNumber(item.place) : "",
duration: item.duration ? Extension.ToThaiNumber(item.duration) : "",
}))
: [
{
institute: "-",
degree: "-",
place: "-",
duration: "-",
},
];
const discipline_raw = await this.disciplineRepository.find({
select: ["refCommandDate", "refCommandNo", "detail", "level"],
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const disciplines =
discipline_raw.length > 0
? discipline_raw.map((item) => ({
disciplineYear: item.refCommandDate
2025-05-13 11:48:45 +07:00
? Extension.ToThaiNumber(Extension.ToThaiShortYear(new Date(item.refCommandDate)))
2025-05-02 09:39:53 +07:00
: null,
disciplineDetail: item.detail ?? null,
refNo: Extension.ToThaiNumber(item.refCommandNo) ?? null,
2025-09-08 00:10:59 +07:00
level: item.level ?? "",
2025-05-02 09:39:53 +07:00
}))
: [
{
disciplineYear: "-",
disciplineDetail: "-",
refNo: "-",
2025-09-08 00:10:59 +07:00
level: "-",
2025-05-02 09:39:53 +07:00
},
];
const education_raw = await this.profileEducationRepo
.createQueryBuilder("education")
.where("education.profileEmployeeId = :profileId", { profileId: id })
.orderBy("CASE WHEN education.isEducation = true THEN 1 ELSE 2 END", "ASC")
.addOrderBy("education.level", "ASC")
.getMany();
const educations =
education_raw.length > 0
? education_raw.map((item) => ({
institute: item.institute,
date: item.isDate
2025-05-13 11:48:45 +07:00
? `${item.startDate ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate)) : ""} - ${item.endDate ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate)) : ""}`
: `${item.startDate ? Extension.ToThaiNumber(Extension.ToThaiShortYear(new Date(item.startDate))) : ""} - ${item.endDate ? Extension.ToThaiNumber(Extension.ToThaiShortYear(new Date(item.endDate))) : ""}`,
2025-05-02 09:39:53 +07:00
degree: item.degree ? `${item.degree} ${item.field ? item.field : ""}` : "",
}))
: [
{
institute: "-",
date: "-",
degree: "-",
},
];
const salary_raw = await this.salaryRepo.find({
where: {
profileEmployeeId: id,
commandCode: In(["5", "6"]),
2025-08-06 11:15:08 +07:00
// isEntry: false,
2025-05-02 09:39:53 +07:00
},
order: { order: "ASC" },
});
const salarys =
salary_raw.length > 0
? salary_raw.map((item) => ({
commandName: item.commandName ?? "",
2025-05-02 09:39:53 +07:00
salaryDate: item.commandDateAffect
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
: null,
position: item.positionName != null ? Extension.ToThaiNumber(item.positionName) : null,
posNo:
item.posNoAbb && item.posNo
? Extension.ToThaiNumber(`${item.posNoAbb}${item.posNo}`)
: null,
salary:
item.amount != null ? Extension.ToThaiNumber(item.amount.toLocaleString()) : null,
special:
2025-09-08 00:10:59 +07:00
item.amountSpecial != null
? Extension.ToThaiNumber(item.amountSpecial.toLocaleString())
: null,
2025-05-02 09:39:53 +07:00
rank: item.positionLevel != null ? Extension.ToThaiNumber(item.positionLevel) : null,
refAll: item.remark ? Extension.ToThaiNumber(item.remark) : null,
2025-05-13 13:07:52 +07:00
positionLevel: item.positionLevel
? Extension.ToThaiNumber(item.positionLevel)
: item.positionCee
? Extension.ToThaiNumber(item.positionCee)
: null,
2025-05-02 09:39:53 +07:00
positionType: item.positionType ?? null,
positionAmount:
item.positionSalaryAmount == null
? null
: Extension.ToThaiNumber(item.positionSalaryAmount.toLocaleString()),
fullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`,
ocFullPath:
(_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root),
}))
: [
{
commandName: "-",
2025-05-02 09:39:53 +07:00
salaryDate: "-",
position: "-",
posNo: "-",
salary: "-",
special: "-",
2025-05-02 09:39:53 +07:00
rank: "-",
refAll: "-",
positionLevel: "-",
positionType: "-",
positionAmount: "-",
fullName: "-",
ocFullPath: "-",
},
];
const insignia_raw = await this.profileInsigniaRepo.find({
relations: {
insignia: {
insigniaType: true,
},
},
where: { profileEmployeeId: id },
order: { receiveDate: "ASC" },
});
const insignias =
insignia_raw.length > 0
? insignia_raw.map((item) => ({
receiveDate: item.receiveDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.receiveDate))
: "",
insigniaName: item.insignia.name,
insigniaShortName: item.insignia.shortName,
insigniaTypeName: item.insignia.insigniaType.name,
no: item.no ? Extension.ToThaiNumber(item.no) : "",
issue: item.issue ? Extension.ToThaiNumber(item.issue) : "",
volumeNo: item.volumeNo ? Extension.ToThaiNumber(item.volumeNo) : "",
volume: item.volume ? Extension.ToThaiNumber(item.volume) : "",
section: item.section ? Extension.ToThaiNumber(item.section) : "",
page: item.page ? Extension.ToThaiNumber(item.page) : "",
refCommandDate: item.refCommandDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.refCommandDate))
: "",
note: item.note ? Extension.ToThaiNumber(item.note) : "",
}))
: [
{
receiveDate: "-",
insigniaName: "-",
insigniaShortName: "-",
insigniaTypeName: "-",
no: "-",
issue: "-",
volumeNo: "-",
volume: "-",
section: "-",
page: "-",
refCommandDate: "-",
},
];
const leave_raw = await this.profileLeaveRepository
.createQueryBuilder("profileLeave")
.leftJoinAndSelect("profileLeave.leaveType", "leaveType")
.select([
"profileLeave.leaveTypeId",
"leaveType.name as name",
"leaveType.code as code",
"profileLeave.status",
"profileLeave.profileEmployeeId",
"MAX(profileLeave.dateLeaveStart) as maxDateLeaveStart",
])
.addSelect("SUM(profileLeave.leaveDays)", "totalLeaveDays")
.where("profileLeave.profileEmployeeId = :profileId", { profileId: id })
.andWhere("profileLeave.status = :status", { status: "approve" })
.groupBy("profileLeave.leaveTypeId")
.orderBy("code", "ASC")
.addOrderBy("maxDateLeaveStart", "ASC")
.getRawMany();
const leaves: any[] = [];
leave_raw.forEach((item) => {
const leaveTypeCode = item.code ? item.code.trim().toUpperCase() : "";
if (leaveTypeCode.startsWith("LV-")) {
const lvIndex = parseInt(leaveTypeCode.split("-")[1], 10);
if (lvIndex >= 1 && lvIndex <= 11) {
const leaveTypeCodeKey = `leaveTypeCodeLv${lvIndex}`;
const totalLeaveDaysKey = `totalLeaveDaysLv${lvIndex}`;
const leaveTypeNameKey = `leaveTypeNameLv${lvIndex}`;
const leaveDate = new Date(item.maxDateLeaveStart);
2025-05-13 11:48:45 +07:00
const year = leaveDate
? Extension.ToThaiNumber(Extension.ToThaiShortYear(leaveDate))
: "";
2025-05-02 09:39:53 +07:00
let yearData = leaves.find((data) => data.year === year);
if (!yearData) {
yearData = { year };
for (let i = 1; i <= 11; i++) {
yearData[`leaveTypeCodeLv${i}`] = "-";
yearData[`totalLeaveDaysLv${i}`] = "-";
yearData[`leaveTypeNameLv${i}`] = "-";
}
leaves.push(yearData);
}
yearData[leaveTypeCodeKey] = item.code ? item.code : "-";
yearData[totalLeaveDaysKey] = item.totalLeaveDays
? Extension.ToThaiNumber(item.totalLeaveDays.toString())
: "-";
yearData[leaveTypeNameKey] = item.name ? item.name : "-";
}
}
});
const leave2_raw = await this.profileLeaveRepository
.createQueryBuilder("profileLeave")
.leftJoinAndSelect("profileLeave.leaveType", "leaveType")
.select([
2025-08-06 11:15:08 +07:00
"profileLeave.dateLeaveStart AS dateLeaveStart",
"profileLeave.dateLeaveEnd AS dateLeaveEnd",
"profileLeave.leaveDays AS leaveDays",
"profileLeave.reason AS reason",
2025-09-08 00:10:59 +07:00
"leaveType.name as name",
2025-05-02 09:39:53 +07:00
])
.where("profileLeave.profileEmployeeId = :profileId", { profileId: id })
.andWhere("leaveType.code IN (:...codes)", { codes: ["LV-008", "LV-009", "LV-010"] })
.andWhere("profileLeave.status = :status", { status: "approve" })
.orderBy("leaveType.code", "ASC")
.getRawMany();
const leaves2 =
leave2_raw.length > 0
? leave2_raw.map((item) => ({
2025-09-08 00:10:59 +07:00
date:
item.dateLeaveStart && item.dateLeaveEnd
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateLeaveStart)) +
" - " +
Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateLeaveEnd))
: "-",
2025-05-02 09:39:53 +07:00
type: item.name || "-",
2025-08-06 11:15:08 +07:00
leaveDays: item.leaveDays ? Extension.ToThaiNumber(item.leaveDays.toString()) : "-",
2025-05-02 09:39:53 +07:00
reason: item.reason || "-",
}))
: [
{
date: "-",
type: "-",
leaveDays: "-",
reason: "-",
},
];
const children_raw = await this.profileChildrenRepository.find({
where: { profileEmployeeId: id },
});
const children =
children_raw.length > 0
? children_raw.map((item, index) => ({
no: Extension.ToThaiNumber((index + 1).toString()),
childrenPrefix: item.childrenPrefix,
childrenFirstName: item.childrenFirstName,
childrenLastName: item.childrenLastName,
childrenFullName: `${item.childrenPrefix}${item.childrenFirstName} ${item.childrenLastName}`,
2025-05-13 13:07:52 +07:00
childrenLive: item.childrenLive == false ? "ถึงแก่กรรม" : "มีชีวิต",
2025-05-02 09:39:53 +07:00
}))
: [
{
no: "",
childrenPrefix: "-",
childrenFirstName: "-",
childrenLastName: "-",
childrenFullName: "-",
childrenLive: "-",
},
];
const changeName_raw = await this.changeNameRepository.find({
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const changeName =
changeName_raw.length > 0
? changeName_raw.map((item) => ({
createdAt: item.createdAt
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.createdAt))
: null,
status: item.status,
prefix: item.prefix,
firstName: item.firstName,
lastName: item.lastName,
}))
: [
{
createdAt: "-",
status: "-",
prefix: "-",
firstName: "-",
lastName: "-",
},
];
const profileHistory = await this.profileHistoryRepo.find({
2025-09-08 00:10:59 +07:00
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const history =
profileHistory.length > 0
? profileHistory.map((item) => ({
birthDateOld: item.birthDateOld
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.birthDateOld))
: "",
birthDate: item.birthDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.birthDate))
: "",
}))
: [
{
birthDateOld: "-",
birthDate: "-",
},
];
2025-05-02 09:39:53 +07:00
const position_raw = await this.salaryRepo.find({
where: {
profileEmployeeId: id,
commandCode: In(["1", "2", "3", "4", "8", "10", "11", "12", "15", "16"]),
isEntry: false,
},
order: { order: "ASC" },
});
const positionList =
position_raw.length > 0
? position_raw.map((item) => ({
commandName: item.commandName ?? "",
2025-05-02 09:39:53 +07:00
commandDateAffect: item.commandDateAffect
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
: "",
commandDateSign: item.commandDateSign
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateSign))
: "",
posNo:
item.posNoAbb && item.posNo
? Extension.ToThaiNumber(`${item.posNoAbb} ${item.posNo}`)
2025-05-02 09:39:53 +07:00
: "",
position: item.positionName,
posType: item.positionType,
2025-05-13 13:07:52 +07:00
posLevel: item.positionLevel
? Extension.ToThaiNumber(item.positionLevel)
: item.positionCee
? Extension.ToThaiNumber(item.positionCee)
: null,
2025-05-02 09:39:53 +07:00
amount: item.amount ? Extension.ToThaiNumber(Number(item.amount).toLocaleString()) : "",
positionSalaryAmount: item.positionSalaryAmount
? Extension.ToThaiNumber(Number(item.positionSalaryAmount).toLocaleString())
: "",
}))
: [
{
commandName: "-",
2025-05-02 09:39:53 +07:00
commandDateAffect: "-",
commandDateSign: "-",
posNo: "-",
position: "-",
posType: "-",
posLevel: "-",
amount: "-",
positionSalaryAmount: "-",
},
];
const actposition_raw = await this.profileActpositionRepo.find({
select: ["dateStart", "dateEnd", "position"],
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const assistance_raw = await this.profileAssistanceRepository.find({
select: ["dateStart", "dateEnd", "commandName", "agency", "document"],
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const _actposition =
actposition_raw.length > 0
? actposition_raw.map((item) => ({
date: item.dateStart
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateStart))
: "" + item.dateEnd
? " - " + Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateEnd))
: "",
position: item.position ? Extension.ToThaiNumber(item.position) : "",
commandName: "รักษาการในตำแหน่ง",
agency: "",
document: "",
}))
: [
{
date: "-",
position: "-",
commandName: "-",
agency: "-",
document: "-",
},
];
const _assistance =
assistance_raw.length > 0
? assistance_raw.map((item) => ({
date: item.dateStart
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateStart))
: "" + item.dateEnd
? " - " + Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateEnd))
: "",
position: "",
commandName: item.commandName ? Extension.ToThaiNumber(item.commandName) : "",
agency: item.agency ? Extension.ToThaiNumber(item.agency) : "",
document: item.document ? Extension.ToThaiNumber(item.document) : "",
}))
: [
{
date: "-",
position: "-",
commandName: "-",
agency: "-",
document: "-",
},
];
const actposition = [..._actposition, ..._assistance];
const duty_raw = await this.dutyRepository.find({
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const duty =
duty_raw.length > 0
? duty_raw.map((item) => ({
date: item.dateStart
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateStart))
: "" + item.dateEnd
? " - " + Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateEnd))
: "",
refCommandDate: item.refCommandDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.refCommandDate))
: "",
refCommandNo: item.refCommandNo ? Extension.ToThaiNumber(item.refCommandNo) : "",
}))
: [
{
date: "-",
refCommandDate: "-",
refCommandNo: "-",
},
];
const assessments_raw = await this.profileAssessmentsRepository.find({
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const assessments =
assessments_raw.length > 0
? assessments_raw.map((item) => ({
2025-05-13 13:07:52 +07:00
year: item.year ? Extension.ToThaiNumber((parseInt(item.year) + 543).toString()) : "",
2025-05-02 09:39:53 +07:00
period: item.period && item.period == "APR" ? "เมษายน" : "ตุลาคม",
point1: item.point1 ? Extension.ToThaiNumber(item.point1.toString()) : "",
point1Total: item.point1Total
? Extension.ToThaiNumber(item.point1Total.toString())
: "",
point2: item.point2 ? Extension.ToThaiNumber(item.point2.toString()) : "",
point2Total: item.point2Total
? Extension.ToThaiNumber(item.point2Total.toString())
: "",
pointSum: item.pointSum ? Extension.ToThaiNumber(item.pointSum.toString()) : "",
pointSumTh: item.pointSum ? Extension.textPoint(item.pointSum) : "",
2025-09-08 00:10:59 +07:00
level:
item.pointSum < 60.0
? "ต้องปรับปรุง (คะแนนต่ำกว่าร้อยละ ๖๐.)"
: item.pointSum <= 69.99 && item.pointSum >= 60.0
? "พอใช้ (คะแนนร้อยละ ๖๐. - ๖๙.๙๙)"
: item.pointSum <= 79.99 && item.pointSum >= 70.0
? "ดี (คะแนนร้อยละ ๗๐. - ๗๙.๙๙)"
: item.pointSum <= 89.99 && item.pointSum >= 80.0
? "ดีมาก (คะแนนร้อยละ ๘๐. - ๘๙.๙๙)"
: "ดีเด่น (คะแนนร้อยละ ๙๐. ขึ้นไป)",
2025-05-02 09:39:53 +07:00
}))
: [
{
year: "-",
period: "-",
point1: "-",
point2: "-",
pointSum: "-",
pointSumTh: "-",
},
];
const profileAbility_raw = await this.profileAbilityRepo.find({
where: { profileEmployeeId: id },
order: { createdAt: "ASC" },
});
const profileAbility =
profileAbility_raw.length > 0
? profileAbility_raw.map((item) => ({
field: item.field ? item.field : "",
detail: item.detail ? item.detail : "",
}))
: [
{
field: "-",
detail: "-",
},
];
const otherIncome_raw = await this.salaryRepo.find({
where: {
profileEmployeeId: id,
commandCode: "7",
2025-08-06 11:15:08 +07:00
// isEntry: false,
2025-05-02 09:39:53 +07:00
},
order: { order: "ASC" },
});
const otherIncome =
otherIncome_raw.length > 0
? otherIncome_raw.map((item) => ({
commandName: item.commandName ?? "",
2025-05-02 09:39:53 +07:00
commandDateAffect: item.commandDateAffect
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateAffect))
: "",
commandDateSign: item.commandDateSign
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.commandDateSign))
: "",
commandNo: item.commandNo ? Extension.ToThaiNumber(item.commandNo) : "",
position: item.positionName,
2025-05-13 13:07:52 +07:00
posLevel: item.positionLevel
? Extension.ToThaiNumber(item.positionLevel)
: item.positionCee
? Extension.ToThaiNumber(item.positionCee)
: null,
2025-05-02 09:39:53 +07:00
amount: item.amount ? Extension.ToThaiNumber(Number(item.amount).toLocaleString()) : "",
}))
: [
{
commandName: "-",
2025-05-02 09:39:53 +07:00
commandDateAffect: "-",
commandDateSign: "-",
commandNo: "-",
position: "-",
posLevel: "-",
amount: "-",
},
];
const sum = profiles
? Extension.ToThaiNumber(
(
Number(profiles.amount) +
Number(profiles.positionSalaryAmount) +
Number(profiles.mouthSalaryAmount) +
Number(profiles.amountSpecial)
).toLocaleString(),
)
: "";
const fullCurrentAddress =
profiles && profiles.currentAddress
? Extension.ToThaiNumber(
profiles.currentAddress +
2025-05-13 11:48:45 +07:00
(profiles.currentSubDistrict && profiles.currentSubDistrict.name
? " ตำบล/แขวง " + profiles.currentSubDistrict.name
: "") +
(profiles.currentDistrict && profiles.currentDistrict.name
? " อำเภอ/เขต " + profiles.currentDistrict.name
: "") +
(profiles.currentProvince && profiles.currentProvince.name
? " จังหวัด " + profiles.currentProvince.name
: "") +
(profiles.currentZipCode ? " " + profiles.currentZipCode : ""),
2025-05-02 09:39:53 +07:00
)
: "";
const fullRegistrationAddress =
profiles && profiles.registrationAddress
? Extension.ToThaiNumber(
profiles.registrationAddress +
2025-05-13 11:48:45 +07:00
(profiles.registrationSubDistrict && profiles.registrationSubDistrict.name
? " ตำบล/แขวง " + profiles.registrationSubDistrict.name
: "") +
(profiles.registrationDistrict && profiles.registrationDistrict.name
? " อำเภอ/เขต " + profiles.registrationDistrict.name
: "") +
(profiles.registrationProvince && profiles.registrationProvince.name
? " จังหวัด " + profiles.registrationProvince.name
: "") +
(profiles.currentZipCode ? " " + profiles.currentZipCode : ""),
2025-05-02 09:39:53 +07:00
)
: "";
const data = {
fullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`,
prefix: profiles?.prefix != null ? profiles.prefix : "",
firstName: profiles?.firstName != null ? profiles.firstName : "",
lastName: profiles?.lastName != null ? profiles.lastName : "",
position: profiles?.position != null ? profiles.position : "",
amount:
profiles?.amount != null ? Extension.ToThaiNumber(profiles.amount.toLocaleString()) : "",
positionSalaryAmount:
profiles?.positionSalaryAmount != null
? Extension.ToThaiNumber(profiles.positionSalaryAmount.toLocaleString())
: "",
mouthSalaryAmount:
profiles?.mouthSalaryAmount != null
? Extension.ToThaiNumber(profiles.mouthSalaryAmount.toLocaleString())
: "",
amountSpecial:
profiles?.amountSpecial != null
? Extension.ToThaiNumber(profiles.amountSpecial.toLocaleString())
: "",
salarySum: sum,
ocFullPath:
(_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root),
birthDate: profiles?.birthDate
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.birthDate))
: "",
retireDate:
profiles.dateRetireLaw != null
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateRetireLaw))
: "",
appointDate: profiles?.dateAppoint
? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateAppoint))
: "",
positionDate:
positionList.length > 0 ? positionList[positionList.length - 1].commandDateAffect : "",
citizenId:
profiles.citizenId != null ? Extension.ToThaiNumber(profiles.citizenId.toString()) : "",
fatherFullName:
profileFamilyFather?.fatherPrefix ||
profileFamilyFather?.fatherFirstName ||
profileFamilyFather?.fatherLastName
? `${profileFamilyFather?.fatherPrefix ?? ""}${profileFamilyFather?.fatherFirstName ?? ""} ${profileFamilyFather?.fatherLastName ?? ""}`.trim()
: null,
fatherLive:
2025-05-13 11:48:45 +07:00
profileFamilyFather && profileFamilyFather?.fatherLive == true ? "ถึงแก่กรรม" : "มีชีวิต",
2025-05-02 09:39:53 +07:00
motherFullName:
profileFamilyMother?.motherPrefix ||
profileFamilyMother?.motherFirstName ||
profileFamilyMother?.motherLastName
? `${profileFamilyMother?.motherPrefix ?? ""}${profileFamilyMother?.motherFirstName ?? ""} ${profileFamilyMother?.motherLastName ?? ""}`.trim()
: null,
motherLive:
2025-05-13 11:48:45 +07:00
profileFamilyMother && profileFamilyMother?.motherLive == true ? "ถึงแก่กรรม" : "มีชีวิต",
2025-05-02 09:39:53 +07:00
coupleFullName:
profileFamilyCouple?.couplePrefix ||
profileFamilyCouple?.coupleFirstName ||
profileFamilyCouple?.coupleLastNameOld
? `${profileFamilyCouple?.couplePrefix ?? ""}${profileFamilyCouple?.coupleFirstName ?? ""} ${profileFamilyCouple?.coupleLastName ?? ""}`.trim()
: null,
coupleLastNameOld: profileFamilyCouple?.coupleLastNameOld ?? null,
coupleLive:
2025-05-13 11:48:45 +07:00
profileFamilyCouple && profileFamilyCouple?.coupleLive == true ? "ถึงแก่กรรม" : "มีชีวิต",
2025-05-02 09:39:53 +07:00
currentAddress:
profiles.currentAddress != null ? Extension.ToThaiNumber(profiles.currentAddress) : "",
currentSubDistrict:
profiles.currentSubDistrict != null
? Extension.ToThaiNumber(profiles.currentSubDistrict.name)
: "",
currentDistrict:
profiles.currentDistrict != null
? Extension.ToThaiNumber(profiles.currentDistrict.name)
: "",
currentProvince:
profiles.currentProvince != null
? Extension.ToThaiNumber(profiles.currentProvince.name)
: "",
currentZipcode:
profiles.currentZipCode != null ? Extension.ToThaiNumber(profiles.currentZipCode) : "",
fullCurrentAddress: fullCurrentAddress,
registrationAddress:
profiles.registrationAddress != null
? Extension.ToThaiNumber(profiles.registrationAddress)
: "",
registrationSubDistrict:
profiles.registrationSubDistrict != null
? Extension.ToThaiNumber(profiles.registrationSubDistrict.name)
: "",
registrationDistrict:
profiles.registrationDistrict != null
? Extension.ToThaiNumber(profiles.registrationDistrict.name)
: "",
registrationProvince:
profiles.registrationProvince != null
? Extension.ToThaiNumber(profiles.registrationProvince.name)
: "",
registrationZipcode:
profiles.registrationZipCode != null
? Extension.ToThaiNumber(profiles.registrationZipCode)
: "",
fullRegistrationAddress: fullRegistrationAddress,
updateAt: Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.lastUpdatedAt)),
2025-05-02 09:39:53 +07:00
telephone: profiles.phone != null ? Extension.ToThaiNumber(profiles.phone) : "",
url: ImgUrl ? ImgUrl : `${process.env.VITE_URL_MGT}`,
url1: _ImgUrl[0] ? _ImgUrl[0] : null,
yearUpload1: profiles.profileAvatars[0]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[0].createdAt))
: null,
url2: _ImgUrl[1] ? _ImgUrl[1] : null,
yearUpload2: profiles.profileAvatars[1]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[1].createdAt))
: null,
url3: _ImgUrl[2] ? _ImgUrl[2] : null,
yearUpload3: profiles.profileAvatars[2]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[2].createdAt))
: null,
url4: _ImgUrl[3] ? _ImgUrl[3] : null,
yearUpload4: profiles.profileAvatars[3]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[3].createdAt))
: null,
url5: _ImgUrl[4] ? _ImgUrl[4] : null,
yearUpload5: profiles.profileAvatars[4]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[4].createdAt))
: null,
url6: _ImgUrl[5] ? _ImgUrl[5] : null,
yearUpload6: profiles.profileAvatars[5]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[5].createdAt))
: null,
url7: _ImgUrl[6] ? _ImgUrl[6] : null,
yearUpload7: profiles.profileAvatars[6]
? Extension.ToThaiNumber(Extension.ToThaiShortYear(profiles.profileAvatars[6].createdAt))
: null,
urlQRcode: "https://seis.ocsc.go.th",
children,
insignias,
leaves,
leaves2,
certs,
trainings,
disciplines,
educations,
salarys,
changeName,
history,
2025-05-02 09:39:53 +07:00
positionList,
actposition,
duty,
assessments,
profileAbility,
otherIncome,
};
return new HttpSuccess({
template: "new_kk1-emp",
reportName: "docx-report",
data: data,
});
}
/**
* API
*
* @summary ORG_065 - (ADMIN) #70
*
*/
@Post()
2024-08-27 14:19:04 +07:00
async createProfile(@Body() body: CreateProfileEmployee, @Request() request: RequestWithUser) {
//ไม่แน่ใจEMPปิดไว้ก่อน
if (await this.profileRepo.findOneBy({ citizenId: body.citizenId })) {
throw new HttpError(
HttpStatus.INTERNAL_SERVER_ERROR,
2024-05-15 13:38:00 +07:00
"รหัสบัตรประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว",
);
}
if (body.posLevelId === "") body.posLevelId = null;
if (body.posTypeId === "") body.posTypeId = null;
if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
}
if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
2024-11-22 12:18:12 +07:00
if (body.citizenId) {
const citizenIdDigits = body.citizenId.toString().split("").map(Number);
const cal =
citizenIdDigits[0] * 13 +
citizenIdDigits[1] * 12 +
citizenIdDigits[2] * 11 +
citizenIdDigits[3] * 10 +
citizenIdDigits[4] * 9 +
citizenIdDigits[5] * 8 +
citizenIdDigits[6] * 7 +
citizenIdDigits[7] * 6 +
citizenIdDigits[8] * 5 +
citizenIdDigits[9] * 4 +
citizenIdDigits[10] * 3 +
citizenIdDigits[11] * 2;
const calStp2 = cal % 11;
let chkDigit = 11 - calStp2;
2025-07-17 14:39:02 +07:00
if (chkDigit >= 10) {
chkDigit = 0;
2024-11-22 12:18:12 +07:00
}
if (citizenIdDigits[12] !== chkDigit) {
throw new HttpError(HttpStatus.NOT_FOUND, "ข้อมูลรหัสบัตรประจำตัวประชาชนไม่ถูกต้อง");
}
}
2024-06-07 03:05:57 +07:00
if (body.employeeClass == null || body.employeeClass == undefined || body.employeeClass == "") {
2024-06-05 16:27:26 +07:00
body.employeeClass = "PERM";
}
if (!["PERM", "TEMP"].includes(body.employeeClass.toLocaleUpperCase())) {
throw new HttpError(HttpStatus.NOT_FOUND, "ประเภทลูกจ้างไม่ถูกต้อง");
}
const profile = Object.assign(new ProfileEmployee(), body);
2024-11-22 12:18:12 +07:00
profile.prefixMain = profile.prefix;
2024-12-12 11:36:11 +07:00
profile.prefix = profile.rank && profile.rank.length > 0 ? profile.rank : profile.prefixMain;
profile.createdUserId = request.user.sub;
profile.createdFullName = request.user.name;
profile.lastUpdateUserId = request.user.sub;
profile.lastUpdateFullName = request.user.name;
profile.createdAt = new Date();
profile.lastUpdatedAt = new Date();
2024-05-15 18:06:28 +07:00
profile.dateRetire = calculateRetireDate(profile.birthDate);
2024-05-16 15:22:30 +07:00
profile.dateRetireLaw = calculateRetireLaw(profile.birthDate);
profile.citizenId = Extension.CheckCitizen(profile.citizenId);
profile.statusTemp = profile.employeeClass.toLocaleUpperCase() == "TEMP" ? "WAITTING" : "";
2024-06-07 03:05:57 +07:00
profile.employeeClass = profile.employeeClass.toLocaleUpperCase();
2024-03-21 10:41:18 +07:00
await this.profileRepo.save(profile);
return new HttpSuccess();
}
/**
* API
*
* @summary ORG_065 - (ADMIN) #70
*
* @param {string} id Id
*/
@Put("{id}")
2024-05-17 14:16:40 +07:00
async updateProfileEmployee(
@Request() request: RequestWithUser,
@Path() id: string,
@Body() body: UpdateProfileEmployee,
) {
2024-11-22 12:18:12 +07:00
const _record = await this.profileRepo.findOneBy({ id: id });
if (_record) {
await new permission().PermissionOrgUserUpdate(request, "SYS_REGISTRY_EMP", _record.id);
}
const exists =
!!body.citizenId &&
(await this.profileRepo.findOne({
where: {
id: Not(id),
citizenId: body.citizenId,
employeeClass: String(body.employeeClass),
},
}));
if (exists) {
2024-05-15 13:38:00 +07:00
throw new HttpError(HttpStatus.CONFLICT, "รหัสบัตรประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว");
}
if (body.posLevelId === "") body.posLevelId = null;
if (body.posTypeId === "") body.posTypeId = null;
if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
}
if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
2024-11-22 12:18:12 +07:00
if (body.citizenId) {
const citizenIdDigits = body.citizenId.toString().split("").map(Number);
const cal =
citizenIdDigits[0] * 13 +
citizenIdDigits[1] * 12 +
citizenIdDigits[2] * 11 +
citizenIdDigits[3] * 10 +
citizenIdDigits[4] * 9 +
citizenIdDigits[5] * 8 +
citizenIdDigits[6] * 7 +
citizenIdDigits[7] * 6 +
citizenIdDigits[8] * 5 +
citizenIdDigits[9] * 4 +
citizenIdDigits[10] * 3 +
citizenIdDigits[11] * 2;
const calStp2 = cal % 11;
let chkDigit = 11 - calStp2;
2025-07-17 14:39:02 +07:00
if (chkDigit >= 10) {
chkDigit = 0;
2024-11-22 12:18:12 +07:00
}
if (citizenIdDigits[12] !== chkDigit) {
throw new HttpError(HttpStatus.NOT_FOUND, "ข้อมูลรหัสบัตรประจำตัวประชาชนไม่ถูกต้อง");
}
}
const record = await this.profileRepo.findOneBy({ id });
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");
2024-06-07 03:05:57 +07:00
if (body.employeeClass == null || body.employeeClass == undefined || body.employeeClass == "") {
2024-06-05 16:27:26 +07:00
body.employeeClass = "PERM";
}
if (!["PERM", "TEMP"].includes(body.employeeClass.toLocaleUpperCase())) {
throw new HttpError(HttpStatus.NOT_FOUND, "ประเภทลูกจ้างไม่ถูกต้อง");
}
Object.assign(record, body);
record.dateRetireLaw = calculateRetireLaw(record.birthDate);
2024-11-22 12:18:12 +07:00
record.prefixMain = record.prefix;
2024-12-12 11:36:11 +07:00
record.prefix = record.rank && record.rank.length > 0 ? record.rank : record.prefixMain;
record.createdUserId = request.user.sub;
record.createdFullName = request.user.name;
record.createdAt = new Date();
record.lastUpdateUserId = request.user.sub;
record.lastUpdateFullName = request.user.name;
record.lastUpdatedAt = new Date();
2024-09-02 15:35:12 +07:00
await this.profileHistoryRepo.save(
Object.assign(new ProfileEmployeeHistory(), {
...record,
birthDateOld: _record?.birthDate,
2024-09-02 15:35:12 +07:00
lastUpdateUserId: request.user.sub,
lastUpdateFullName: request.user.name,
lastUpdatedAt: new Date(),
profileEmployeeId: id,
id: undefined,
}),
);
await this.profileRepo.save(record);
return new HttpSuccess();
}
/**
* API
*
* @summary ORG_065 - (ADMIN) #70
*
* @param {string} id Id
*/
@Delete("{id}")
async deleteProfile(@Path() id: string, @Request() request: RequestWithUser) {
2024-06-18 12:08:03 +07:00
const result = await this.profileRepo.findOne({ where: { id: id } });
if (!result) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
2025-10-22 14:23:28 +07:00
try{
await new permission().PermissionOrgUserDelete(request, "SYS_REGISTRY_EMP", result.id);
await this.informationHistoryRepository.delete({ profileEmployeeId: id });
await this.profileRepo.remove(result);
} catch {
2025-10-22 15:57:07 +07:00
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่สามารถลบข้อมูลได้ เนื่องจากข้อมูลนี้ถูกใช้งานในระบบอื่น");
2025-10-22 14:23:28 +07:00
}
return new HttpSuccess();
}
/**
* API
*
* @summary ORG_065 - (ADMIN) #70
2024-05-24 01:11:47 +07:00
*
* @param {string} id Id
*/
@Get("user")
async detailProfileUser(@Request() request: RequestWithUser) {
const profile = await this.profileRepo.findOne({
relations: {
posLevel: true,
posType: true,
// gender: true,
// relationship: true,
// bloodGroup: true,
},
where: { keycloak: request.user.sub },
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
return new HttpSuccess(profile);
}
/**
* API
*
* @summary (ADMIN)
*
*/
@Get("temp")
async listProfileEmp() {
const [record, total] = await this.profileRepo
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
.leftJoinAndSelect("profileEmployee.posType", "posType")
.leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
2024-06-10 16:14:25 +07:00
.leftJoinAndSelect("profileEmployee.profileEmployeeEmployment", "profileEmployeeEmployment")
.leftJoinAndSelect("current_holders.positions", "positions")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
.andWhere("profileEmployee.employeeClass = :employeeClass", { employeeClass: "TEMP" })
2024-06-10 18:18:39 +07:00
.andWhere("profileEmployee.statusTemp = :statusTemp", { statusTemp: "PENDING" })
.getManyAndCount();
const data = await Promise.all(
record.map((_data) => {
const shortName =
_data.current_holders.length == 0
? null
: _data.current_holders[0].orgChild4 != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders[0].orgChild4.orgChild4ShortName} ${_data.current_holders[0].posMasterNo}`
: _data.current_holders[0].orgChild3 != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders[0].orgChild3.orgChild3ShortName} ${_data.current_holders[0].posMasterNo}`
: _data.current_holders[0].orgChild2 != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders[0].orgChild2.orgChild2ShortName} ${_data.current_holders[0].posMasterNo}`
: _data.current_holders[0].orgChild1 != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders[0].orgChild1.orgChild1ShortName} ${_data.current_holders[0].posMasterNo}`
: _data.current_holders[0].orgRoot != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders[0].orgRoot.orgRootShortName} ${_data.current_holders[0].posMasterNo}`
: null;
const dateEmployment =
2024-06-10 16:14:25 +07:00
_data.profileEmployeeEmployment.length == 0
? null
: _data.profileEmployeeEmployment.reduce((latest, current) => {
return latest.date > current.date ? latest : current;
}).date;
return {
id: _data.id,
prefix: _data.prefix,
rank: _data.rank,
firstName: _data.firstName,
lastName: _data.lastName,
citizenId: _data.citizenId,
posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
posType: _data.posType == null ? null : _data.posType.posTypeName,
posTypeShortName: _data.posType == null ? null : _data.posType.posTypeShortName,
posLevelId: _data.posLevel == null ? null : _data.posLevel.id,
posTypeId: _data.posType == null ? null : _data.posType.id,
2024-06-10 16:14:25 +07:00
positionId: _data.positionIdTemp,
posmasterId: _data.posmasterIdTemp,
position: _data.position,
2024-06-07 18:04:40 +07:00
posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
2025-10-02 14:37:25 +07:00
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
2024-06-10 16:14:25 +07:00
dateEmployment: dateEmployment,
dateAppoint: _data.dateAppoint,
dateStart: _data.dateStart,
createdAt: _data.createdAt,
dateRetireLaw: _data.dateRetireLaw,
draftOrganizationOrganization:
_data.nodeTemp == "0"
? _data.rootTemp
: _data.nodeTemp == "1"
? _data.child1Temp
: _data.nodeTemp == "2"
? _data.child2Temp
: _data.nodeTemp == "3"
? _data.child3Temp
: _data.nodeTemp == "4"
? _data.child4Temp
: null,
draftPositionEmployee: _data.positionTemp,
draftOrgEmployeeStatus: _data.statusTemp,
node: _data.nodeTemp,
nodeId: _data.nodeIdTemp,
nodeName:
_data.nodeTemp == "0"
? _data.rootTemp
: _data.nodeTemp == "1"
? _data.child1Temp
: _data.nodeTemp == "2"
? _data.child2Temp
: _data.nodeTemp == "3"
? _data.child3Temp
: _data.nodeTemp == "4"
? _data.child4Temp
: null,
nodeShortName:
_data.nodeTemp == "0"
? _data.rootShortNameTemp
: _data.nodeTemp == "1"
? _data.child1ShortNameTemp
: _data.nodeTemp == "2"
? _data.child1ShortNameTemp
: _data.nodeTemp == "3"
? _data.child3ShortNameTemp
: _data.nodeTemp == "4"
? _data.child4ShortNameTemp
: null,
root: _data.rootTemp ? _data.rootTemp : null,
rootId: _data.rootIdTemp ? _data.rootIdTemp : null,
rootShortName: _data.rootShortNameTemp ? _data.rootShortNameTemp : null,
child1: _data.child1Temp ? _data.child1Temp : null,
child1Id: _data.child1IdTemp ? _data.child1IdTemp : null,
child1ShortName: _data.child1ShortNameTemp ? _data.child1ShortNameTemp : null,
child2: _data.child2Temp ? _data.child2Temp : null,
child2Id: _data.child2IdTemp ? _data.child2IdTemp : null,
child2ShortName: _data.child2ShortNameTemp ? _data.child2ShortNameTemp : null,
child3: _data.child3Temp ? _data.child3Temp : null,
child3Id: _data.child3IdTemp ? _data.child3IdTemp : null,
child3ShortName: _data.child3ShortNameTemp ? _data.child3ShortNameTemp : null,
child4: _data.child4Temp ? _data.child4Temp : null,
child4Id: _data.child4IdTemp ? _data.child4IdTemp : null,
child4ShortName: _data.child4ShortNameTemp ? _data.child4ShortNameTemp : null,
};
}),
);
return new HttpSuccess({ data: data, total });
}
2024-05-24 13:13:52 +07:00
/**
* API
*
* @summary
*
* @param {string} id Id
*/
@Get("history/user")
async getHistoryProfileByUser(@Request() request: RequestWithUser) {
const historyProfile = await this.profileHistoryRepo.find({
relations: {
posLevel: true,
posType: true,
},
where: { keycloak: request.user.sub },
order: {
createdAt: "ASC",
},
});
if (!historyProfile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
return new HttpSuccess(historyProfile);
}
/**
* API
*
* @summary ORG_038 - (ADMIN) #
*
*/
@Get("report")
async getReport(@Request() request: RequestWithUser) {
const profiles = await this.profileRepo.find({
where: { statusTemp: "REPORT", employeeClass: "TEMP" },
relations: [
"posLevel",
"posType",
"current_holders",
"current_holders.orgChild1",
"current_holders.orgChild2",
"current_holders.orgChild3",
2024-06-18 12:08:03 +07:00
"current_holders.orgChild4",
],
});
2024-06-18 12:08:03 +07:00
if (!profiles) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
2024-06-18 12:08:03 +07:00
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
2024-06-18 12:08:03 +07:00
const formattedData = profiles.map((profile) => {
const fullName = `${profile.prefix} ${profile.firstName} ${profile.lastName}`;
const shortName =
profile.current_holders.length == 0
? null
: profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-06-18 12:08:03 +07:00
: profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild3 != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-06-18 12:08:03 +07:00
: profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild2 != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-06-18 12:08:03 +07:00
: profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild1 != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-06-18 12:08:03 +07:00
: profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
null &&
profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgRoot != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-06-18 12:08:03 +07:00
: null;
const root =
profile.current_holders.length == 0 ||
(profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null)
? null
: profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;
return {
id: profile.id,
prefix: profile.prefix,
firstName: profile.firstName,
lastName: profile.lastName,
fullName: fullName,
birthDate: profile.birthDate,
rank: profile.rank,
citizenId: profile.citizenId,
email: profile.email,
phone: profile.phone,
isProbation: profile.isProbation,
isLeave: profile.isLeave,
leaveReason: profile.leaveReason,
dateLeave: profile.dateLeave,
dateRetire: profile.dateRetire,
dateRetireLaw: profile.dateRetireLaw,
salaryLevel: profile.salaryLevel,
group: profile.group,
ethnicity: profile.ethnicity,
2025-04-05 19:21:50 +07:00
telephoneNumber: profile.phone,
nationality: profile.nationality,
gender: profile.gender,
relationship: profile.relationship,
religion: profile.religion,
bloodGroup: profile.bloodGroup,
positionNumber: shortName,
organization: root == null ? null : root.orgRootShortName,
positionName: profile.position,
possitionTypeId: profile.posTypeId,
positionType: profile.posType?.posTypeName,
positionLevelId: profile.posLevelId,
positionLevel: profile.posLevel?.posLevelName,
};
});
2024-06-18 12:08:03 +07:00
return new HttpSuccess(formattedData);
}
/**
* API
*
* @summary ORG_038 - (ADMIN) #
*
*/
@Get("report-temp")
async getReportTemp(@Request() request: RequestWithUser) {
const profiles = await this.profileRepo.find({
where: { statusTemp: "REPORT", employeeClass: "TEMP" },
});
if (!profiles) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
const formattedData = profiles.map((profile) => {
const shortName =
profile.child4Temp != null
2025-04-05 19:21:50 +07:00
? `${profile.child4ShortNameTemp} ${profile.posMasterNoTemp}`
: profile.child3Temp != null
2025-04-05 19:21:50 +07:00
? `${profile.child3ShortNameTemp} ${profile.posMasterNoTemp}`
: profile.child2Temp != null
2025-04-05 19:21:50 +07:00
? `${profile.child2ShortNameTemp} ${profile.posMasterNoTemp}`
: profile.child1Temp != null
2025-04-05 19:21:50 +07:00
? `${profile.child1ShortNameTemp} ${profile.posMasterNoTemp}`
: profile.rootIdTemp != null
2025-04-05 19:21:50 +07:00
? `${profile.rootShortNameTemp} ${profile.posMasterNoTemp}`
: null;
return {
id: profile.id,
citizenId: profile.citizenId,
prefix: profile.prefix,
firstName: profile.firstName,
lastName: profile.lastName,
organization: profile.rootTemp,
positionName: profile.positionTemp,
positionType: profile.posTypeNameTemp,
positionLevel: profile.posLevelNameTemp,
positionNumber: shortName,
birthDate: profile.birthDate,
};
});
return new HttpSuccess(formattedData);
}
2025-02-18 23:02:38 +07:00
/**
* API
*
* @summary ORG_065 -
*
*/
@Get("otherSystem")
async listProfileNoPermission(
@Request() request: RequestWithUser,
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query()
searchField?: "firstName" | "lastName" | "fullName" | "citizenId" | "position" | "posNo",
@Query() searchKeyword: string = "",
@Query() posType?: string,
@Query() posLevel?: string,
@Query() yearLeave?: number,
@Query() isProbation?: boolean,
@Query() isRetire?: boolean,
@Query() nodeId?: string,
) {
let queryLike =
"CONCAT(profileEmployee.prefix, profileEmployee.firstName, ' ', profileEmployee.lastName) LIKE :keyword";
if (searchField == "citizenId") {
queryLike = "profileEmployee.citizenId LIKE :keyword";
} else if (searchField == "position") {
queryLike = "profileEmployee.position LIKE :keyword";
} else if (searchField == "posNo") {
queryLike = `
CASE
2025-04-05 19:21:50 +07:00
WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT(orgChild4.orgChild4ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT(orgChild3.orgChild3ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT(orgChild2.orgChild2ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT(orgChild1.orgChild1ShortName, " ", current_holders.posMasterNo)
ELSE CONCAT(orgRoot.orgRootShortName, " ", current_holders.posMasterNo)
2025-02-18 23:02:38 +07:00
END LIKE :keyword
`;
}
let posMaster = await this.posMasterRepo.findOne({
where: {
current_holder: { keycloak: request.user.sub },
orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true },
},
});
let revisionId = "";
if (nodeId == null) {
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
revisionId = findRevision.id;
if (posMaster != null) nodeId = posMaster.orgRootId ?? "";
} else {
const findRoot = await this.orgRootRepository.findOne({
where: { id: nodeId },
});
if (!findRoot) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบสำนักงานนี้ในระบบ");
}
revisionId = findRoot.orgRevisionId;
}
let nodeCondition = "current_holders.orgRootId = :nodeId";
const [record, total] = await this.profileRepo
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
.leftJoinAndSelect("profileEmployee.posType", "posType")
.leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.positions", "positions")
.leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
.where("current_holders.orgRevisionId = :orgRevisionId", { orgRevisionId: revisionId })
.andWhere(
posType != undefined && posType != null && posType != ""
? "posType.posTypeName LIKE :keyword1"
: "1=1",
{
keyword1: `${posType}`,
},
)
.andWhere(
posLevel != undefined && posLevel != null && posLevel != ""
? "posLevel.posLevelName LIKE :keyword2"
: "1=1",
{
keyword2: `${posLevel}`,
},
)
.andWhere(
isProbation != undefined && isProbation != null
? `profile.isProbation = ${isProbation}`
: "1=1",
)
.andWhere(
isRetire != undefined && isRetire != null
? isRetire == false
? `profile.dateLeave IS null`
: `profile.dateLeave IS NOT NULL`
: "1=1",
)
.andWhere(
searchKeyword != undefined && searchKeyword != null && searchKeyword != ""
? queryLike
: "1=1",
{
keyword: `%${searchKeyword}%`,
},
)
.andWhere(nodeCondition, {
nodeId: nodeId,
})
.orderBy("current_holders.posMasterNo", "ASC")
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
const data = await Promise.all(
record.map((_data) => {
const shortName =
_data.current_holders.length == 0
? null
: _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4.orgChild4ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
2025-02-18 23:02:38 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 !=
null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3.orgChild3ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
2025-02-18 23:02:38 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 !=
null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2.orgChild2ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
2025-02-18 23:02:38 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 !=
null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1.orgChild1ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
2025-02-18 23:02:38 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot !=
null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot.orgRootShortName} ${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}`
2025-02-18 23:02:38 +07:00
: null;
const root =
_data.current_holders.length == 0 ||
(_data.current_holders.find((x) => x.orgRevisionId == revisionId) != null &&
_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null)
? null
: _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot;
const child1 =
_data.current_holders == null ||
_data.current_holders.length == 0 ||
_data.current_holders.find((x) => x.orgRevisionId == revisionId) == null
? null
: _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1;
const child2 =
_data.current_holders == null ||
_data.current_holders.length == 0 ||
_data.current_holders.find((x) => x.orgRevisionId == revisionId) == null
? null
: _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2;
const child3 =
_data.current_holders == null ||
_data.current_holders.length == 0 ||
_data.current_holders.find((x) => x.orgRevisionId == revisionId) == null
? null
: _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3;
const child4 =
_data.current_holders == null ||
_data.current_holders.length == 0 ||
_data.current_holders.find((x) => x.orgRevisionId == revisionId) == null
? null
: _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4;
2025-04-05 19:21:50 +07:00
let _root = root?.orgRootName;
let _child1 = child1?.orgChild1Name;
let _child2 = child2?.orgChild2Name;
let _child3 = child3?.orgChild3Name;
let _child4 = child4?.orgChild4Name;
2025-02-18 23:02:38 +07:00
return {
id: _data.id,
avatar: _data.avatar,
avatarName: _data.avatarName,
prefix: _data.prefix,
rank: _data.rank,
firstName: _data.firstName,
lastName: _data.lastName,
citizenId: _data.citizenId,
2025-08-04 16:43:22 +07:00
posLevel: `${_data.posType?.posTypeShortName ?? ""} ${_data.posLevel?.posLevelName ?? ""}`,
2025-02-18 23:02:38 +07:00
posType: _data.posType == null ? null : _data.posType.posTypeName,
posLevelId: _data.posLevel == null ? null : _data.posLevel.id,
posTypeId: _data.posType == null ? null : _data.posType.id,
position: _data.position,
posNo: shortName,
rootId: root == null ? null : root.id,
root: root == null ? null : root.orgRootName,
orgRootShortName: root == null ? null : root.orgRootShortName,
orgRevisionId: root == null ? null : root.orgRevisionId,
2025-04-05 19:21:50 +07:00
org:
(_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root),
2025-02-18 23:02:38 +07:00
};
}),
);
return new HttpSuccess({ data: data, total });
}
2024-12-14 12:00:45 +07:00
/**
* API Update amount
*
* @summary Update amount (ADMIN)
*
*/
@Get("update-amount")
async updateProfileAmount(@Request() request: RequestWithUser) {
const profiles = await this.profileRepo.find({
order: { profileSalary: { order: "DESC" } },
relations: ["profileSalary"],
});
profiles.map(async (x) => {
const amount = x.profileSalary[0];
x.amount = amount?.amount ?? 0;
x.amountSpecial = amount?.amountSpecial ?? 0;
x.positionSalaryAmount = amount?.positionSalaryAmount ?? 0;
await this.profileRepo.save(x);
});
return new HttpSuccess();
}
2025-04-05 19:21:50 +07:00
2025-03-27 11:08:41 +07:00
/**
* API .
*
* @summary .
*
*/
@Get("profileLeave")
@Example({
status: 200,
message: "สำเร็จ",
result: {
data: [
{
page: 1,
pageSize: 12,
posLevel: "บ 1",
posType: "บริการพื้นฐาน",
isProbation: false,
isRetire: true,
node: 0,
nodeId: "8349b6b6-d005-4eb7-9960-ceb5b96e1962",
isAll: true,
sortBy: "profile.dateAppoint",
sort: "DESC",
retireType: "RETIRE_DECEASED",
},
],
total: 1,
},
})
2025-03-27 11:08:41 +07:00
async listProfileLeave(
@Request() request: RequestWithUser,
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query()
searchField?: "firstName" | "lastName" | "fullName" | "citizenId" | "position" | "posNo",
@Query() searchKeyword: string = "",
@Query() posType?: string,
@Query() posLevel?: string,
@Query() isProbation?: boolean,
@Query() node?: number,
@Query() nodeId?: string,
@Query() isAll?: boolean,
@Query() retireType?: string,
@Query() sortBy: string = "profileEmployee.dateLeave",
@Query() sort: "ASC" | "DESC" = "DESC",
2025-03-27 11:08:41 +07:00
) {
let _data = await new permission().PermissionOrgList(request, "SYS_REGISTRY_EMP");
const { data, total } = await this.profileLeaveService.getLeaveEmployees(request, {
page,
pageSize,
searchField,
searchKeyword,
posType,
posLevel,
isProbation,
node,
nodeId,
isAll,
retireType,
sortBy,
sort,
_data,
});
2025-03-27 11:08:41 +07:00
return new HttpSuccess({ data, total });
2025-03-27 11:08:41 +07:00
}
2024-12-14 12:00:45 +07:00
/**
* API
*
* @summary ORG_065 - (ADMIN) #70
*
* @param {string} id Id
*/
@Get("{id}")
async detailProfile(@Path() id: string, @Request() req: RequestWithUser) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_EMP");
if (_workflow == false)
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", id);
2024-09-27 13:50:26 +07:00
const profile: any = await this.profileRepo.findOne({
relations: {
posLevel: true,
posType: true,
// gender: true,
// relationship: true,
// bloodGroup: true,
},
where: { id },
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
2024-09-27 13:50:26 +07:00
profile.profileType = "EMPLOYEE";
return new HttpSuccess(profile);
}
@Get("admin/{id}")
async detailProfileAdmin(@Path() id: string) {
const profile = await this.profileRepo.findOne({
relations: {
posLevel: true,
posType: true,
},
where: { id },
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
return new HttpSuccess(profile);
}
/**
* API
*
* @summary ORG_065 - (ADMIN) #70
*
*/
@Get()
async listProfile(
@Request() request: RequestWithUser,
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query()
searchField?: "firstName" | "lastName" | "fullName" | "citizenId" | "position" | "posNo",
@Query() searchKeyword: string = "",
@Query() posType?: string,
@Query() posLevel?: string,
@Query() isProbation?: boolean,
@Query() isRetire?: boolean,
@Query() node?: number,
@Query() nodeId?: string,
@Query() isAll?: boolean,
@Query() retireType?: string,
@Query() sortBy?: string,
@Query() sort: "ASC" | "DESC" = "ASC",
) {
let _data = await new permission().PermissionOrgList(request, "SYS_REGISTRY_EMP");
let queryLike =
"CONCAT(profileEmployee.prefix, profileEmployee.firstName, ' ', profileEmployee.lastName) LIKE :keyword";
if (searchField == "citizenId") {
queryLike = "profileEmployee.citizenId LIKE :keyword";
} else if (searchField == "position") {
queryLike = "profileEmployee.position LIKE :keyword";
} else if (searchField == "posNo") {
2024-12-03 13:53:03 +07:00
queryLike = `
2024-12-03 17:37:54 +07:00
CASE
2025-04-05 19:21:50 +07:00
WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT(orgChild4.orgChild4ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT(orgChild3.orgChild3ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT(orgChild2.orgChild2ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT(orgChild1.orgChild1ShortName, " ", current_holders.posMasterNo)
ELSE CONCAT(orgRoot.orgRootShortName, " ", current_holders.posMasterNo)
2024-12-03 17:37:54 +07:00
END LIKE :keyword
2024-12-03 13:53:03 +07:00
`;
}
let nodeCondition = "1=1";
let nodeAll = "";
if (node === 0 && nodeId) {
nodeCondition = "current_holders.orgRootId = :nodeId";
2024-09-04 12:10:34 +07:00
if (isAll == false) nodeAll = " AND current_holders.orgChild1Id IS NULL";
} else if (node === 1 && nodeId) {
nodeCondition = "current_holders.orgChild1Id = :nodeId";
2024-09-04 12:10:34 +07:00
if (isAll == false) nodeAll = " AND current_holders.orgChild2Id IS NULL";
} else if (node === 2 && nodeId) {
nodeCondition = "current_holders.orgChild2Id = :nodeId";
2024-09-04 12:10:34 +07:00
if (isAll == false) nodeAll = " AND current_holders.orgChild3Id IS NULL";
} else if (node === 3 && nodeId) {
nodeCondition = "current_holders.orgChild3Id = :nodeId";
2024-09-04 12:10:34 +07:00
if (isAll == false) nodeAll = " AND current_holders.orgChild4Id IS NULL";
} else if (node === 4 && nodeId) {
nodeCondition = "current_holders.orgChild4Id = :nodeId";
}
nodeCondition = nodeCondition + nodeAll;
2024-11-25 16:57:36 +07:00
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
const [record, total] = await this.profileRepo
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
.leftJoinAndSelect("profileEmployee.posType", "posType")
.leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
2024-06-10 16:14:25 +07:00
.leftJoinAndSelect("profileEmployee.profileEmployeeEmployment", "profileEmployeeEmployment")
.leftJoinAndSelect("current_holders.positions", "positions")
2024-11-26 10:42:16 +07:00
.leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
2024-12-25 01:10:49 +07:00
.where(node && nodeId ? "current_holders.orgRevisionId = :orgRevisionId" : "1=1", {
orgRevisionId: node && nodeId ? findRevision.id : undefined,
})
.andWhere(
_data.root != undefined && _data.root != null
2024-08-29 14:41:48 +07:00
? _data.root[0] != null
? `current_holders.orgRootId IN (:...root)`
2024-08-29 14:41:48 +07:00
: `current_holders.orgRootId is null`
: "1=1",
{
root: _data.root,
},
)
.andWhere(
_data.child1 != undefined && _data.child1 != null
2024-08-29 14:41:48 +07:00
? _data.child1[0] != null
? `current_holders.orgChild1Id IN (:...child1)`
2024-08-29 14:41:48 +07:00
: `current_holders.orgChild1Id is null`
: "1=1",
{
child1: _data.child1,
},
)
.andWhere(
_data.child2 != undefined && _data.child2 != null
2024-08-29 14:41:48 +07:00
? _data.child2[0] != null
? `current_holders.orgChild2Id IN (:...child2)`
2024-08-29 14:41:48 +07:00
: `current_holders.orgChild2Id is null`
: "1=1",
{
child2: _data.child2,
},
)
.andWhere(
_data.child3 != undefined && _data.child3 != null
2024-08-29 14:41:48 +07:00
? _data.child3[0] != null
? `current_holders.orgChild3Id IN (:...child3)`
2024-08-29 14:41:48 +07:00
: `current_holders.orgChild3Id is null`
: "1=1",
{
child3: _data.child3,
},
)
.andWhere(
_data.child4 != undefined && _data.child4 != null
2024-08-29 14:41:48 +07:00
? _data.child4[0] != null
? `current_holders.orgChild4Id IN (:...child4)`
2024-08-29 14:41:48 +07:00
: `current_holders.orgChild4Id is null`
: "1=1",
{
child4: _data.child4,
},
)
.andWhere(
posType != undefined && posType != null && posType != ""
? "posType.posTypeName LIKE :keyword1"
: "1=1",
{
keyword1: `${posType}`,
},
)
.andWhere(
posLevel != undefined && posLevel != null && posLevel != ""
2024-11-29 10:31:36 +07:00
? `CONCAT(posType.posTypeShortName,' ',posLevel.posLevelName) LIKE :keyword2`
: "1=1",
{
keyword2: `${posLevel}`,
},
)
.andWhere(
isProbation != undefined && isProbation != null
? `profileEmployee.isProbation = ${isProbation}`
: "1=1",
)
.andWhere(
isRetire != undefined && isRetire != null
? isRetire == false
2025-02-20 12:59:22 +07:00
? `profileEmployee.isLeave IS FALSE`
: isRetire == true && retireType != undefined && retireType != null
2025-02-20 12:59:22 +07:00
? `profileEmployee.isLeave IS TRUE AND profileEmployee.leaveType = '${retireType}'`
: `profileEmployee.isLeave IS TRUE`
2025-02-03 15:40:44 +07:00
: "1=1",
)
.andWhere("profileEmployee.employeeClass LIKE :type", {
type: "PERM",
})
.andWhere(
searchKeyword != undefined && searchKeyword != null && searchKeyword != ""
? queryLike
: "1=1",
{
keyword: `%${searchKeyword}%`,
2024-05-13 15:38:56 +07:00
},
)
.andWhere(nodeCondition, {
nodeId: nodeId,
})
2025-05-13 16:52:14 +07:00
.addSelect("CASE WHEN current_holders.posMasterNo IS NULL THEN 1 ELSE 0 END", "sort_order")
.orderBy(sortBy ? sortBy : "sort_order", sort)
2025-05-13 16:52:14 +07:00
.addOrderBy("orgRoot.orgRootOrder", sort)
.addOrderBy("orgChild1.orgChild1Order", sort)
.addOrderBy("orgChild2.orgChild2Order", sort)
.addOrderBy("orgChild3.orgChild3Order", sort)
.addOrderBy("orgChild4.orgChild4Order", sort)
.addOrderBy("current_holders.posMasterNo", sort)
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
const data = await Promise.all(
record.map((_data) => {
const shortName =
_data.current_holders.length == 0
? null
2025-01-17 10:19:10 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2025-01-17 10:19:10 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild3 != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2025-01-17 10:19:10 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild2 != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2025-01-17 10:19:10 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild1 != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2025-01-17 10:19:10 +07:00
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
null &&
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgRoot != null
2025-04-05 19:21:50 +07:00
? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: null;
const dateEmployment =
2024-06-10 16:14:25 +07:00
_data.profileEmployeeEmployment.length == 0
? null
: _data.profileEmployeeEmployment.reduce((latest, current) => {
return latest.date > current.date ? latest : current;
}).date;
2024-09-01 22:44:23 +07:00
const root =
_data.current_holders.length == 0 ||
(_data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null)
? null
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;
const child1 =
_data.current_holders == null ||
_data.current_holders.length == 0 ||
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
? null
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1;
const child2 =
_data.current_holders == null ||
_data.current_holders.length == 0 ||
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
? null
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2;
const child3 =
_data.current_holders == null ||
_data.current_holders.length == 0 ||
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
? null
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3;
const child4 =
_data.current_holders == null ||
_data.current_holders.length == 0 ||
_data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
? null
: _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4;
2025-04-04 09:52:59 +07:00
let _root = root?.orgRootName;
2025-04-05 19:21:50 +07:00
let _child1 = child1?.orgChild1Name;
let _child2 = child2?.orgChild2Name;
let _child3 = child3?.orgChild3Name;
let _child4 = child4?.orgChild4Name;
return {
2025-05-13 16:56:06 +07:00
id: _data.id,
avatar: _data.avatar,
avatarName: _data.avatarName,
prefix: _data.prefix,
rank: _data.rank,
firstName: _data.firstName,
lastName: _data.lastName,
citizenId: _data.citizenId,
posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName,
posType: _data.posType == null ? null : _data.posType.posTypeName,
posTypeShortName: _data.posType == null ? null : _data.posType.posTypeShortName,
posLevelTemp: _data.posLevelNameTemp,
posTypeTemp: _data.posTypeNameTemp,
posTypeShortNameTemp: _data.posTypeShortNameTemp,
posLevelId: _data.posLevel == null ? null : _data.posLevel.id,
posTypeId: _data.posType == null ? null : _data.posType.id,
positionId: _data.positionIdTemp,
posmasterId: _data.posmasterIdTemp,
position: _data.position,
positionTemp: _data.positionTemp,
2024-06-07 18:04:40 +07:00
posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
2025-05-13 16:56:06 +07:00
employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
2025-10-02 14:37:25 +07:00
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
2025-05-13 16:56:06 +07:00
dateEmployment: dateEmployment,
dateAppoint: _data.dateAppoint,
dateStart: _data.dateStart,
createdAt: _data.createdAt,
dateRetireLaw: _data.dateRetireLaw,
draftOrganizationOrganization:
_data.nodeTemp == "0"
? _data.rootTemp
: _data.nodeTemp == "1"
? _data.child1Temp
: _data.nodeTemp == "2"
? _data.child2Temp
: _data.nodeTemp == "3"
? _data.child3Temp
: _data.nodeTemp == "4"
? _data.child4Temp
: null,
draftPositionEmployee: _data.positionTemp,
draftOrgEmployeeStatus: _data.statusTemp,
node: _data.nodeTemp,
nodeId: _data.nodeIdTemp,
nodeName:
_data.nodeTemp == "0"
? _data.rootTemp
: _data.nodeTemp == "1"
? _data.child1Temp
: _data.nodeTemp == "2"
? _data.child2Temp
: _data.nodeTemp == "3"
? _data.child3Temp
: _data.nodeTemp == "4"
? _data.child4Temp
: null,
nodeShortName:
_data.nodeTemp == "0"
? _data.rootShortNameTemp
: _data.nodeTemp == "1"
? _data.child1ShortNameTemp
: _data.nodeTemp == "2"
? _data.child1ShortNameTemp
: _data.nodeTemp == "3"
? _data.child3ShortNameTemp
: _data.nodeTemp == "4"
? _data.child4ShortNameTemp
: null,
root: _data.rootTemp ? _data.rootTemp : null,
rootId: _data.rootIdTemp ? _data.rootIdTemp : null,
rootShortName: _data.rootShortNameTemp ? _data.rootShortNameTemp : null,
child1: _data.child1Temp ? _data.child1Temp : null,
child1Id: _data.child1IdTemp ? _data.child1IdTemp : null,
child1ShortName: _data.child1ShortNameTemp ? _data.child1ShortNameTemp : null,
child2: _data.child2Temp ? _data.child2Temp : null,
child2Id: _data.child2IdTemp ? _data.child2IdTemp : null,
child2ShortName: _data.child2ShortNameTemp ? _data.child2ShortNameTemp : null,
child3: _data.child3Temp ? _data.child3Temp : null,
child3Id: _data.child3IdTemp ? _data.child3IdTemp : null,
child3ShortName: _data.child3ShortNameTemp ? _data.child3ShortNameTemp : null,
child4: _data.child4Temp ? _data.child4Temp : null,
child4Id: _data.child4IdTemp ? _data.child4IdTemp : null,
child4ShortName: _data.child4ShortNameTemp ? _data.child4ShortNameTemp : null,
org:
(_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root),
orgTemp:
(_data.child4Temp == null ? "" : _data.child4Temp + "\n") +
(_data.child3Temp == null ? "" : _data.child3Temp + "\n") +
(_data.child2Temp == null ? "" : _data.child2Temp + "\n") +
(_data.child1Temp == null ? "" : _data.child1Temp + "\n") +
(_data.rootTemp == null ? "" : _data.rootTemp),
};
}),
);
return new HttpSuccess({ data: data, total });
}
@Get("history/{id}")
async getProfileHistory(@Path() id: string, @Request() req: RequestWithUser) {
2024-10-22 08:20:45 +07:00
//await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", id); ไม่แน่ใจEMPปิดไว้ก่อน;
const profile = await this.profileHistoryRepo.find({
relations: {
posLevel: true,
posType: true,
},
where: { profileEmployeeId: id },
2024-09-02 15:35:12 +07:00
order: {
createdAt: "ASC",
},
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
return new HttpSuccess(profile);
}
/**
* API
*
* @summary ORG_063 - (ADMIN) #68
*
*/
@Post("search")
async searchProfileOrg(
@Body()
requestBody: {
position?: string;
posLevelId?: string;
posTypeId?: string;
page: number;
pageSize: number;
keyword?: string;
},
) {
2024-03-21 10:41:18 +07:00
const orgRevision = await this.orgRevisionRepo.findOne({
where: {
orgRevisionIsDraft: false,
orgRevisionIsCurrent: true,
},
relations: ["employeePosMasters"],
});
if (!orgRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
}
2024-03-21 10:41:18 +07:00
const [profiles, total] = await this.profileRepo
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
.leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
.leftJoinAndSelect("profileEmployee.posType", "posType")
.where(
requestBody.position != null && requestBody.position != ""
? "profileEmployee.position LIKE :position"
: "1=1",
{
position: `%${requestBody.position}%`,
},
)
.andWhere("profileEmployee.isLeave IS FALSE")
.andWhere(
new Brackets((qb) => {
qb.where(
requestBody.keyword != null && requestBody.keyword != ""
? "profileEmployee.prefix LIKE :keyword"
: "1=1",
{
keyword: `%${requestBody.keyword}%`,
},
)
2025-05-01 13:35:54 +07:00
.orWhere(
requestBody.keyword != null && requestBody.keyword != ""
? "profileEmployee.firstName LIKE :keyword"
: "1=1",
{
keyword: `%${requestBody.keyword}%`,
},
)
.orWhere(
requestBody.keyword != null && requestBody.keyword != ""
? "profileEmployee.lastName LIKE :keyword"
: "1=1",
{
keyword: `%${requestBody.keyword}%`,
},
)
2025-07-11 16:46:52 +07:00
.orWhere(
requestBody.keyword != null && requestBody.keyword != ""
? "CONCAT(profileEmployee.prefix,profileEmployee.firstName,' ',profileEmployee.lastName) LIKE :keyword"
: "1=1",
{
keyword: `%${requestBody.keyword}%`,
},
)
.orWhere(
requestBody.keyword != null && requestBody.keyword != ""
? "CONCAT(profileEmployee.firstName,' ',profileEmployee.lastName) LIKE :keyword"
: "1=1",
{
keyword: `%${requestBody.keyword}%`,
},
)
2025-05-01 13:35:54 +07:00
.orWhere(
requestBody.keyword != null && requestBody.keyword != ""
? "profileEmployee.citizenId LIKE :keyword"
: "1=1",
{
keyword: `%${requestBody.keyword}%`,
},
);
}),
)
.andWhere(
requestBody.posTypeId != null && requestBody.posTypeId != ""
? "profileEmployee.posTypeId LIKE :posTypeId"
: "1=1",
{
posTypeId: `%${requestBody.posTypeId}%`,
},
)
.andWhere(
requestBody.posLevelId != null && requestBody.posLevelId != ""
? "profileEmployee.posLevelId LIKE :posLevelId"
: "1=1",
{
posLevelId: `%${requestBody.posLevelId}%`,
},
)
.andWhere(
new Brackets((qb) => {
qb.where("profileEmployee.id NOT IN (:...ids)", {
ids:
orgRevision.employeePosMasters
.filter((x) => x.current_holderId != null)
.map((x) => x.current_holderId).length == 0
? ["zxc"]
: orgRevision.employeePosMasters
2025-05-01 13:35:54 +07:00
.filter((x) => x.current_holderId != null)
.map((x) => x.current_holderId),
});
}),
2024-07-19 11:08:47 +07:00
)
.andWhere("profileEmployee.employeeClass = :employeeClass", { employeeClass: "PERM" })
.skip((requestBody.page - 1) * requestBody.pageSize)
.take(requestBody.pageSize)
.orderBy("posType.posTypeRank", "ASC")
.addOrderBy("posLevel.posLevelRank", "ASC")
.getManyAndCount();
2025-05-01 13:35:54 +07:00
const data = profiles.map((_data) => ({
id: _data.id,
prefix: _data.prefix,
rank: _data.rank,
firstName: _data.firstName,
lastName: _data.lastName,
citizenId: _data.citizenId,
2025-01-17 11:10:04 +07:00
posLevel:
_data.posLevel == null
? null
: `${_data?.posType?.posTypeShortName ?? ""} ${_data?.posLevel?.posLevelName ?? ""}`,
posType: _data.posType == null ? null : _data.posType.posTypeName,
position: _data.position,
}));
return new HttpSuccess({ data: data, total });
}
2024-12-24 18:04:19 +07:00
// /**
// * API ค้นหาประวัติการครองตำแหน่ง ลูกจ้าง
// *
// * @summary ค้นหาประวัติการครองตำแหน่ง ลูกจ้าง
// *
// */
// @Post("search/history/oc")
// async searchHistoryOC(
// @Body()
// requestBody: {
// posNo?: string;
// position?: string;
// },
// ) {
// const profiles = await this.profileRepo
// .createQueryBuilder("profileEmployee")
// .leftJoinAndSelect("profileEmployee.profileSalary", "profileSalary")
// .select([
// "profileEmployee.id",
// "profileEmployee.prefix",
// "profileEmployee.firstName",
// "profileEmployee.lastName",
// "profileEmployee.citizenId",
// "profileSalary.position",
// "profileSalary.posNo",
// "profileSalary.date",
// ])
// .andWhere(
// requestBody.position != null && requestBody.position != "" && requestBody.posNo == undefined
// ? "profileSalary.position LIKE :position"
// : "1=2",
// {
// position: `%${requestBody.position}%`,
// },
// )
// .orWhere(
// requestBody.posNo != null && requestBody.posNo != "" && requestBody.position == undefined
// ? "profileSalars.posNo LIKE :posNo"
// : "1=2",
// {
// posNo: `%${requestBody.posNo}%`,
// },
// )
// .getMany();
// const mapData = profiles.map((profile) => {
// let profileSalary;
// if (profile.profileSalary && profile.profileSalary.length > 0) {
// profileSalary = profile.profileSalary.reduce((latest, current) => {
// return new Date(current.date) > new Date(latest.date) ? current : latest;
// });
// }
// return {
// id: profile.id,
// fullName: `${profile.prefix}${profile.firstName} ${profile.lastName}`,
// citizenId: profile.citizenId,
// position: profileSalary ? profileSalary.position : null,
// posNo: profileSalary ? profileSalary.posNo : null,
// date: profileSalary ? profileSalary.date : null,
// };
// });
// return new HttpSuccess(mapData);
// }
2024-12-25 01:10:49 +07:00
/**
2024-12-24 18:04:19 +07:00
* API
*
2024-12-24 18:04:19 +07:00
* @summary
*
*/
2024-12-25 01:10:49 +07:00
@Post("search/history/oc")
async searchOC(
@Body()
requestBody: {
posNo?: string;
position?: string;
},
) {
let queryLike = `
2024-12-24 18:04:19 +07:00
CASE
2025-04-05 19:21:50 +07:00
WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT(orgChild4.orgChild4ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT(orgChild3.orgChild3ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT(orgChild2.orgChild2ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT(orgChild1.orgChild1ShortName, " ", current_holders.posMasterNo)
ELSE CONCAT(orgRoot.orgRootShortName, " ", current_holders.posMasterNo)
2024-12-24 18:04:19 +07:00
END LIKE :keyword
`;
2024-12-25 01:10:49 +07:00
const profiles = await this.profileRepo
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.positions", "positions")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
.where("positions.positionIsSelected = :posIsSelected", { posIsSelected: true })
.andWhere(
new Brackets((qb) => {
qb.orWhere(
requestBody.posNo != undefined && requestBody.posNo != null && requestBody.posNo != ""
? queryLike
: "1=1",
{
keyword: `%${requestBody.posNo}%`,
},
);
}),
)
.andWhere(
requestBody.position != null && requestBody.position !== ""
? "positions.positionName LIKE :positionName"
: "1=1",
{ positionName: `%${requestBody.position}%` },
2024-12-25 01:10:49 +07:00
)
.getMany();
const mapData = profiles
.map((profile) => {
const shortNames = profile.current_holders.map((holder) => {
const shortName =
holder.orgChild4?.orgChild4ShortName ||
holder.orgChild3?.orgChild3ShortName ||
holder.orgChild2?.orgChild2ShortName ||
holder.orgChild1?.orgChild1ShortName ||
holder.orgRoot?.orgRootShortName;
2025-04-05 19:21:50 +07:00
return `${shortName || ""} ${holder.posMasterNo || ""}`;
2024-12-25 01:10:49 +07:00
});
return profile.current_holders.map((holder, index) => {
const position = holder.positions.find((position) => position.posMasterId === holder.id);
const positionName = position ? position.positionName : null;
return {
id: profile.id,
posMasterId: holder.id,
fullName: `${profile.prefix}${profile.firstName} ${profile.lastName}`,
citizenId: profile.citizenId,
posNo: shortNames[index],
positionName: positionName,
date: holder.createdAt,
};
});
})
.flat();
return new HttpSuccess(mapData);
}
/**
* API keycloak
*
* @summary ORG_065 - keycloak (ADMIN) #70
*
*/
@Get("keycloak/position")
2024-09-26 18:11:59 +07:00
async getProfileByKeycloak(
@Request() request: { user: Record<string, any> },
@Query("revisionId") revisionId?: string,
) {
2024-03-21 10:41:18 +07:00
const profile = await this.profileRepo.findOne({
where: { keycloak: request.user.sub },
2024-09-26 18:11:59 +07:00
relations: [
"posLevel",
"posType",
"current_holders",
"current_holders.orgRoot",
"current_holders.orgChild1",
"current_holders.orgChild2",
"current_holders.orgChild3",
"current_holders.orgChild4",
"profileSalary",
2024-09-26 18:11:59 +07:00
],
2024-09-25 10:58:28 +07:00
order: {
profileSalary: {
2024-09-25 10:58:28 +07:00
order: "DESC",
2024-09-26 18:11:59 +07:00
},
},
});
if (!profile) {
2024-11-21 15:39:38 +07:00
if (request.user.role.includes("SUPER_ADMIN")) {
return new HttpSuccess(null);
} else {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
}
}
2024-09-27 14:12:18 +07:00
let orgRevisionPublish: any = await this.orgRevisionRepo
.createQueryBuilder("orgRevision")
.where("orgRevision.orgRevisionIsDraft = false")
.andWhere("orgRevision.orgRevisionIsCurrent = true")
.getOne();
if (!orgRevisionPublish) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
}
2024-09-26 18:11:59 +07:00
if (revisionId) {
2024-09-27 13:50:26 +07:00
orgRevisionPublish = await this.orgRevisionRepo
2024-09-26 18:11:59 +07:00
.createQueryBuilder("orgRevision")
.where("orgRevision.id = :revisionId", { revisionId })
.getOne();
if (!orgRevisionPublish) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
}
}
2024-11-06 10:32:02 +07:00
const posMaster =
profile.current_holders == null ||
profile.current_holders.length == 0 ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id);
const root =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot;
const child1 =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1 ==
null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1;
const child2 =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2 ==
null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2;
const child3 =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3 ==
null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3;
const child4 =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4 ==
null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4;
2025-02-18 23:02:38 +07:00
const position = await this.employeePositionRepository.findOne({
2024-11-06 10:32:02 +07:00
where: {
posMasterId: posMaster?.id,
},
});
const _profile: any = {
profileId: profile.id,
prefix: profile.prefix,
2024-11-06 10:32:02 +07:00
rank: profile.rank,
avatar: profile.avatar,
isProbation: profile.isProbation,
avatarName: profile.avatarName,
firstName: profile.firstName,
lastName: profile.lastName,
citizenId: profile.citizenId,
2024-11-06 10:32:02 +07:00
birthDate: profile.birthDate,
position: profile.position,
2024-11-06 10:32:02 +07:00
leaveDate: profile.dateLeave,
dateStart: profile.dateStart,
dateRetireLaw: profile.dateRetireLaw,
posMaster: posMaster == null ? null : posMaster.posMasterNo,
posMasterNo: posMaster == null ? null : posMaster.posMasterNo,
posLevelName:
profile.posLevel == null && profile.posType == null
? null
: `${profile.posType.posTypeShortName} ${profile.posLevel.posLevelName}`,
posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank,
posLevelId: profile.posLevel == null ? null : profile.posLevel.id,
posTypeName: profile.posType == null ? null : profile.posType.posTypeName,
posTypeShortName: profile.posType == null ? null : profile.posType.posTypeShortName,
posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
posTypeId: profile.posType == null ? null : profile.posType.id,
2025-02-18 23:02:38 +07:00
posExecutiveName: null,
posExecutivePriority: null,
posExecutiveId: null,
2024-11-06 10:32:02 +07:00
rootId: root == null ? null : root.id,
2025-02-05 15:38:21 +07:00
rootDnaId: root == null ? null : root.ancestorDNA,
2024-11-06 10:32:02 +07:00
root: root == null ? null : root.orgRootName,
rootShortName: root == null ? null : root.orgRootShortName,
child1Id: child1 == null ? null : child1.id,
2025-02-05 15:38:21 +07:00
child1DnaId: child1 == null ? null : child1.ancestorDNA,
2024-11-06 10:32:02 +07:00
child1: child1 == null ? null : child1.orgChild1Name,
child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
child2Id: child2 == null ? null : child2.id,
2025-02-05 15:38:21 +07:00
child2DnaId: child2 == null ? null : child2.ancestorDNA,
2024-11-06 10:32:02 +07:00
child2: child2 == null ? null : child2.orgChild2Name,
child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
child3Id: child3 == null ? null : child3.id,
2025-02-05 15:38:21 +07:00
child3DnaId: child3 == null ? null : child3.ancestorDNA,
2024-11-06 10:32:02 +07:00
child3: child3 == null ? null : child3.orgChild3Name,
child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
child4Id: child4 == null ? null : child4.id,
2025-02-05 15:38:21 +07:00
child4DnaId: child4 == null ? null : child4.ancestorDNA,
2024-11-06 10:32:02 +07:00
child4: child4 == null ? null : child4.orgChild4Name,
child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
node: null,
nodeId: null,
2025-02-03 15:40:44 +07:00
nodeDnaId: null,
salary: profile ? profile.amount : null,
2024-12-25 01:10:49 +07:00
amountSpecial: profile ? profile.amountSpecial : null,
posNo: null
// root?.orgRootShortName && posMaster?.posMasterNo
// ? `${root?.orgRootShortName} ${posMaster?.posMasterNo}`
// : "",
2024-09-26 18:11:59 +07:00
};
if (_profile.child4Id != null) {
_profile.node = 4;
_profile.nodeId = _profile.child4Id;
_profile.nodeDnaId = _profile.child4DnaId;
_profile.nodeShortName = _profile.child4ShortName;
_profile.posNo = `${_profile.child4ShortName} ${_profile.posMasterNo}`;
} else if (_profile.child3Id != null) {
_profile.node = 3;
_profile.nodeId = _profile.child3Id;
_profile.nodeDnaId = _profile.child3DnaId;
_profile.nodeShortName = _profile.child3ShortName;
_profile.posNo = `${_profile.child3ShortName} ${_profile.posMasterNo}`;
} else if (_profile.child2Id != null) {
_profile.node = 2;
_profile.nodeId = _profile.child2Id;
_profile.nodeDnaId = _profile.child2DnaId;
_profile.nodeShortName = _profile.child2ShortName;
_profile.posNo = `${_profile.child2ShortName} ${_profile.posMasterNo}`;
} else if (_profile.child1Id != null) {
_profile.node = 1;
_profile.nodeId = _profile.child1Id;
_profile.nodeDnaId = _profile.child1DnaId;
_profile.nodeShortName = _profile.child1ShortName;
_profile.posNo = `${_profile.child1ShortName} ${_profile.posMasterNo}`;
} else if (_profile.rootId != null) {
_profile.node = 0;
_profile.nodeId = _profile.rootId;
_profile.nodeDnaId = _profile.rootDnaId;
_profile.nodeShortName = _profile.rootShortName;
_profile.posNo = `${_profile.rootShortName} ${_profile.posMasterNo}`;
}
return new HttpSuccess(_profile);
}
/**
* API
*
* @summary ORG_065 - (ADMIN) #70
*
*/
@Post("search-personal")
async getProfileBySearchKeyword(
@Request() request: RequestWithUser,
2024-06-13 17:38:01 +07:00
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Body()
body: {
fieldName: string;
keyword?: string;
2025-09-08 00:10:59 +07:00
system?: string;
},
) {
// ค้นหารายชื่อถ้าไม่ส่ง system มาให้ default ตามทะเบียนประวัติ
2025-09-08 00:10:59 +07:00
let _system: string = "SYS_REGISTRY_EMP";
if (body.system) _system = body.system;
let _data = await new permission().PermissionOrgList(request, _system);
2025-09-08 00:10:59 +07:00
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
2025-09-08 00:10:59 +07:00
let queryLike = "1=1";
switch (body.fieldName) {
2024-06-13 17:38:01 +07:00
case "citizenId":
queryLike = "profile.citizenId LIKE :keyword";
break;
2024-12-16 16:45:53 +07:00
case "fullName":
2025-09-08 00:10:59 +07:00
queryLike =
"CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword";
2024-12-16 16:45:53 +07:00
break;
case "position":
queryLike = "profile.position LIKE :keyword";
break;
2024-12-16 16:45:53 +07:00
case "posNo":
2025-09-08 00:10:59 +07:00
queryLike = `
CASE
WHEN current_holders.orgChild4Id IS NOT NULL THEN CONCAT(orgChild4.orgChild4ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild3Id IS NOT NULL THEN CONCAT(orgChild3.orgChild3ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild2Id IS NOT NULL THEN CONCAT(orgChild2.orgChild2ShortName, " ", current_holders.posMasterNo)
WHEN current_holders.orgChild1Id IS NOT NULL THEN CONCAT(orgChild1.orgChild1ShortName, " ", current_holders.posMasterNo)
ELSE CONCAT(orgRoot.orgRootShortName, " ", current_holders.posMasterNo)
END LIKE :keyword
`;
2024-12-16 16:45:53 +07:00
break;
case "posType":
queryLike = "posType.posTypeName LIKE :keyword";
2024-12-16 16:45:53 +07:00
break;
case "posLevel":
queryLike = "posLevel.posLevelName LIKE :keyword";
break;
2024-12-16 16:45:53 +07:00
case "organization":
queryLike = "orgRoot.orgRootName LIKE :keyword";
break;
default:
2025-09-08 00:10:59 +07:00
queryLike = "1=1";
break;
}
2025-09-08 00:10:59 +07:00
const [findProfile, total] = await this.profileRepo
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.posType", "posType")
.leftJoinAndSelect("profile.posLevel", "posLevel")
.leftJoinAndSelect("profile.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
.where("current_holders.orgRevision = :revisionId", { revisionId: findRevision?.id })
.andWhere(
_data.root != undefined && _data.root != null
? _data.root[0] != null
? `current_holders.orgRootId IN (:...root)`
: `current_holders.orgRootId is null`
: "1=1",
{ root: _data.root },
)
.andWhere(
_data.child1 != undefined && _data.child1 != null
? _data.child1[0] != null
? `current_holders.orgChild1Id IN (:...child1)`
: `current_holders.orgChild1Id is null`
: "1=1",
{ child1: _data.child1 },
)
.andWhere(
_data.child2 != undefined && _data.child2 != null
? _data.child2[0] != null
? `current_holders.orgChild2Id IN (:...child2)`
: `current_holders.orgChild2Id is null`
: "1=1",
{ child2: _data.child2 },
)
.andWhere(
_data.child3 != undefined && _data.child3 != null
? _data.child3[0] != null
? `current_holders.orgChild3Id IN (:...child3)`
: `current_holders.orgChild3Id is null`
: "1=1",
{ child3: _data.child3 },
)
.andWhere(
_data.child4 != undefined && _data.child4 != null
? _data.child4[0] != null
? `current_holders.orgChild4Id IN (:...child4)`
: `current_holders.orgChild4Id is null`
: "1=1",
{ child4: _data.child4 },
)
.andWhere(
new Brackets((qb) => {
qb.orWhere(body.keyword ? queryLike : "1=1", { keyword: `%${body.keyword}%` });
}),
)
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
const mapDataProfile = await Promise.all(
findProfile.map(async (item: ProfileEmployee) => {
2024-12-16 16:45:53 +07:00
const fullName = `${item.prefix}${item.firstName} ${item.lastName}`;
const shortName =
item.current_holders.length == 0
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild2 != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild1 != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgRoot != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: null;
const root =
item.current_holders.length == 0 ||
(item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null)
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;
2024-05-24 13:13:52 +07:00
const rootHolder = item.current_holders?.find(
(x) => x.orgRevisionId == findRevision.id,
)?.orgRoot;
const child1Holder = item.current_holders?.find(
(x) => x.orgRevisionId == findRevision.id,
)?.orgChild1;
const child2Holder = item.current_holders?.find(
(x) => x.orgRevisionId == findRevision.id,
)?.orgChild2;
const child3Holder = item.current_holders?.find(
(x) => x.orgRevisionId == findRevision.id,
)?.orgChild3;
const child4Holder = item.current_holders?.find(
(x) => x.orgRevisionId == findRevision.id,
)?.orgChild4;
2024-05-28 15:01:15 +07:00
const posMasterNo = item.current_holders?.find(
(x) => x.orgRevisionId == findRevision.id,
)?.posMasterNo;
2024-05-24 13:13:52 +07:00
2025-01-06 23:58:24 +07:00
const latestProfileEducation = await this.profileEducationRepo.findOne({
where: { profileEmployeeId: item.id },
2025-01-06 23:58:24 +07:00
order: { level: "ASC" },
});
2024-06-12 17:50:48 +07:00
return {
id: item.id,
prefix: item.prefix,
rank: item.rank,
firstName: item.firstName,
lastName: item.lastName,
position: item.position,
2024-06-13 17:38:01 +07:00
citizenId: item.citizenId,
email: item.email,
phone: item.phone,
name: fullName,
2024-06-12 17:50:48 +07:00
birthDate: item.birthDate,
positionLevel: item.posLevelId,
2025-02-25 18:24:38 +07:00
positionLevelName: item.posLevel?.posLevelName,
positionType: item.posTypeId,
positionTypeName: item.posType?.posTypeName,
posNo: shortName,
2024-12-19 15:46:14 +07:00
organization: root == null ? null : root.orgRootName,
2024-12-19 14:53:35 +07:00
salary: item.amount,
root: rootHolder?.orgRootName ?? null,
rootId: rootHolder?.id ?? null,
2025-02-06 09:17:35 +07:00
rootDnaId: rootHolder?.ancestorDNA ?? null,
rootShortName: rootHolder?.orgRootShortName ?? null,
child1: child1Holder?.orgChild1Name ?? null,
child1Id: child1Holder?.id ?? null,
2025-02-06 09:17:35 +07:00
child1DnaId: child1Holder?.ancestorDNA ?? null,
child1ShortName: child1Holder?.orgChild1ShortName ?? null,
child2: child2Holder?.orgChild2Name ?? null,
child2Id: child2Holder?.id ?? null,
2025-02-06 09:17:35 +07:00
child2DnaId: child2Holder?.ancestorDNA ?? null,
child2ShortName: child2Holder?.orgChild2ShortName ?? null,
child3: child3Holder?.orgChild3Name ?? null,
child3Id: child3Holder?.id ?? null,
2025-02-06 09:17:35 +07:00
child3DnaId: child3Holder?.ancestorDNA ?? null,
child3ShortName: child3Holder?.orgChild3ShortName ?? null,
child4: child4Holder?.orgChild4Name ?? null,
child4Id: child4Holder?.id ?? null,
2025-02-06 09:17:35 +07:00
child4DnaId: child4Holder?.ancestorDNA ?? null,
child4ShortName: child4Holder?.orgChild4ShortName ?? null,
2024-05-28 15:01:15 +07:00
posMasterNo: posMasterNo ?? null,
posTypeId: item.posTypeId,
posTypeName: item.posType?.posTypeName,
posLevelId: item.posLevelId,
posLevelName:
item.posLevel == null && item.posType == null
? null
: `${item.posType?.posTypeShortName} ${item.posLevel?.posLevelName}`,
2024-06-13 11:59:09 +07:00
educationDegree:
latestProfileEducation != null && latestProfileEducation.educationLevel != null
? latestProfileEducation.educationLevel
: null,
};
}),
);
2024-06-13 17:38:01 +07:00
return new HttpSuccess({ data: mapDataProfile, total });
}
/**
* API
*
* @summary ORG_069 - (ADMIN) #75
*
*/
@Get("search/commander")
async searchCommander(@Request() request: { user: Record<string, any> }) {
let fullName_: any = {};
let position_: any = {};
let commanderAboveFullname_: any = {};
let commanderAbovePosition_: any = {};
let commanderFullname_: any = {};
let commanderPosition_: any = {};
2024-03-21 10:41:18 +07:00
const findProfile = await this.profileRepo.findOne({
where: { keycloak: request.user.sub },
});
2024-03-21 10:41:18 +07:00
const findRevision = await this.orgRevisionRepo.findOne({
where: {
orgRevisionIsCurrent: true,
},
});
2024-03-21 10:41:18 +07:00
const findPosMaster = await this.posMasterRepo.findOne({
where: {
current_holderId: findProfile?.id,
orgRevisionId: findRevision?.id,
},
});
let node = 4;
let childId = findPosMaster?.orgChild4Id;
let condition: any = { orgChild4Id: childId };
if (findPosMaster?.orgChild4Id == null && findPosMaster?.orgChild3Id != null) {
node = 3;
childId = findPosMaster?.orgChild3Id;
condition = { orgChild3Id: childId, orgChild4Id: IsNull() };
} else if (findPosMaster?.orgChild3Id == null && findPosMaster?.orgChild2Id != null) {
node = 2;
childId = findPosMaster?.orgChild2Id;
condition = { orgChild2Id: childId, orgChild3Id: IsNull() };
} else if (findPosMaster?.orgChild2Id == null && findPosMaster?.orgChild1Id != null) {
node = 1;
childId = findPosMaster?.orgChild1Id;
condition = { orgChild1Id: childId, orgChild2Id: IsNull() };
} else if (findPosMaster?.orgChild1Id == null) {
node = 0;
childId = findPosMaster?.orgRootId;
condition = { orgRootId: childId, orgChild1Id: IsNull() };
}
2024-03-21 10:41:18 +07:00
const findCmd = await this.posMasterRepo.findOne({
where: {
current_holderId: Not(IsNull()) || Not(""),
orgRevisionId: findRevision?.id,
...condition,
},
relations: ["current_holder"],
order: { posMasterOrder: "ASC" },
});
let findOSAB: EmployeePosMaster | null = null;
let findTSAB: EmployeePosMaster | null = null;
//หาผู้บังคับบัญชาที่เหนือขึ้นไปอีก 1 ขั้น
if (node !== 0) {
findOSAB = await AppDataSource.getRepository(EmployeePosMaster)
.createQueryBuilder("posMaster")
.leftJoinAndSelect("posMaster.current_holder", "current_holder")
.where("posMaster.current_holderId IS NOT NULL")
.andWhere("posMaster.orgRevisionId = :revisionId", { revisionId: findRevision?.id })
.andWhere(
new Brackets((qb) => {
if (node === 4) {
qb.andWhere("posMaster.orgChild4Id IS NULL");
qb.andWhere("posMaster.orgChild3Id = :childId", {
childId: findPosMaster?.orgChild3Id,
});
} else if (node === 3) {
qb.andWhere("posMaster.orgChild3Id IS NULL");
qb.andWhere("posMaster.orgChild2Id = :childId", {
childId: findPosMaster?.orgChild2Id,
});
} else if (node === 2) {
qb.andWhere("posMaster.orgChild2Id IS NULL");
qb.andWhere("posMaster.orgChild1Id = :childId", {
childId: findPosMaster?.orgChild1Id,
});
} else if (node === 1) {
qb.andWhere("posMaster.orgChild1Id IS NULL");
qb.andWhere("posMaster.orgRootId = :childId", { childId: findPosMaster?.orgRootId });
}
}),
)
.orderBy("posMaster.posMasterOrder", "ASC")
.getOne();
}
//หาผู้บังคับบัญชาที่เหนือขึ้นไปอีก 2 ขั้น
if (node !== 0 && node !== 1) {
findTSAB = await AppDataSource.getRepository(EmployeePosMaster)
.createQueryBuilder("posMaster")
.leftJoinAndSelect("posMaster.current_holder", "current_holder")
.where("posMaster.current_holderId IS NOT NULL")
.andWhere("posMaster.orgRevisionId = :revisionId", { revisionId: findRevision?.id })
.andWhere(
new Brackets((qb) => {
if (node === 4) {
qb.andWhere("posMaster.orgChild3Id IS NULL");
qb.andWhere("posMaster.orgChild2Id = :childId", {
childId: findPosMaster?.orgChild2Id,
});
} else if (node === 3) {
qb.andWhere("posMaster.orgChild2Id IS NULL");
qb.andWhere("posMaster.orgChild1Id = :childId", {
childId: findPosMaster?.orgChild1Id,
});
} else if (node === 2) {
qb.andWhere("posMaster.orgChild1Id IS NULL");
qb.andWhere("posMaster.orgRootId = :childId", {
childId: findPosMaster?.orgRootId,
});
}
}),
)
.orderBy("posMaster.posMasterOrder", "ASC")
.getOne();
}
fullName_ =
(findProfile?.prefix ?? "") +
(findProfile?.firstName ?? "") +
(findProfile?.firstName ? " " : "") +
(findProfile?.lastName ?? "");
position_ = findProfile?.position ?? "";
commanderFullname_ =
(findCmd?.current_holder?.prefix ?? "") +
(findCmd?.current_holder?.firstName ?? "") +
(findCmd?.current_holder?.firstName ? " " : "") +
(findCmd?.current_holder?.lastName ?? "");
commanderPosition_ = findCmd?.current_holder?.position ?? "";
commanderAboveFullname_ =
(findOSAB?.current_holder?.prefix ?? "") +
(findOSAB?.current_holder?.firstName ?? "") +
(findOSAB?.current_holder?.firstName ? " " : "") +
(findOSAB?.current_holder?.lastName ?? "");
commanderAbovePosition_ = findOSAB?.current_holder?.position ?? "";
if (findCmd?.current_holderId == findProfile?.id) {
commanderFullname_ =
(findOSAB?.current_holder?.prefix ?? "") +
(findOSAB?.current_holder?.firstName ?? "") +
(findOSAB?.current_holder?.firstName ? " " : "") +
(findOSAB?.current_holder?.lastName ?? "");
commanderPosition_ = findOSAB?.current_holder?.position ?? "";
commanderAboveFullname_ =
(findTSAB?.current_holder?.prefix ?? "") +
(findTSAB?.current_holder?.firstName ?? "") +
(findTSAB?.current_holder?.firstName ? " " : "") +
(findTSAB?.current_holder?.lastName ?? "");
commanderAbovePosition_ = findTSAB?.current_holder?.position ?? "";
const formattedDataTSAB = {
fullname: fullName_,
position: position_,
commanderAboveFullname: commanderAboveFullname_,
commanderAbovePosition: commanderAbovePosition_,
commanderFullname: commanderFullname_,
commanderPosition: commanderPosition_,
};
return new HttpSuccess(formattedDataTSAB);
}
const formattedData = {
fullname: fullName_,
position: position_,
commanderAboveFullname: commanderAboveFullname_,
commanderAbovePosition: commanderAbovePosition_,
commanderFullname: commanderFullname_,
commanderPosition: commanderPosition_,
};
return new HttpSuccess(formattedData);
}
/**
* API
*
* @summary (ADMIN)
*
* @param {string} id Id
*/
@Put("position/{id}")
async positionProfileEmployee(
@Request() request: RequestWithUser,
@Path() id: string,
@Body() body: UpdatePositionTempProfileEmployee,
) {
2024-08-27 16:15:41 +07:00
// await new permission().PermissionOrgUserUpdate(request, "SYS_REGISTRY_EMP", id);//ไม่แน่ใจEMPปิดไว้ก่อน
if (body.posLevelId === "") body.posLevelId = null;
if (body.posTypeId === "") body.posTypeId = null;
if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
}
if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
const profileEmp = await this.profileRepo.findOneBy({ id });
if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");
switch (body.node) {
case 0: {
const data = await this.orgRootRepository.findOne({
where: { id: body.nodeId },
});
if (data != null) {
profileEmp.rootIdTemp = data.id;
profileEmp.rootTemp = data.orgRootName;
profileEmp.rootShortNameTemp = data.orgRootShortName;
}
}
case 1: {
const data = await this.child1Repository.findOne({
where: { id: body.nodeId },
2024-06-07 03:05:57 +07:00
relations: ["orgRoot"],
});
if (data != null) {
profileEmp.rootIdTemp = data.orgRoot.id;
profileEmp.rootTemp = data.orgRoot.orgRootName;
profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName;
profileEmp.child1IdTemp = data.id;
profileEmp.child1Temp = data.orgChild1Name;
profileEmp.child1ShortNameTemp = data.orgChild1ShortName;
}
}
case 2: {
const data = await this.child2Repository.findOne({
where: { id: body.nodeId },
2024-06-07 03:05:57 +07:00
relations: ["orgRoot", "orgChild1"],
});
if (data != null) {
profileEmp.rootIdTemp = data.orgRoot.id;
profileEmp.rootTemp = data.orgRoot.orgRootName;
profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName;
profileEmp.child1IdTemp = data.orgChild1.id;
profileEmp.child1Temp = data.orgChild1.orgChild1Name;
profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName;
profileEmp.child2IdTemp = data.id;
profileEmp.child2Temp = data.orgChild2Name;
profileEmp.child2ShortNameTemp = data.orgChild2ShortName;
}
}
case 3: {
const data = await this.child3Repository.findOne({
where: { id: body.nodeId },
2024-06-07 03:05:57 +07:00
relations: ["orgRoot", "orgChild1", "orgChild2"],
});
if (data != null) {
profileEmp.rootIdTemp = data.orgRoot.id;
profileEmp.rootTemp = data.orgRoot.orgRootName;
profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName;
profileEmp.child1IdTemp = data.orgChild1.id;
profileEmp.child1Temp = data.orgChild1.orgChild1Name;
profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName;
profileEmp.child2IdTemp = data.orgChild2.id;
profileEmp.child2Temp = data.orgChild2.orgChild2Name;
profileEmp.child2ShortNameTemp = data.orgChild2.orgChild2ShortName;
profileEmp.child3IdTemp = data.id;
profileEmp.child3Temp = data.orgChild3Name;
profileEmp.child3ShortNameTemp = data.orgChild3ShortName;
}
}
case 4: {
const data = await this.child4Repository.findOne({
where: { id: body.nodeId },
2024-06-07 03:05:57 +07:00
relations: ["orgRoot", "orgChild1", "orgChild2", "orgChild3"],
});
if (data != null) {
profileEmp.rootIdTemp = data.orgRoot.id;
profileEmp.rootTemp = data.orgRoot.orgRootName;
profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName;
profileEmp.child1IdTemp = data.orgChild1.id;
profileEmp.child1Temp = data.orgChild1.orgChild1Name;
profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName;
profileEmp.child2IdTemp = data.orgChild2.id;
profileEmp.child2Temp = data.orgChild2.orgChild2Name;
profileEmp.child2ShortNameTemp = data.orgChild2.orgChild2ShortName;
profileEmp.child3IdTemp = data.orgChild3.id;
profileEmp.child3Temp = data.orgChild3.orgChild3Name;
profileEmp.child3ShortNameTemp = data.orgChild3.orgChild3ShortName;
profileEmp.child4IdTemp = data.id;
profileEmp.child4Temp = data.orgChild4Name;
profileEmp.child4ShortNameTemp = data.orgChild4ShortName;
}
}
}
profileEmp.lastUpdateUserId = request.user.sub;
profileEmp.lastUpdateFullName = request.user.name;
profileEmp.lastUpdatedAt = new Date();
profileEmp.nodeTemp = String(body.node);
profileEmp.nodeIdTemp = body.nodeId;
profileEmp.orgRevisionIdTemp = body.orgRevisionId;
profileEmp.posmasterIdTemp = body.posmasterId;
profileEmp.posMasterNoTemp = body.posMasterNo;
profileEmp.positionIdTemp = body.positionId;
profileEmp.positionTemp = body.position;
profileEmp.positionFieldTemp = body.positionField;
profileEmp.posTypeIdTemp = String(body.posTypeId);
profileEmp.posTypeNameTemp = body.posTypeName;
if (body.posTypeId != null) {
const posTypeTemp = await this.posTypeRepo.findOne({
where: { id: body.posTypeId },
});
if (posTypeTemp != null) {
profileEmp.posTypeShortNameTemp = posTypeTemp.posTypeShortName;
}
}
profileEmp.posLevelIdTemp = String(body.posLevelId);
profileEmp.posLevelNameTemp = body.posLevelName;
2024-06-10 18:18:39 +07:00
profileEmp.statusTemp = "PENDING";
// this.profileRepo.merge(profileEmp, body);
await this.profileRepo.save(profileEmp);
return new HttpSuccess();
}
/**
* API
*
* @summary (ADMIN)
*
* @param {string} id Id
*/
@Put("citizenId/{id}")
async checkCitizenIdProfile(
@Path() id: string,
@Request() req: RequestWithUser,
@Body()
requestBody: { citizenId: string },
) {
2024-03-21 10:41:18 +07:00
const profile = await this.profileRepo.findOne({
where: { id: Not(id), citizenId: requestBody.citizenId },
});
if (profile) {
throw new HttpError(
HttpStatus.INTERNAL_SERVER_ERROR,
"เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว",
);
}
return new HttpSuccess();
}
/**
* API
*
* @summary (ADMIN)
*
*/
@Post("probation")
async getProfileBySearchKeywordProbation(
2024-10-30 17:53:52 +07:00
@Request() request: RequestWithUser,
@Body()
body: {
page: number;
pageSize: number;
keyword?: string;
},
) {
2024-10-30 17:53:52 +07:00
let _data: any = {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
if (!request.user.role.includes("SUPER_ADMIN")) {
_data = await new permission().PermissionOrgCreate(request, "SYS_PROBATION");
}
const [findProfile, total] = await AppDataSource.getRepository(ProfileEmployee)
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.posLevel", "posLevel")
.leftJoinAndSelect("profile.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
2025-02-18 23:02:38 +07:00
.andWhere("profile.isLeave = false")
2024-10-30 17:53:52 +07:00
.andWhere(
_data.root != undefined && _data.root != null
? _data.root[0] != null
? `current_holders.orgRootId IN (:...root)`
: `current_holders.orgRootId is null`
: "1=1",
{
root: _data.root,
},
)
.andWhere(
_data.child1 != undefined && _data.child1 != null
? _data.child1[0] != null
? `current_holders.orgChild1Id IN (:...child1)`
: `current_holders.orgChild1Id is null`
: "1=1",
{
child1: _data.child1,
},
)
.andWhere(
_data.child2 != undefined && _data.child2 != null
? _data.child2[0] != null
? `current_holders.orgChild2Id IN (:...child2)`
: `current_holders.orgChild2Id is null`
: "1=1",
{
child2: _data.child2,
},
)
.andWhere(
_data.child3 != undefined && _data.child3 != null
? _data.child3[0] != null
? `current_holders.orgChild3Id IN (:...child3)`
: `current_holders.orgChild3Id is null`
: "1=1",
{
child3: _data.child3,
},
)
.andWhere(
_data.child4 != undefined && _data.child4 != null
? _data.child4[0] != null
? `current_holders.orgChild4Id IN (:...child4)`
: `current_holders.orgChild4Id is null`
: "1=1",
{
child4: _data.child4,
},
)
.andWhere(
new Brackets((qb) => {
2024-12-25 01:10:49 +07:00
qb.orWhere(
"CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword",
{ keyword: `%${body.keyword}%` },
)
// .orWhere("profile.firstName LIKE :keyword", { keyword: `%${body.keyword}%` })
// .orWhere("profile.lastName LIKE :keyword", { keyword: `%${body.keyword}%` })
2024-10-30 17:53:52 +07:00
.orWhere("profile.position LIKE :keyword", { keyword: `%${body.keyword}%` })
.orWhere("posLevel.posLevelName LIKE :keyword", { keyword: `%${body.keyword}%` });
}),
)
.orderBy("profile.citizenId", "ASC")
.skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
2024-03-21 10:41:18 +07:00
const orgRevisionActive = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
});
const mapDataProfile = await Promise.all(
findProfile.map(async (item: ProfileEmployee) => {
return {
id: item.id,
rank: item.rank,
prefix: item.prefix,
firstName: item.firstName,
lastName: item.lastName,
position: item.position,
idcard: item.citizenId,
posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName,
isProbation: item.isProbation,
orgRootName:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot
?.orgRootName == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot
?.orgRootName,
orgChild1Name:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1 ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1
?.orgChild1Name == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
?.orgChild1?.orgChild1Name,
orgChild2Name:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2 ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2
?.orgChild2Name == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
?.orgChild2?.orgChild2Name,
orgChild3Name:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3 ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3
?.orgChild3Name == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
?.orgChild3?.orgChild3Name,
orgChild4Name:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4 ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4
?.orgChild4Name == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
?.orgChild4?.orgChild4Name,
};
}),
);
return new HttpSuccess({ data: mapDataProfile, total });
}
/**
* API
*
* @summary (ADMIN)
*
*/
@Post("retire")
async getProfileBySearchKeywordRetire(
@Body()
body: {
page: number;
pageSize: number;
keyword?: string;
},
) {
let conditionFullName =
"CONCAT(profileEmployee.prefix, profileEmployee.firstName, ' ', profileEmployee.lastName) LIKE :keyword";
const [findProfile, total] = await AppDataSource.getRepository(ProfileEmployee)
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
.leftJoinAndSelect("profileEmployee.posType", "posType")
.leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
.leftJoinAndSelect("current_holders.positions", "positions")
.where(`profileEmployee.position LIKE :keyword`, {
keyword: `%${body.keyword}%`,
})
.orWhere(`profileEmployee.prefix LIKE :keyword`, {
keyword: `%${body.keyword}%`,
})
.orWhere(`profileEmployee.firstName LIKE :keyword`, {
keyword: `%${body.keyword}%`,
})
.orWhere(`profileEmployee.lastName LIKE :keyword`, {
keyword: `%${body.keyword}%`,
})
.orWhere(`posLevel.posLevelName LIKE :keyword`, {
keyword: `%${body.keyword}%`,
})
.orWhere(`posType.posTypeName LIKE :keyword`, {
keyword: `%${body.keyword}%`,
})
.orWhere(conditionFullName, {
keyword: `%${body.keyword}%`,
})
2025-01-21 12:38:27 +07:00
.andWhere("profileEmployee.isLeave = false")
.orderBy("profileEmployee.citizenId", "ASC")
.skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
const orgRevisionActive = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
});
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
const mapDataProfile = await Promise.all(
findProfile.map(async (item: ProfileEmployee) => {
const posMaster =
item.current_holders == null ||
item.current_holders.length == 0 ||
item.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id);
const position =
posMaster == null ||
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions == null ||
item.current_holders?.find((x) => x.orgRevisionId == findRevision.id)?.positions.length ==
0 ||
item.current_holders
.find((x) => x.orgRevisionId == findRevision.id)
?.positions?.find((position) => position.positionIsSelected == true) == null
? null
: item.current_holders
.find((x) => x.orgRevisionId == findRevision.id)
?.positions?.find((position) => position.positionIsSelected == true);
const shortName =
item.current_holders.length == 0
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild2 != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild1 != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgRoot != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: null;
return {
id: item.id,
prefix: item.prefix,
rank: item.rank,
firstName: item.firstName,
lastName: item.lastName,
position: item.position,
idcard: item.citizenId,
posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName,
posTypeName: item.posType == null ? null : item.posType.posTypeName,
2025-04-05 19:21:50 +07:00
posNo: `${shortName} ${posMaster == null ? null : posMaster.posMasterNo}`,
isProbation: item.isProbation,
orgRootName:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot
?.orgRootName == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot
?.orgRootName,
orgChild1Name:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1 ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1
?.orgChild1Name == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
?.orgChild1?.orgChild1Name,
orgChild2Name:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2 ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2
?.orgChild2Name == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
?.orgChild2?.orgChild2Name,
orgChild3Name:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3 ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3
?.orgChild3Name == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
?.orgChild3?.orgChild3Name,
orgChild4Name:
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4 ==
null ||
item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4
?.orgChild4Name == null
? null
: item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)
?.orgChild4?.orgChild4Name,
};
}),
);
return new HttpSuccess({ data: mapDataProfile, total });
}
/**
* API
*
* @summary ORG_072 - #76
*
*/
@Post("salary/gen")
async salaryGen(
@Body()
body: {
page: number;
pageSize: number;
keyword?: string;
rootId?: string;
year: number;
period: string;
2025-10-01 17:41:27 +07:00
sortBy?: string;
descending?: boolean;
},
) {
2024-03-21 10:41:18 +07:00
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
2025-10-01 17:41:27 +07:00
let query = await AppDataSource.getRepository(EmployeePosMaster)
.createQueryBuilder("employeePosMaster")
.leftJoinAndSelect("employeePosMaster.current_holder", "current_holder")
.leftJoinAndSelect("employeePosMaster.orgRoot", "orgRoot")
.leftJoinAndSelect("employeePosMaster.orgChild1", "orgChild1")
.leftJoinAndSelect("employeePosMaster.orgChild2", "orgChild2")
.leftJoinAndSelect("employeePosMaster.orgChild3", "orgChild3")
.leftJoinAndSelect("employeePosMaster.orgChild4", "orgChild4")
.leftJoinAndSelect("employeePosMaster.positions", "positions")
.leftJoinAndSelect("current_holder.profileSalary", "profileSalary")
2024-05-14 17:24:38 +07:00
.leftJoinAndSelect("current_holder.profileDisciplines", "profileDisciplines")
.leftJoinAndSelect("current_holder.posLevel", "posLevel")
.leftJoinAndSelect("current_holder.posType", "posType")
.where((qb) => {
if (body.rootId) {
qb.andWhere("employeePosMaster.orgRootId = :rootId", { rootId: body.rootId });
} else {
qb.andWhere("employeePosMaster.orgRevisionId = :orgRevisionId", {
orgRevisionId: findRevision?.id,
});
}
qb.andWhere("employeePosMaster.current_holderId IS NOT NULL");
})
.andWhere(
new Brackets((qb) => {
qb.where(
body.keyword != null && body.keyword != ""
? "current_holder.prefix LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "current_holder.firstName LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "current_holder.lastName LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "CONCAT(current_holder.prefix,current_holder.firstName,' ',current_holder.lastName) LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
2025-08-08 16:15:59 +07:00
.orWhere(
body.keyword != null && body.keyword != ""
? "CONCAT(orgRoot.orgRootShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "CONCAT(orgChild1.orgChild1ShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "CONCAT(orgChild2.orgChild2ShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "CONCAT(orgChild3.orgChild3ShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "CONCAT(orgChild4.orgChild4ShortName,' ',employeePosMaster.posMasterNo) LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "current_holder.position LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "current_holder.citizenId LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "posType.posTypeName LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
)
.orWhere(
body.keyword != null && body.keyword != ""
? "CONCAT(posType.posTypeShortName,' ',posLevel.posLevelName) LIKE :keyword"
: "1=1",
{
keyword: `%${body.keyword}%`,
},
);
}),
);
2025-10-01 17:41:27 +07:00
if (body.sortBy) {
if (body.sortBy === "posType") {
query = query.orderBy(`posType.posTypeName`, body.descending ? "DESC" : "ASC");
} else if (body.sortBy === "posLevel") {
2025-10-01 17:41:27 +07:00
query = query
.orderBy(`posType.posTypeShortName`, body.descending ? "DESC" : "ASC")
.addOrderBy(`posLevel.posLevelName`, body.descending ? "DESC" : "ASC");
} else if (body.sortBy === "orgShortName" || body.sortBy === "posMasterNo") {
2025-10-01 17:41:27 +07:00
query = query
.orderBy(`orgRoot.orgRootShortName`, body.descending ? "DESC" : "ASC")
.addOrderBy(`orgChild1.orgChild1ShortName`, body.descending ? "DESC" : "ASC")
.addOrderBy(`orgChild2.orgChild2ShortName`, body.descending ? "DESC" : "ASC")
.addOrderBy(`orgChild3.orgChild3ShortName`, body.descending ? "DESC" : "ASC")
.addOrderBy(`orgChild4.orgChild4ShortName`, body.descending ? "DESC" : "ASC")
.addOrderBy(`employeePosMaster.posMasterNo`, body.descending ? "DESC" : "ASC");
} else {
query = query.orderBy(`current_holder.${body.sortBy}`, body.descending ? "DESC" : "ASC");
2025-10-01 17:41:27 +07:00
}
} else {
query = query.orderBy("current_holder.citizenId", "ASC");
2025-10-01 17:41:27 +07:00
}
const [findPosMaster, total] = await query
.skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
2025-10-01 17:41:27 +07:00
if (!findPosMaster) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. PosMaster");
}
const formattedData = findPosMaster.map((item) => {
let orgShortName = "";
if (item.orgChild1Id === null) {
orgShortName = item.orgRoot?.orgRootShortName;
} else if (item.orgChild2Id === null) {
orgShortName = item.orgChild1?.orgChild1ShortName;
} else if (item.orgChild3Id === null) {
orgShortName = item.orgChild2?.orgChild2ShortName;
} else if (item.orgChild4Id === null) {
orgShortName = item.orgChild3?.orgChild3ShortName;
} else {
orgShortName = item.orgChild4?.orgChild4ShortName;
}
// const amount =
// item.current_holder == null || item.current_holder.profileSalary.length == 0
// ? null
// : item.current_holder.profileSalary.sort((a: any, b: any) => b.date - a.date)[0].amount;
2024-12-12 11:36:11 +07:00
const amount = item.current_holder ? item.current_holder.amount : null;
let datePeriodStart = new Date(
`${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, "0")}-${String(new Date().getDate() + 1).padStart(2, "0")}T00:00:00.000Z`,
);
let datePeriodEnd = new Date(
`${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, "0")}-${String(new Date().getDate() + 1).padStart(2, "0")}T00:00:00.000Z`,
);
if (body.period.toLocaleUpperCase() == "APR") {
datePeriodStart = new Date(`${body.year}-03-31T00:00:00.000Z`);
datePeriodEnd = new Date(`${body.year}-03-31T00:00:00.000Z`);
}
if (body.period.toLocaleUpperCase() == "OCT") {
datePeriodStart = new Date(`${body.year}-09-30T00:00:00.000Z`);
datePeriodEnd = new Date(`${body.year}-09-30T00:00:00.000Z`);
}
datePeriodStart = new Date(
new Date(datePeriodStart.setDate(datePeriodStart.getDate() + 1)).setMonth(
datePeriodStart.getMonth() - 6,
),
);
2024-05-28 14:17:45 +07:00
// const specialPosition = item.positions.find(
// (position) => position.positionIsSelected === true,
// );
// const isSpecial = specialPosition ? specialPosition.isSpecial : null;
return {
2024-05-28 14:17:45 +07:00
profileId: item.current_holder.id,
salaryLevel: item.current_holder.salaryLevel,
group: item.current_holder.group,
rank: item.current_holder.rank,
prefix: item.current_holder.prefix,
firstName: item.current_holder.firstName,
lastName: item.current_holder.lastName,
citizenId: item.current_holder.citizenId,
posMasterNoPrefix: item.posMasterNoPrefix,
posMasterNo: item.posMasterNo,
posMasterNoSuffix: item.posMasterNoSuffix,
orgShortName: orgShortName,
position: item.current_holder.position,
2024-03-19 11:30:44 +07:00
posType:
item.current_holder.posType == null ? null : item.current_holder.posType.posTypeName,
2024-03-21 16:57:44 +07:00
posTypeShort:
item.current_holder.posType == null ? null : item.current_holder.posType.posTypeShortName,
2024-03-19 11:30:44 +07:00
posLevel:
item.current_holder.posLevel == null ? null : item.current_holder.posLevel.posLevelName,
amount: amount ? amount : null,
rootId: item.orgRootId,
root: item.orgRoot?.orgRootName ? item.orgRoot.orgRootName : null,
child1Id: item.orgChild1Id,
child1: item.orgChild1?.orgChild1Name ? item.orgChild1.orgChild1Name : null,
child2Id: item.orgChild2Id,
child2: item.orgChild2?.orgChild2Name ? item.orgChild2.orgChild2Name : null,
child3Id: item.orgChild3Id,
child3: item.orgChild3?.orgChild3Name ? item.orgChild3.orgChild3Name : null,
child4Id: item.orgChild4Id,
child4: item.orgChild4?.orgChild4Name ? item.orgChild4.orgChild4Name : null,
result: null,
duration: null,
isPunish:
2024-05-14 17:24:38 +07:00
item.current_holder.profileDisciplines.filter(
(x: any) =>
new Date(
`${new Date(x.date).getFullYear()}-${String(new Date(x.date).getMonth() + 1).padStart(2, "0")}-${String(new Date(x.date).getDate() + 1).padStart(2, "0")}T00:00:00.000Z`,
) >= datePeriodStart &&
new Date(
`${new Date(x.date).getFullYear()}-${String(new Date(x.date).getMonth() + 1).padStart(2, "0")}-${String(new Date(x.date).getDate() + 1).padStart(2, "0")}T00:00:00.000Z`,
) <= datePeriodEnd,
).length > 0
? true
: false,
isSuspension: item.current_holder.dateRetire == null ? false : true,
isAbsent: false,
isLeave: false,
isRetired:
item.current_holder.birthDate == null ||
calculateRetireDate(item.current_holder.birthDate).getFullYear() != body.year
? false
: true,
2024-05-28 14:17:45 +07:00
isSpecial: false,
};
});
return new HttpSuccess({ data: formattedData, total: total });
}
/**
* API keycloak by revisionId
*
* @summary keycloak by revisionId (ADMIN)
*
*/
@Get("keycloak/position/{revisionId}")
async getProfileByKeycloakByRevision(
@Path() revisionId: string,
@Request() request: { user: Record<string, any> },
) {
2024-03-21 10:41:18 +07:00
const profile = await this.profileRepo.findOne({
where: { keycloak: request.user.sub },
relations: [
"posLevel",
"posType",
"current_holders",
"current_holders.orgRoot",
"current_holders.orgChild1",
"current_holders.orgChild2",
"current_holders.orgChild3",
"current_holders.orgChild4",
],
});
if (!profile) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
}
const _profile = {
profileId: profile.id,
rank: profile.rank,
prefix: profile.prefix,
firstName: profile.firstName,
lastName: profile.lastName,
citizenId: profile.citizenId,
position: profile.position,
posLevelName: profile.posLevel == null ? null : profile.posLevel.posLevelName,
posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank,
posLevelId: profile.posLevel == null ? null : profile.posLevel.id,
posTypeName: profile.posType == null ? null : profile.posType.posTypeName,
posTypeShortName: profile.posType == null ? null : profile.posType.posTypeShortName,
posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
posTypeId: profile.posType == null ? null : profile.posType.id,
rootId:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRootId,
2025-02-05 15:38:21 +07:00
rootDnaId:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
root:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot.orgRootName,
child1Id:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1Id,
2025-02-05 15:38:21 +07:00
child1DnaId:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
child1:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1
.orgChild1Name,
child2Id:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2Id,
2025-02-05 15:38:21 +07:00
child2DnaId:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
child2:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2
.orgChild2Name,
child3Id:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3Id,
2025-02-05 15:38:21 +07:00
child3DnaId:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
child3:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3
.orgChild3Name,
child4Id:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4Id,
2025-02-05 15:38:21 +07:00
child4DnaId:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.ancestorDNA,
child4:
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null ||
profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4
.orgChild4Name,
};
return new HttpSuccess(_profile);
}
2024-05-29 15:38:56 +07:00
/**
* API
*
* @summary
*
*/
@Get("profileid/retire/{year}")
async getProfileByRetireYear(@Path() year: number, @Request() req: RequestWithUser) {
2024-08-27 14:19:04 +07:00
// await new permission().PermissionOrgUserList(req, "SYS_REGISTRY_EMP", id);//ไม่แน่ใจEMPปิดไว้ก่อน
2024-05-29 15:38:56 +07:00
const profiles = await this.profileRepo
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
.leftJoinAndSelect("profileEmployee.posType", "posType")
.leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
.leftJoinAndSelect("current_holders.positions", "positions")
// calculate range: start = 2 Oct of (year-1), end = 1 Oct of year (inclusive)
.where("profileEmployee.dateRetire BETWEEN :start AND :end", {
2025-10-17 12:14:35 +07:00
start: `${year - 1}-10-01`,
end: `${year}-09-30`,
})
.andWhere(
"profileEmployee.isLeave = :isLeave AND profileEmployee.isRetirement = :isRetirement",
{
isLeave: false,
isRetirement: false,
},
)
2024-05-29 15:38:56 +07:00
.getMany();
if (!profiles || profiles.length === 0) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลที่มีอายุเกษียณราชการในปีนี้");
}
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
const formattedData = profiles.map((item) => {
const posMaster =
item.current_holders == null ||
item.current_holders.length == 0 ||
item.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id);
const shortName =
item.current_holders.length == 0
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-05-29 15:38:56 +07:00
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-05-29 15:38:56 +07:00
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-05-29 15:38:56 +07:00
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild1 != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-05-29 15:38:56 +07:00
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgRoot != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
2024-05-29 15:38:56 +07:00
: null;
const root =
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;
const child1 =
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1 == null
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1;
const child2 =
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2 == null
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2;
const child3 =
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 == null
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3;
const child4 =
item.current_holders == null ||
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 == null
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4;
let node = null;
let nodeId = null;
let nodeShortName = null;
if (root) {
node = 0;
nodeId = root.id;
nodeShortName = root.orgRootShortName;
}
if (child1) {
node = 1;
nodeId = child1.id;
nodeShortName = child1.orgChild1ShortName;
}
if (child2) {
node = 2;
nodeId = child2.id;
nodeShortName = child2.orgChild2ShortName;
}
if (child3) {
node = 3;
nodeId = child3.id;
nodeShortName = child3.orgChild3ShortName;
}
if (child4) {
node = 4;
nodeId = child4.id;
nodeShortName = child4.orgChild4ShortName;
}
return {
profileId: item.id,
prefix: item.prefix,
rank: item.rank,
firstName: item.firstName,
lastName: item.lastName,
citizenId: item.citizenId,
root: root == null ? null : root.orgRootName,
rootId: root == null ? null : root.id,
rootShortName: root == null ? null : root.orgRootShortName,
child1: child1 == null ? null : child1.orgChild1Name,
child1Id: child1 == null ? null : child1.id,
child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
child2: child2 == null ? null : child2.orgChild2Name,
child2Id: child2 == null ? null : child2.id,
child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
child3: child3 == null ? null : child3.orgChild3Name,
child3Id: child3 == null ? null : child3.id,
child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
child4: child4 == null ? null : child4.orgChild4Name,
child4Id: child4 == null ? null : child4.id,
child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
dateRetire: item.dateRetire,
posLevelId: item.posLevel == null ? null : item.posLevel.id,
posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName,
posLevelRank: item.posLevel == null ? null : item.posLevel.posLevelRank,
posTypeId: item.posType == null ? null : item.posType.id,
posTypeName: item.posType == null ? null : item.posType.posTypeName,
posTypeRank: item.posType == null ? null : item.posType.posTypeRank,
2024-05-30 16:05:00 +07:00
posNo: shortName,
2024-05-29 15:38:56 +07:00
posMasterNo: posMaster == null ? null : posMaster.posMasterNo,
position: item.position,
node: node,
nodeId: nodeId,
nodeShortName: nodeShortName,
2025-06-16 13:58:39 +07:00
positionExecutiveField: null,
positionArea: null,
2024-05-29 15:38:56 +07:00
};
});
return new HttpSuccess(formattedData);
}
2024-06-07 03:05:57 +07:00
/**
* API
*
* @summary (ADMIN)
*
* @param {string} id Id
*/
@Post("leave/{id}")
async updateLeaveUser(
@Path() id: string,
@Body()
requestBody: { isLeave: boolean; leaveReason: string; dateLeave: Date },
@Request() request: RequestWithUser,
2024-06-07 03:05:57 +07:00
) {
const profile = await this.profileRepo.findOne({
where: { id: id },
2025-04-05 19:21:50 +07:00
relations: [
"posType",
"posLevel",
"current_holders",
"current_holders.orgRoot",
"current_holders.orgChild1",
"current_holders.orgChild2",
"current_holders.orgChild3",
"current_holders.orgChild4",
"current_holders.positions",
],
2024-06-07 03:05:57 +07:00
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
2025-04-05 19:21:50 +07:00
const orgRevision = await this.orgRevisionRepo.findOne({
where: {
orgRevisionIsCurrent: true,
orgRevisionIsDraft: false,
},
});
const orgRevisionRef =
profile?.current_holders?.find((x) => x.orgRevisionId == orgRevision?.id) ?? null;
const orgRootRef = orgRevisionRef?.orgRoot ?? null;
const orgChild1Ref = orgRevisionRef?.orgChild1 ?? null;
const orgChild2Ref = orgRevisionRef?.orgChild2 ?? null;
const orgChild3Ref = orgRevisionRef?.orgChild3 ?? null;
const orgChild4Ref = orgRevisionRef?.orgChild4 ?? null;
const shortName =
!profile.current_holders || profile.current_holders.length == 0
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4 !=
null
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4.orgChild4ShortName}`
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3 !=
null
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3.orgChild3ShortName}`
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)
?.orgChild2 != null
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2.orgChild2ShortName}`
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)
?.orgChild1 != null
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1.orgChild1ShortName}`
: profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)
?.orgRoot != null
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot.orgRootShortName}`
: null;
const dest_item = await this.salaryRepo.findOne({
2025-05-22 15:05:54 +07:00
where: { profileEmployeeId: id },
2025-04-05 19:21:50 +07:00
order: { order: "DESC" },
});
const data: any = {
order: dest_item == null ? 1 : dest_item.order + 1,
amount: profile.amount,
positionSalaryAmount: profile.positionSalaryAmount,
mouthSalaryAmount: profile.mouthSalaryAmount,
profileEmployeeId: profile.id,
posNo: orgRevisionRef?.posMasterNo,
positionExecutive: "",
positionType: profile.posType?.posTypeName,
2025-09-08 00:10:59 +07:00
positionLevel:
profile.posType && profile.posLevel
? `${profile.posType?.posTypeShortName} ${profile.posLevel?.posLevelName}`
: "",
2025-04-05 19:21:50 +07:00
amountSpecial: profile.amountSpecial,
orgRoot: orgRootRef?.orgRootName,
orgChild1: orgChild1Ref?.orgChild1Name,
orgChild2: orgChild2Ref?.orgChild2Name,
orgChild3: orgChild3Ref?.orgChild3Name,
orgChild4: orgChild4Ref?.orgChild4Name,
commandYear: new Date().getFullYear() + 543,
2025-05-08 09:21:35 +07:00
// commandDateSign: new Date(),
commandDateAffect: requestBody.dateLeave,
2025-04-05 19:21:50 +07:00
commandCode: "16",
commandName: "พ้นจากราชการ",
posNoAbb: shortName,
isEntry: false,
positionName: profile.position,
createdUserId: request.user.sub,
createdFullName: request.user.name,
lastUpdateUserId: request.user.sub,
lastUpdateFullName: request.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
2025-05-08 09:21:35 +07:00
remark: "ถึงแก่กรรม",
2025-06-11 14:30:44 +07:00
isGovernment: false,
2025-04-05 19:21:50 +07:00
};
delete data.id;
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
data.dateGovernment = data.createdAt;
await this.salaryRepo.save(data);
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history);
let _null: any = null;
2024-06-07 03:05:57 +07:00
profile.isLeave = requestBody.isLeave;
profile.leaveReason = requestBody.leaveReason;
profile.dateLeave = requestBody.dateLeave;
profile.leaveDate = requestBody.dateLeave;
profile.leaveType = "RETIRE_DECEASED";
2025-05-08 09:21:35 +07:00
// profile.position = _null;
// profile.posLevelId = _null;
// profile.posTypeId = _null;
if (profile.keycloak != null) {
const delUserKeycloak = await deleteUser(profile.keycloak);
if (delUserKeycloak) {
profile.keycloak = _null;
profile.roleKeycloaks = [];
profile.isActive = false;
}
}
2024-06-07 03:05:57 +07:00
await this.profileRepo.save(profile);
2025-05-08 09:21:35 +07:00
if (requestBody.isLeave == true) {
await removeProfileInOrganize(profile.id, "EMPLOYEE");
}
2024-06-07 03:05:57 +07:00
return new HttpSuccess();
}
/**
* API
*
* @summary (ADMIN)
*
* @param {string} profileEmployeeId profileEmployeeId
*/
@Put("information/{profileEmployeeId}")
async ProfileEmployeeInformation(
@Request() request: RequestWithUser,
@Path() profileEmployeeId: string,
@Body() body: UpdateInformationProfileEmployee,
) {
2024-08-27 16:49:29 +07:00
await new permission().PermissionOrgUserUpdate(request, "SYS_REGISTRY_EMP", profileEmployeeId);
const profileEmp = await this.profileRepo.findOneBy({ id: profileEmployeeId });
if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");
const history = new ProfileEmployeeInformationHistory();
Object.assign(profileEmp, body);
2024-08-30 18:02:34 +07:00
Object.assign(history, { ...profileEmp, id: undefined });
history.profileEmployeeId = profileEmployeeId;
history.lastUpdateFullName = request.user.name;
history.lastUpdateUserId = request.user.sub;
2024-08-30 18:02:34 +07:00
history.lastUpdatedAt = new Date();
history.createdUserId = request.user.sub;
history.createdFullName = request.user.name;
history.createdAt = new Date();
profileEmp.lastUpdateUserId = request.user.sub;
profileEmp.lastUpdateFullName = request.user.name;
profileEmp.lastUpdatedAt = new Date();
await Promise.all([
this.profileRepo.save(profileEmp),
this.informationHistoryRepository.save(history),
]);
return new HttpSuccess();
}
/**
* API
*
* @summary (ADMIN)
*
* @param {string} profileEmployeeId profileEmployeeId
*/
@Get("information/{profileEmployeeId}")
async getInformationById(@Path() profileEmployeeId: string, @Request() req: RequestWithUser) {
// let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP");
// if (_workflow == false)
// await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId);
const profileInformation = await this.profileRepo.findOne({
where: { id: profileEmployeeId },
});
if (!profileInformation) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const mapData = {
id: profileInformation.id,
positionEmployeeGroupId: profileInformation.positionEmployeeGroupId,
positionEmployeeLineId: profileInformation.positionEmployeeLineId,
positionEmployeePositionId: profileInformation.positionEmployeePositionId,
employeeOc: profileInformation.employeeOc,
employeeTypeIndividual: profileInformation.employeeTypeIndividual,
employeeWage: profileInformation.employeeWage,
employeeMoneyIncrease: profileInformation.employeeMoneyIncrease,
employeeMoneyAllowance: profileInformation.employeeMoneyAllowance,
employeeMoneyEmployee: profileInformation.employeeMoneyEmployee,
employeeMoneyEmployer: profileInformation.employeeMoneyEmployer,
};
return new HttpSuccess(mapData);
}
/**
* API
*
* @summary (ADMIN)
*
* @param {string} profileEmployeeId profileEmployeeId
*/
@Get("information/history/{profileEmployeeId}")
async getInformationHistory(@Path() profileEmployeeId: string, @Request() req: RequestWithUser) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP");
if (_workflow == false)
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId);
2024-09-02 15:35:12 +07:00
const profileInformation = await this.informationHistoryRepository.find({
where: { profileEmployeeId: profileEmployeeId },
order: {
2024-09-10 10:24:06 +07:00
createdAt: "DESC",
},
});
2024-09-02 15:35:12 +07:00
return new HttpSuccess(profileInformation);
}
/**
* API
*
* @summary
*
* @param {string} profileEmployeeId profileEmployeeId
*/
@Get("employment/{profileEmployeeId}")
async ProfileEmployeeEmployment(
@Path() profileEmployeeId: string,
@Request() req: RequestWithUser,
) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP");
if (_workflow == false)
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId);
const employment = await this.employmentRepository.find({
where: { profileEmployeeId: profileEmployeeId },
order: { createdAt: "ASC" },
});
const mapData = employment.map((employment) => ({
id: employment.id,
date: employment.date,
command: employment.command,
}));
return new HttpSuccess(mapData);
}
/**
* API
*
* @summary
*
* @param {string} id Id
*/
@Get("employment/id/{id}")
async GetEmploymentById(@Path() id: string, @Request() req: RequestWithUser) {
const employment = await this.employmentRepository.findOne({
where: { id: id },
});
2024-08-27 16:49:29 +07:00
if (employment) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_EMP");
if (_workflow == false)
await new permission().PermissionOrgUserGet(
req,
"SYS_REGISTRY_EMP",
employment.profileEmployeeId,
);
2024-08-27 16:49:29 +07:00
}
return new HttpSuccess(employment);
}
/**
* API
*
* @summary
*
* @param {string} id Id
*/
@Get("employment/history/{id}")
async GetHistoryEmploymentById(@Path() id: string, @Request() req: RequestWithUser) {
const employment = await this.employmentRepository.findOne({
where: { id: id },
});
2024-08-27 16:49:29 +07:00
if (employment) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_EMP");
if (_workflow == false)
await new permission().PermissionOrgUserGet(
req,
"SYS_REGISTRY_EMP",
employment.profileEmployeeId,
);
2024-08-27 16:49:29 +07:00
}
const employmentHistory = await this.employmentHistoryRepository.find({
where: { profileEmployeeEmploymentId: id },
order: { lastUpdatedAt: "ASC" },
});
return new HttpSuccess(employmentHistory);
}
/**
* API
*
* @summary
*
* @param {string} profileEmployeeId profileEmployeeId
*/
@Post("employment/{profileEmployeeId}")
async CreateEmployment(
@Path() profileEmployeeId: string,
@Body() body: CreateEmploymentProfileEmployee,
@Request() request: RequestWithUser,
) {
const profile = await this.profileRepo.findOne({
where: { id: profileEmployeeId },
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
2024-08-27 16:49:29 +07:00
await new permission().PermissionOrgUserUpdate(request, "SYS_REGISTRY_EMP", profile.id);
2024-08-30 18:02:34 +07:00
const data = new ProfileEmployeeEmployment();
const meta = {
createdUserId: request.user.sub,
createdFullName: request.user.name,
lastUpdateUserId: request.user.sub,
lastUpdateFullName: request.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
profileEmployeeId: profileEmployeeId,
};
Object.assign(data, { ...body, ...meta });
const history = new ProfileEmployeeEmploymentHistory();
Object.assign(history, { ...data, id: undefined });
await this.employmentRepository.save(data);
history.profileEmployeeEmploymentId = data.id;
await this.employmentHistoryRepository.save(history);
return new HttpSuccess();
}
/**
* API
*
* @summary (ADMIN)
*
* @param {string} id Id
*/
@Delete("employment/{id}")
async DeleteEmployment(@Path() id: string, @Request() request: RequestWithUser) {
const employment = await this.employmentRepository.findOne({
where: { id: id },
});
2024-08-27 16:49:29 +07:00
if (employment) {
await new permission().PermissionOrgUserDelete(
request,
"SYS_REGISTRY_EMP",
employment.profileEmployeeId,
);
}
await this.employmentHistoryRepository.delete({
profileEmployeeEmploymentId: id,
});
const result = await this.employmentRepository.delete({ id });
if (result.affected == undefined || result.affected <= 0) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
return new HttpSuccess();
}
/**
* API
*
* @summary (ADMIN)
*
* @param {string} id Id
*/
@Put("employment/{id}")
async UpdateEmployment(
@Request() request: RequestWithUser,
@Path() id: string,
@Body() body: UpdateEmploymentProfileEmployee,
) {
const employment = await this.employmentRepository.findOneBy({ id });
if (!employment) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
2024-08-27 16:49:29 +07:00
await new permission().PermissionOrgUserUpdate(
request,
"SYS_REGISTRY_EMP",
employment.profileEmployeeId,
);
const history = new ProfileEmployeeEmploymentHistory();
Object.assign(employment, body);
2024-08-30 18:02:34 +07:00
Object.assign(history, { ...employment, id: undefined });
employment.lastUpdateUserId = request.user.sub;
employment.lastUpdateFullName = request.user.name;
employment.lastUpdatedAt = new Date();
history.profileEmployeeEmploymentId = id;
history.lastUpdateUserId = request.user.sub;
2024-08-30 18:02:34 +07:00
history.lastUpdateFullName = request.user.name;
history.createdUserId = request.user.sub;
history.createdFullName = request.user.name;
history.createdAt = new Date();
history.lastUpdatedAt = new Date();
await Promise.all([
this.employmentRepository.save(employment),
this.employmentHistoryRepository.save(history),
]);
return new HttpSuccess();
}
/**
* API
*
* @summary ORG_038 - (ADMIN) #
*
*/
@Post("report")
async sendReport(@Request() request: RequestWithUser, @Body() requestBody: { id: string[] }) {
const profiles = await this.profileRepo.find({ where: { id: In(requestBody.id) } });
const _profiles = await Promise.all(
profiles.map(async (item: any) => {
return {
...item,
statusTemp: "REPORT",
lastUpdateUserId: request.user.sub,
lastUpdateFullName: request.user.name,
2024-08-30 18:02:34 +07:00
lastUpdatedAt: new Date(),
};
}),
);
await this.profileRepo.save(_profiles);
return new HttpSuccess();
}
2024-06-12 14:18:55 +07:00
/**
* API
*
* @summary ORG_038 - (ADMIN) #
*
*/
2024-06-13 11:54:57 +07:00
@Post("report/resume")
async doneReport(
@Body()
body: {
result: {
id: string;
remark: string;
2024-06-18 12:08:03 +07:00
amount: Double | null;
positionSalaryAmount: Double | null;
mouthSalaryAmount: Double | null;
refCommandNo: string;
}[];
},
@Request() request: { user: Record<string, any> },
) {
await Promise.all(
body.result.map(async (v) => {
const profile = await this.profileRepo.findOne({
where: {
id: v.id,
},
relations: ["posType", "posLevel"],
});
if (profile != null) {
await new CallAPI()
2024-08-07 17:49:28 +07:00
.PostData(request, "/org/profile-employee/salary", {
2024-06-18 12:31:49 +07:00
profileEmployeeId: profile.id,
date: new Date(),
amount: v.amount,
positionSalaryAmount: v.positionSalaryAmount,
mouthSalaryAmount: v.mouthSalaryAmount,
posNo: profile.posMasterNoTemp,
position: profile.positionTemp,
positionType: profile.posTypeNameTemp,
positionLevel: profile.posLevelNameTemp,
refCommandNo: v.refCommandNo,
remark: v.remark,
})
.then(async () => {
profile.statusTemp = "DONE";
2024-06-18 12:08:03 +07:00
profile.employeeClass = "PERM";
2024-08-07 18:05:24 +07:00
const _null: any = null;
profile.employeeWage = v.amount == null ? _null : v.amount.toString();
await this.profileRepo.save(profile);
2024-08-07 18:05:24 +07:00
});
2024-06-24 10:52:40 +07:00
await new CallAPI()
2024-08-07 17:49:28 +07:00
.PostData(request, "/org/employee/pos/report/current", {
2024-06-24 10:52:40 +07:00
posmasterId: profile.posmasterIdTemp,
positionId: profile.positionIdTemp,
profileId: profile.id,
})
.then(async () => {});
}
}),
);
return new HttpSuccess();
}
/**
* API keycloak
*
* @summary keycloak
*
*/
@Post("search-personal-no-keycloak")
async getProfileBySearchKeywordNoKeyCloak(
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Body()
body: {
fieldName: string;
keyword?: string;
},
) {
let findProfile: any;
let total: any;
const skip = (page - 1) * pageSize;
const take = pageSize;
switch (body.fieldName) {
2024-06-13 16:15:56 +07:00
case "citizenId":
[findProfile, total] = await this.profileRepo.findAndCount({
where: {
keycloak: IsNull(),
citizenId: Like(`%${body.keyword}%`),
2025-01-17 12:10:23 +07:00
employeeClass: "PERM",
},
2024-12-19 14:53:35 +07:00
relations: ["posType", "posLevel", "current_holders"],
skip,
take,
});
break;
case "firstname":
[findProfile, total] = await this.profileRepo.findAndCount({
where: {
keycloak: IsNull(),
firstName: Like(`%${body.keyword}%`),
2025-01-17 12:10:23 +07:00
employeeClass: "PERM",
},
2024-12-19 14:53:35 +07:00
relations: ["posType", "posLevel", "current_holders"],
skip,
take,
});
break;
case "lastname":
[findProfile, total] = await this.profileRepo.findAndCount({
where: {
keycloak: IsNull(),
lastName: Like(`%${body.keyword}%`),
2025-01-17 12:10:23 +07:00
employeeClass: "PERM",
},
2024-12-19 14:53:35 +07:00
relations: ["posType", "posLevel", "current_holders"],
skip,
take,
});
break;
default:
[findProfile, total] = await this.profileRepo.findAndCount({
where: {
keycloak: IsNull(),
2025-01-17 12:10:23 +07:00
employeeClass: "PERM",
},
2024-12-19 14:53:35 +07:00
relations: ["posType", "posLevel", "current_holders"],
skip,
take,
});
break;
}
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
const mapDataProfile = await Promise.all(
findProfile.map(async (item: ProfileEmployee) => {
const fullName = `${item.prefix} ${item.firstName} ${item.lastName}`;
const shortName =
item.current_holders.length == 0
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 !=
null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild2 != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgChild1 != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)
?.orgRoot != null
2025-04-05 19:21:50 +07:00
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
: null;
const root =
item.current_holders.length == 0 ||
(item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null)
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot;
const posMasterNo = item.current_holders?.find(
(x) => x.orgRevisionId == findRevision.id,
)?.posMasterNo;
2025-01-06 23:58:24 +07:00
const latestProfileEducation = await this.profileEducationRepo.findOne({
where: { profileEmployeeId: item.id },
2025-01-06 23:58:24 +07:00
order: { level: "ASC" },
});
return {
id: item.id,
prefix: item.prefix,
rank: item.rank,
firstName: item.firstName,
lastName: item.lastName,
position: item.position,
2024-06-13 16:15:56 +07:00
citizenId: item.citizenId,
email: item.email,
phone: item.phone,
name: fullName,
birthDate: item.birthDate,
positionLevel: item.posLevelId,
2025-02-25 18:24:38 +07:00
positionLevelName: item.posLevel?.posLevelName,
positionType: item.posTypeId,
positionTypeName: item.posType?.posTypeName,
posNo: shortName,
2024-12-19 15:46:14 +07:00
organization: root == null ? null : root.orgRootName,
2024-12-19 14:53:35 +07:00
salary: item.amount,
posMasterNo: posMasterNo ?? null,
posTypeId: item.posTypeId,
posTypeName: item.posType?.posTypeName,
posLevelId: item.posLevelId,
posLevelName:
item.posLevel == null && item.posType == null
? null
: `${item.posType?.posTypeShortName} ${item.posLevel?.posLevelName}`,
educationDegree:
latestProfileEducation != null && latestProfileEducation.educationLevel != null
? latestProfileEducation.educationLevel
: null,
};
}),
);
return new HttpSuccess({ data: mapDataProfile, total });
}
2024-06-25 10:21:30 +07:00
/**
* API profileid
*
* @summary ORG_065 - profileid (ADMIN) #70
*
*/
@Get("profileid/position/{id}")
async getProfileByProfileid(@Request() request: RequestWithUser, @Path() id: string) {
2024-06-25 10:21:30 +07:00
const profile = await this.profileRepo.findOne({
where: { id: id },
2024-10-22 08:20:45 +07:00
relations: [
"posLevel",
"posType",
"current_holders",
"current_holders.orgRoot",
"current_holders.orgChild1",
"current_holders.orgChild2",
"current_holders.orgChild3",
"current_holders.orgChild4",
"profileSalary",
2024-11-14 18:03:56 +07:00
"profileEducations",
2024-10-22 08:20:45 +07:00
],
order: {
2024-11-08 12:11:01 +07:00
// profileSalary: {
// order: "DESC",
// },
profileEducations: {
2025-01-06 23:58:24 +07:00
level: "ASC",
2024-11-14 18:03:56 +07:00
},
2024-10-22 08:20:45 +07:00
},
2024-06-25 10:21:30 +07:00
});
if (!profile) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
}
2024-10-22 08:20:45 +07:00
//await new permission().PermissionOrgUserGet(request, "SYS_REGISTRY_EMP", profile.id); //ไม่แน่ใจEMPปิดไว้ก่อน
2024-06-25 10:21:30 +07:00
const orgRevisionPublish = await this.orgRevisionRepo
.createQueryBuilder("orgRevision")
.where("orgRevision.orgRevisionIsDraft = false")
.andWhere("orgRevision.orgRevisionIsCurrent = true")
.getOne();
if (!orgRevisionPublish) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
}
const permissionProflile = await this.permissionProflileRepository.findOne({
relations: ["orgRootTree"],
where: {
2025-03-26 15:23:18 +07:00
profileId: id,
orgRootTree: {
orgRevisionId: orgRevisionPublish.id,
},
},
2025-03-26 15:23:18 +07:00
});
2024-06-25 10:21:30 +07:00
const posMaster =
profile.current_holders == null ||
profile.current_holders.length == 0 ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id);
const root =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot == null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot;
const child1 =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1 ==
null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1;
const child2 =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2 ==
null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2;
const child3 =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3 ==
null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3;
const child4 =
profile.current_holders == null ||
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4 ==
null
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4;
2024-07-08 16:32:02 +07:00
const shortName =
profile.current_holders.length == 0
? null
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
?.orgChild4 != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4.orgChild4ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
2024-07-08 16:32:02 +07:00
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
?.orgChild3 != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3.orgChild3ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
2024-07-08 16:32:02 +07:00
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) !=
null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
?.orgChild2 != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2.orgChild2ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
2024-07-08 16:32:02 +07:00
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) !=
null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
?.orgChild1 != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1.orgChild1ShortName} ${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
2024-07-08 16:32:02 +07:00
: profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) !=
null &&
profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)
?.orgRoot != null
2025-04-05 19:21:50 +07:00
? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot.orgRootShortName} ${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}`
2024-07-08 16:32:02 +07:00
: null;
2024-06-25 10:21:30 +07:00
const _profile: any = {
profileId: profile.id,
prefix: profile.prefix,
rank: profile.rank,
isProbation: profile.isProbation,
firstName: profile.firstName,
lastName: profile.lastName,
citizenId: profile.citizenId,
birthDate: profile.birthDate,
position: profile.position,
leaveDate: profile.dateLeave,
posMasterNo: posMaster == null ? null : posMaster.posMasterNo,
2025-02-04 17:08:50 +07:00
posLevelName: `${profile?.posType?.posTypeShortName ?? ""} ${profile?.posLevel?.posLevelName ?? ""}`,
2024-06-25 10:21:30 +07:00
posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank,
posLevelId: profile.posLevel == null ? null : profile.posLevel.id,
posTypeName: profile.posType == null ? null : profile.posType.posTypeName,
posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank,
2025-01-20 16:28:41 +07:00
posTypeShortName: profile.posType == null ? null : profile.posType.posTypeShortName,
2024-06-25 10:21:30 +07:00
posTypeId: profile.posType == null ? null : profile.posType.id,
rootId: root == null ? null : root.id,
2025-02-05 15:38:21 +07:00
rootDnaId: root == null ? null : root.ancestorDNA,
2024-06-25 10:21:30 +07:00
root: root == null ? null : root.orgRootName,
rootShortName: root == null ? null : root.orgRootShortName,
child1Id: child1 == null ? null : child1.id,
2025-02-05 15:38:21 +07:00
child1DnaId: child1 == null ? null : child1.ancestorDNA,
2024-06-25 10:21:30 +07:00
child1: child1 == null ? null : child1.orgChild1Name,
child1ShortName: child1 == null ? null : child1.orgChild1ShortName,
child2Id: child2 == null ? null : child2.id,
2025-02-05 15:38:21 +07:00
child2DnaId: child2 == null ? null : child2.ancestorDNA,
2024-06-25 10:21:30 +07:00
child2: child2 == null ? null : child2.orgChild2Name,
child2ShortName: child2 == null ? null : child2.orgChild2ShortName,
child3Id: child3 == null ? null : child3.id,
2025-02-05 15:38:21 +07:00
child3DnaId: child3 == null ? null : child3.ancestorDNA,
2024-06-25 10:21:30 +07:00
child3: child3 == null ? null : child3.orgChild3Name,
child3ShortName: child3 == null ? null : child3.orgChild3ShortName,
child4Id: child4 == null ? null : child4.id,
2025-02-05 15:38:21 +07:00
child4DnaId: child4 == null ? null : child4.ancestorDNA,
2024-06-25 10:21:30 +07:00
child4: child4 == null ? null : child4.orgChild4Name,
child4ShortName: child4 == null ? null : child4.orgChild4ShortName,
node: null,
nodeId: null,
2024-07-08 16:32:02 +07:00
posNo: shortName,
2024-11-15 16:57:20 +07:00
salary: profile.amount,
2024-11-14 18:03:56 +07:00
education:
profile && profile.profileEducations.length > 0
2025-09-08 00:10:59 +07:00
? await getTopDegrees(profile.profileEducations)
2024-11-14 18:03:56 +07:00
: "-",
2025-03-21 10:27:33 +07:00
statusCheckEdit: profile.statusCheckEdit,
isEdit: permissionProflile?.isEdit ?? false,
isCheck: permissionProflile?.isCheck ?? false,
2024-06-25 10:21:30 +07:00
};
if (_profile.child4Id != null) {
_profile.node = 4;
_profile.nodeId = _profile.child4Id;
_profile.nodeShortName = _profile.child4ShortName;
2024-06-25 10:21:30 +07:00
} else if (_profile.child3Id != null) {
_profile.node = 3;
_profile.nodeId = _profile.child3Id;
_profile.nodeShortName = _profile.child3ShortName;
2024-06-25 10:21:30 +07:00
} else if (_profile.child2Id != null) {
_profile.node = 2;
_profile.nodeId = _profile.child2Id;
_profile.nodeShortName = _profile.child2ShortName;
2024-06-25 10:21:30 +07:00
} else if (_profile.child1Id != null) {
_profile.node = 1;
_profile.nodeId = _profile.child1Id;
_profile.nodeShortName = _profile.child1ShortName;
2024-06-25 10:21:30 +07:00
} else if (_profile.rootId != null) {
_profile.node = 0;
_profile.nodeId = _profile.rootId;
_profile.nodeShortName = _profile.rootShortName;
2024-06-25 10:21:30 +07:00
}
return new HttpSuccess(_profile);
}
async sendVerifyEmail(
@Request() req: RequestWithUser,
@Body()
body: {
profileId: string;
email: string;
subject: string;
},
) {
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{ email_id: body.email, profileId: body.profileId },
process.env.AUTH_ACCOUNT_SECRET,
{ expiresIn: "15m" },
);
const link = process.env.VITE_URL_USER + "/verifyemail?upn=" + token;
await new CallAPI()
.PostData(req, "/placement/noti/send-mail", {
subject: body.subject,
body: link,
Email: body.email,
})
.catch((error) => {
console.error("Error calling API:", error);
});
return new HttpSuccess();
}
/**
* API
*
* @summary (USER)
*
*/
@Put("updatePhoneNumber/user")
async updatePhoneNumber(
@Request() request: RequestWithUser,
@Body()
body: {
phone: string;
},
) {
const profile = await this.profileRepo.findOne({
relations: {
posLevel: true,
posType: true,
},
where: { keycloak: request.user.sub },
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const history = new ProfileEmployeeHistory();
Object.assign(profile, body);
Object.assign(history, { ...profile, id: undefined });
profile.lastUpdateUserId = request.user.sub;
profile.lastUpdateFullName = request.user.name;
profile.lastUpdatedAt = new Date();
history.lastUpdateUserId = request.user.sub;
history.lastUpdateFullName = request.user.name;
history.createdUserId = request.user.sub;
history.createdFullName = request.user.name;
history.createdAt = new Date();
history.lastUpdatedAt = new Date();
await Promise.all([
this.profileRepo.save(profile, { data: request }),
this.profileHistoryRepo.save(history, { data: request }),
]);
return new HttpSuccess();
}
/**
* API
*
* @summary (USER)
*
*/
@Put("updateEmail/user")
async updateEmail(
@Request() request: RequestWithUser,
@Body()
body: {
email: string;
},
) {
const profile = await this.profileRepo.findOne({
relations: {
posLevel: true,
posType: true,
},
where: { keycloak: request.user.sub },
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const history = new ProfileEmployeeHistory();
Object.assign(profile, body);
Object.assign(history, { ...profile, id: undefined });
profile.statusEmail = "NOT_VERIFIED";
profile.lastUpdateUserId = request.user.sub;
profile.lastUpdateFullName = request.user.name;
profile.lastUpdatedAt = new Date();
history.lastUpdateUserId = request.user.sub;
history.lastUpdateFullName = request.user.name;
history.createdUserId = request.user.sub;
history.createdFullName = request.user.name;
history.createdAt = new Date();
history.lastUpdatedAt = new Date();
await Promise.all([
this.profileRepo.save(profile, { data: request }),
this.profileHistoryRepo.save(history, { data: request }),
]);
const verifyemailBody = {
profileId: profile.id,
email: body.email,
subject: "ยืนยันอีเมล",
};
this.sendVerifyEmail(request, verifyemailBody);
return new HttpSuccess();
}
}