Merge branch 'develop' into dev

This commit is contained in:
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 2025-10-14 10:56:32 +07:00
commit 84863e089b
22 changed files with 2838 additions and 1816 deletions

View file

@ -1,49 +0,0 @@
name: Build
on:
push:
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
- "v[0-9]+.[0-9]+.[0-9]+*"
workflow_dispatch:
env:
REGISTRY: ${{ vars.CONTAINER_REGISTRY }}
REGISTRY_USERNAME: ${{ vars.CONTAINER_REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.CONTAINER_REGISTRY_PASSWORD }}
CONTAINER_IMAGE_NAME: ${{ vars.CONTAINER_REGISTRY }}/${{ vars.CONTAINER_IMAGE_OWNER }}/${{ vars.CONTAINER_IMAGE_NAME }}
IMAGE_VERSION: build
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
with:
config-inline: |
[registry."${{ env.REGISTRY }}"]
ca=["/etc/ssl/certs/ca-certificates.crt"]
- name: Tag Version
run: |
if [[ "${{ github.event_name }}" == "push" ]]; then
echo "IMAGE_VERSION=${{ github.ref_name }}" | sed 's/v//g' >> $GITHUB_ENV
else
echo "IMAGE_VERSION=${{ env.IMAGE_VERSION }}-${{ github.run_number }}" >> $GITHUB_ENV
fi
- name: Login in to registry
uses: docker/login-action@v2
with:
registry: ${{ env.REGISTRY }}
username: ${{ env.REGISTRY_USERNAME }}
password: ${{ env.REGISTRY_PASSWORD }}
- name: Build and push docker image
uses: docker/build-push-action@v3
with:
platforms: linux/amd64
context: .
file: ./docker/Dockerfile
tags: ${{ env.CONTAINER_IMAGE_NAME }}:latest,${{ env.CONTAINER_IMAGE_NAME }}:${{ env.IMAGE_VERSION }}
push: true

View file

@ -1,79 +0,0 @@
# /.forgejo/workflows/ci-cd.yml
name: Build & Deploy on Dev
on:
push:
branches:
- dev
workflow_dispatch:
env:
REGISTRY: ${{ vars.CONTAINER_REGISTRY }}
REGISTRY_USERNAME: ${{ vars.CONTAINER_REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.CONTAINER_REGISTRY_PASSWORD }}
CONTAINER_IMAGE_NAME: ${{ vars.CONTAINER_REGISTRY }}/${{ vars.CONTAINER_IMAGE_OWNER }}/${{ vars.CONTAINER_IMAGE_NAME }}
IMAGE_VERSION: latest
DISCORD_WEBHOOK: ${{ vars.DISCORD_WEBHOOK }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
with:
config-inline: |
[registry."${{ env.REGISTRY }}"]
ca=["/etc/ssl/certs/ca-certificates.crt"]
- name: Tag Version
run: |
echo "IMAGE_VERSION=latest"
- name: Login in to registry
uses: docker/login-action@v2
with:
registry: ${{ env.REGISTRY }}
username: ${{ env.REGISTRY_USERNAME }}
password: ${{ env.REGISTRY_PASSWORD }}
- name: Build and push docker image
uses: docker/build-push-action@v3
with:
platforms: linux/amd64
context: .
file: ./docker/Dockerfile
tags: ${{ env.CONTAINER_IMAGE_NAME }}:latest,${{ env.CONTAINER_IMAGE_NAME }}:${{ env.IMAGE_VERSION }}
push: true
- name: Remote Deploy
uses: appleboy/ssh-action@v1.2.1
with:
host: ${{ vars.SSH_DEPLOY_HOST }}
port: ${{ vars.SSH_DEPLOY_PORT }}
username: ${{ secrets.SSH_DEPLOY_USER }}
password: ${{ secrets.SSH_DEPLOY_PASSWORD }}
script: |
cd ~/repo
./replace-env.sh API_ORG "${{ env.IMAGE_VERSION }}"
./deploy.sh hrms-api-org
- name: Discord Notification
if: always()
run: |
STATUS="${{ job.status == 'success' && '✅ Success' || '❌ Failed' }}"
COLOR="${{ job.status == 'success' && '3066993' || '15158332' }}"
TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)
curl -H "Content-Type: application/json" \
-X POST \
-d "{
\"embeds\": [{
\"title\": \"$STATUS\",
\"description\": \"**Build & Deploy**\\n- Image: \`${{ env.CONTAINER_IMAGE_NAME }}\`\\n- Version: \`${{ env.IMAGE_VERSION }}\`\\n- By: \`${{ github.actor }}\`\",
\"color\": $COLOR,
\"footer\": {
\"text\": \"Release Notification\",
\"icon_url\": \"https://example.com/success-icon.png\"
},
\"timestamp\": \"$TIMESTAMP\"
}]
}" \
${{ env.DISCORD_WEBHOOK }}

View file

@ -1,29 +0,0 @@
name: Build
on:
workflow_dispatch:
inputs:
version:
description: "Version to deploy"
type: string
required: false
default: "latest"
env:
IMAGE_VERSION: build
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Remote Deploy
uses: appleboy/ssh-action@v1.2.1
with:
host: ${{ vars.SSH_DEPLOY_HOST }}
port: ${{ vars.SSH_DEPLOY_PORT }}
username: ${{ secrets.SSH_DEPLOY_USER }}
password: ${{ secrets.SSH_DEPLOY_PASSWORD }}
script: |
cd ~/repo
./replace-env.sh API_ORG "${{ inputs.version }}"
./deploy.sh hrms-api-org

22
.github/workflows/discord-notify.yml vendored Normal file
View file

@ -0,0 +1,22 @@
name: Discord PR Notify
on:
pull_request:
types: [opened]
jobs:
discord:
runs-on: ubuntu-latest
steps:
- name: Send Discord
run: |
curl -X POST "${{ secrets.DISCORD_WEBHOOK_PULLREQUEST }}" \
-H "Content-Type: application/json" \
-d '{
"embeds": [{
"title": "🔔 **Service:** ${{ github.repository }}",
"description": "👤 **Author:** ${{ github.event.pull_request.user.login }}\n🌿 **Branch:** ${{ github.event.pull_request.head.ref }} → ${{ github.event.pull_request.base.ref }}\n📦 **Pull Request:** [#${{ github.event.pull_request.number }} - ${{ github.event.pull_request.title }}](${{ github.event.pull_request.html_url }})",
"color": 5814783,
"timestamp": "${{ github.event.pull_request.created_at }}"
}]
}'

View file

@ -264,7 +264,7 @@ export class CommandController extends Controller {
yearKeyword = match[1].trim();
}
let yearInBC = yearKeyword ? parseInt(yearKeyword) - 543 : null;
// const [commands, total] = await this.commandRepository
let query = await this.commandRepository
.createQueryBuilder("command")
@ -335,16 +335,13 @@ export class CommandController extends Controller {
);
}),
)
.orderBy("command.createdAt", "DESC")
.orderBy("command.createdAt", "DESC");
if (sortBy) {
query = query.orderBy(
`command.${sortBy}`,
descending ? "DESC" : "ASC"
);
}
if (sortBy) {
query = query.orderBy(`command.${sortBy}`, descending ? "DESC" : "ASC");
}
let [commands, total] = await query
let [commands, total] = await query
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
@ -1477,8 +1474,8 @@ export class CommandController extends Controller {
return new HttpSuccess();
}
async cronjobUpdateRetirementStatus() {
// @Get("XXX")
async cronjobUpdateRetirementStatus(/*@Request() request: RequestWithUser*/) {
let body = {
client_id: "gettoken",
client_secret: process.env.AUTH_ACCOUNT_SECRET,
@ -1496,9 +1493,11 @@ export class CommandController extends Controller {
},
);
const adminToken = response.data.access_token;
// const adminToken = request.headers["authorization"]?.replace("Bearer ", "");
const today = new Date();
today.setUTCHours(0, 0, 0, 0);
let type: string = "OFFICER";
let _Date = new Date();
try {
const response_ = await axios.get(
process.env.API_URL + `/retirement/update-status/${type}/${today.getFullYear()}`,
@ -1510,23 +1509,47 @@ export class CommandController extends Controller {
},
},
);
if (response && response_.data.result.length > 0) {
let profiles: Profile[] = [];
if (response_ && response_.data.result) {
let signDate: string = "";
if (response_.data.result.signDate != null) {
signDate = Extension.ToThaiShortDate_noPrefix(new Date(response_.data.result.signDate));
} else {
signDate = Extension.ToThaiShortDate_noPrefix(_Date);
}
await Promise.all(
response_.data.result.map(async (x: any) => {
const _profile = await this.profileRepository.findOneBy({ id: x.profileId });
response_.data.result.profiles.map(async (x: any) => {
const _profile = await this.profileRepository.findOne({
where: { id: x.profileId },
relations: ["roleKeycloaks"],
});
if (_profile) {
// console.log("1. บันทึกลงประวัติตำแหน่ง")
await this.profileSalaryRetire(x.profileId, type, signDate, _Date);
// console.log("2. ปลดออกจากโครงสร้าง")
await this.posMasterRetire(x.profileId, type, _Date);
// console.log("3. แก้ไขสถานะในทะเบียนประวัติ")
_profile.isRetirement = true;
_profile.isLeave = true;
_profile.isActive = false;
_profile.leaveType = "RETIRE";
_profile.leaveDate = new Date();
_profile.dateLeave = new Date();
_profile.lastUpdatedAt = new Date();
profiles.push(_profile);
_profile.leaveReason = "เกษียณอายุราชการ";
_profile.leaveDate = _Date;
_profile.dateLeave = _Date;
_profile.lastUpdatedAt = _Date;
if (_profile.keycloak != null && _profile.keycloak != "") {
// console.log("4. disable keycloak/authen")
const delUserKeycloak = await deleteUser(_profile.keycloak, adminToken);
if (delUserKeycloak) {
_profile.keycloak = "";
_profile.roleKeycloaks = [];
}
}
// console.log("5. save profile ",_profile)
await this.profileRepository.save(_profile);
}
}),
);
await this.profileRepository.save(profiles);
}
} catch {}
@ -1542,29 +1565,171 @@ export class CommandController extends Controller {
},
},
);
if (response && response_.data.result.length > 0) {
let profiles: ProfileEmployee[] = [];
if (response_ && response_.data.result) {
let signDate: string = "";
if (response_.data.result.signDate != null) {
signDate = Extension.ToThaiShortDate_noPrefix(new Date(response_.data.result.signDate));
} else {
signDate = Extension.ToThaiShortDate_noPrefix(_Date);
}
await Promise.all(
response_.data.result.map(async (x: any) => {
const _profileEmp = await this.profileEmployeeRepository.findOneBy({ id: x.profileId });
response_.data.result.profiles.map(async (x: any) => {
const _profileEmp = await this.profileEmployeeRepository.findOne({
where: { id: x.profileId },
relations: ["roleKeycloaks"],
});
if (_profileEmp) {
// บันทึกลงประวัติตำแหน่ง
await this.profileSalaryRetire(x.profileId, type, signDate, _Date);
// ปลดออกจากโครงสร้าง
await this.posMasterRetire(x.profileId, type, _Date);
// แก้ไขสถานะในทะเบียนประวัติ
_profileEmp.isRetirement = true;
_profileEmp.isLeave = true;
_profileEmp.isActive = false;
_profileEmp.leaveType = "RETIRE";
_profileEmp.leaveDate = new Date();
_profileEmp.dateLeave = new Date();
_profileEmp.lastUpdatedAt = new Date();
profiles.push(_profileEmp);
_profileEmp.leaveReason = "เกษียณอายุราชการ";
_profileEmp.leaveDate = _Date;
_profileEmp.dateLeave = _Date;
_profileEmp.lastUpdatedAt = _Date;
if (_profileEmp.keycloak != null && _profileEmp.keycloak != "") {
// disable keycloak/authen
const delUserKeycloak = await deleteUser(_profileEmp.keycloak, adminToken);
if (delUserKeycloak) {
_profileEmp.keycloak = "";
_profileEmp.roleKeycloaks = [];
}
}
await this.profileEmployeeRepository.save(_profileEmp);
}
}),
);
await this.profileEmployeeRepository.save(profiles);
}
} catch {}
return new HttpSuccess();
}
async profileSalaryRetire(profileId: string, type: string, signDate: string, _Date: Date) {
const whereKey =
type == "OFFICER" ? { profileId: profileId } : { profileEmployeeId: profileId };
const maxOrder = await this.salaryRepo.findOne({
select: { order: true },
where: whereKey,
order: { order: "DESC" },
});
const data: any = {
order: maxOrder ? maxOrder.order + 1 : 1,
amount: null,
positionSalaryAmount: null,
mouthSalaryAmount: null,
posNo: null,
positionExecutive: null,
positionType: null,
positionLevel: null,
amountSpecial: null,
orgRoot: null,
orgChild1: null,
orgChild2: null,
orgChild3: null,
orgChild4: null,
commandYear: _Date.getFullYear() + 543,
commandDateAffect: _Date,
commandCode: "16",
commandName: "พ้นจากราชการ",
posNoAbb: null,
isEntry: false,
positionName: "เกษียณอายุราชการ",
createdUserId: "",
createdFullName: "System Administrator",
lastUpdateUserId: "",
lastUpdateFullName: "System Administrator",
createdAt: _Date,
lastUpdatedAt: _Date,
remark: `ประกาศคณะอนุกรรมการสามัญข้าราชการกรุงเทพมหานครสามัญ ลว. ${signDate}`, // script เกษียณจริง ๆ ให้เอา “วันที่ประกาศเกษียณฉบับแรก” มาลงในเอกสารอ้างอิง
isGovernment: false,
};
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
data.dateGovernment = _Date;
if (type == "OFFICER") {
data.profileId = profileId;
data.profileEmployeeId = null;
} else if (type == "EMPLOYEE") {
data.profileEmployeeId = profileId;
data.profileId = null;
}
const savedData = await this.salaryRepo.save(data);
history.profileSalaryId = savedData.id;
await this.salaryHistoryRepo.save(history);
}
async posMasterRetire(profileId: string, type: string, _Date: Date) {
const orgRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
});
if (orgRevision) {
let _posMaster: any = null;
let _position: any = null;
if (type == "OFFICER") {
_posMaster = await this.posMasterRepository.findOne({
where: {
orgRevisionId: orgRevision.id,
current_holderId: profileId,
},
});
if (_posMaster) {
_position = await this.positionRepository.findOne({
where: {
posMasterId: _posMaster.id,
positionIsSelected: true,
},
});
if (_position) {
_position.positionIsSelected = false;
_position.lastUpdateFullName = "System Administrator";
_position.lastUpdatedAt = _Date;
await this.positionRepository.save(_position);
}
_posMaster.isSit = false;
_posMaster.current_holderId = null;
_posMaster.lastUpdateFullName = "System Administrator";
_posMaster.lastUpdatedAt = _Date;
await this.posMasterRepository.save(_posMaster);
await CreatePosMasterHistoryOfficer(_posMaster.id, null);
}
} else if (type == "EMPLOYEE") {
_posMaster = await this.employeePosMasterRepository.findOne({
where: {
orgRevisionId: orgRevision.id,
current_holderId: profileId,
},
});
if (_posMaster) {
_position = await this.employeePositionRepository.findOne({
where: {
posMasterId: _posMaster.id,
positionIsSelected: true,
},
});
if (_position) {
_position.positionIsSelected = false;
_position.lastUpdateFullName = "System Administrator";
_position.lastUpdatedAt = _Date;
await this.employeePositionRepository.save(_position);
}
_posMaster.isSit = false;
_posMaster.current_holderId = null;
_posMaster.lastUpdateFullName = "System Administrator";
_posMaster.lastUpdatedAt = _Date;
await this.employeePosMasterRepository.save(_posMaster);
await CreatePosMasterHistoryEmployee(_posMaster.id, null);
}
}
}
}
@Get("cornjob/cronjobUpdateRetirementStatus")
async runCronjobUpdateRetirementStatus() {
await this.cronjobUpdateRetirementStatus();
@ -1791,20 +1956,13 @@ export class CommandController extends Controller {
const orgLeave = _OrgLeave.filter((x: any) => x !== undefined && x !== null).join("\n");
return {
no: Extension.ToThaiNumber((idx + 1).toString()),
org:
commandCode != "C-PM-21"
? profile?.isLeave == false
? (_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root)
: orgLeave
: (profile?.child4Temp == null ? "" : profile?.child4Temp + "\n") +
(profile?.child3Temp == null ? "" : profile?.child3Temp + "\n") +
(profile?.child2Temp == null ? "" : profile?.child2Temp + "\n") +
(profile?.child1Temp == null ? "" : profile?.child1Temp + "\n") +
(profile?.rootTemp == null ? "" : profile?.rootTemp),
org: profile?.isLeave == false
? (_child4 == null ? "" : _child4 + "\n") +
(_child3 == null ? "" : _child3 + "\n") +
(_child2 == null ? "" : _child2 + "\n") +
(_child1 == null ? "" : _child1 + "\n") +
(_root == null ? "" : _root)
: orgLeave,
fullName: `${x.prefix}${x.firstName} ${x.lastName}`,
citizenId: Extension.ToThaiNumber(x.citizenId),
position: profile?.position ? profile?.position : "-",
@ -1814,14 +1972,9 @@ export class CommandController extends Controller {
`${profile?.posType.posTypeShortName} ${profile?.posLevel.posLevelName}`,
)
: "-",
posNo:
commandCode != "C-PM-21"
? shortName
? Extension.ToThaiNumber(shortName)
: "-"
: Extension.ToThaiNumber(
`${profile?.rootShortNameTemp} ${profile?.posMasterNoTemp}`,
),
posNo: shortName
? Extension.ToThaiNumber(shortName)
: "-",
amount: x.amount ? Extension.ToThaiNumber(x.amount.toLocaleString()) : "-",
dateRetire: profile?.dateRetire
? Extension.ToThaiNumber(Extension.ToThaiShortDate_monthYear(profile?.dateRetire))
@ -3039,13 +3192,10 @@ export class CommandController extends Controller {
where: { refId: In(_refId) },
});
// 2. ดึง commandId ที่ไม่ซ้ำ
const commandIds = Array.from(new Set(commandRecives.map(x => x.commandId).filter(Boolean)));
const commandIds = Array.from(new Set(commandRecives.map((x) => x.commandId).filter(Boolean)));
// 3. อัปเดต status ของ command
if (commandIds.length > 0) {
await this.commandRepository.update(
{ id: In(commandIds) },
{ status: "CANCEL" }
);
await this.commandRepository.update({ id: In(commandIds) }, { status: "CANCEL" });
}
return new HttpSuccess();
}
@ -3555,7 +3705,7 @@ export class CommandController extends Controller {
if (commandRecive && commandRecive.commandId) {
await this.commandRepository.update(
{ id: commandRecive?.commandId },
{ status: "CANCEL" }
{ status: "CANCEL" },
);
}
}
@ -3891,7 +4041,7 @@ export class CommandController extends Controller {
if (commandRecive && commandRecive.commandId) {
await this.commandRepository.update(
{ id: commandRecive?.commandId },
{ status: "CANCEL" }
{ status: "CANCEL" },
);
}
}
@ -4540,6 +4690,7 @@ export class CommandController extends Controller {
if (item.isLeave != null) {
const _profile = await this.profileRepository.findOne({
where: { id: item.profileId },
relations: ["roleKeycloaks"],
});
if (!_profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัตินี้");
@ -4742,6 +4893,7 @@ export class CommandController extends Controller {
if (item.isLeave != null) {
const _profile = await this.profileEmployeeRepository.findOne({
where: { id: item.profileId },
relations: ["roleKeycloaks"],
});
if (!_profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัตินี้");
@ -5034,6 +5186,7 @@ export class CommandController extends Controller {
if (item.isLeave != null) {
const _profile = await this.profileEmployeeRepository.findOne({
where: { id: item.profileId },
relations: ["roleKeycloaks"],
});
if (!_profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัตินี้");
@ -5735,7 +5888,7 @@ export class CommandController extends Controller {
//กรณีลูกจ้างประจำมาสอบเป็นข้าราชการ ต้อง update สถานะโปรไฟล์เดิม
let profileEmployee: any = await this.profileEmployeeRepository.findOne({
where: { citizenId: item.bodyProfile.citizenId },
relations: ["profileInsignias"],
relations: ["profileInsignias", "roleKeycloaks"],
});
if (profileEmployee) {
const _order = await this.salaryRepo.findOne({

View file

@ -2293,22 +2293,22 @@ export class EmployeePositionController extends Controller {
if (!dataMaster) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งนี้");
}
if (dataMaster.current_holderId != null) {
const profile = await this.profileRepository.findOne({
where: {
id: dataMaster.current_holderId,
},
});
const _null: any = null;
if (profile != null) {
profile.posLevelId = _null;
profile.posTypeId = _null;
profile.position = _null;
profile.employeeOc = _null;
profile.positionEmployeePositionId = _null;
await this.profileRepository.save(profile);
}
}
// if (dataMaster.current_holderId != null) {
// const profile = await this.profileRepository.findOne({
// where: {
// id: dataMaster.current_holderId,
// },
// });
// const _null: any = null;
// if (profile != null) {
// profile.posLevelId = _null;
// profile.posTypeId = _null;
// profile.position = _null;
// profile.employeeOc = _null;
// profile.positionEmployeePositionId = _null;
// await this.profileRepository.save(profile);
// }
// }
await this.employeePosMasterRepository.update(id, {
isSit: false,

View file

@ -0,0 +1,126 @@
import axios from "axios";
import {
Controller,
Post,
Delete,
Route,
Security,
Tags,
Body,
Path,
Request,
Response,
Get,
} from "tsoa";
import HttpError from "../interfaces/http-error";
import HttpStatusCode from "../interfaces/http-status";
interface CachedToken {
token: string;
expiry: Date;
}
const API_URL_BANGKOK = "https://exprofile.bangkok.go.th/API";
const clientId = "e5f6ad6ce374177eef023bf5d0c018b6";
const clientSecret = "5EhOvN5DwHOKakupqT9FmCk7MOwpT3zLqLPkPh4ZhJpxBN2nMG@2022";
class TokenCache {
private static cache: Map<string, CachedToken> = new Map();
static get(key: string): string | null {
const cached = this.cache.get(key);
if (!cached) return null;
return cached.token;
}
static set(key: string, token: string): void {
this.cache.set(key, { token, expiry: new Date(Date.now() + 50 * 60 * 1000) });
}
static delete(key: string): void {
this.cache.delete(key);
}
}
@Route("api/v1/org/ex/retirement")
@Tags("ExRetirement")
@Security("bearerAuth")
export class ExRetirementController extends Controller {
@Post()
async getExRetirement(
@Body()
requestBody: {
type: string; //ประเภท
retireYear: string; //ปีที่เกษียณ
citizenID: string; //เลขบัตรประชาชน
firstNameTH: string; //ชื่อ
lastNameTH: string; //นามสกุล
page: number; //หน้า
},
) {
let retryCount = 0;
const maxRetries = 2;
while (retryCount < maxRetries) {
try {
const token = await getToken(clientId, clientSecret);
if (!token) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่สามารถขอ Token ได้");
}
const scope = requestBody.type === "officer" ? "getOfficerRetireData" : "";
const startRecord = requestBody.page !== 1 ? (requestBody.page - 1) * 25 : 0;
const formData = new FormData();
formData.append("scope", scope);
formData.append("startRecord", startRecord.toString());
formData.append("retireYear", requestBody.retireYear);
formData.append("citizenID", requestBody.citizenID);
formData.append("firstNameTH", requestBody.firstNameTH);
formData.append("lastNameTH", requestBody.lastNameTH);
const res = await axios.post(API_URL_BANGKOK + "/getData", formData, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return res.data;
} catch (error: any) {
if (error.response?.status === 500 && retryCount < maxRetries - 1) {
TokenCache.delete(`${clientId}:${clientSecret}`);
retryCount++;
continue;
}
throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "ไม่สามารถติดต่อ API ได้");
}
}
}
}
async function getToken(ClientID: string, ClientSecret: string): Promise<string> {
const cacheKey = `${ClientID}:${ClientSecret}`;
// ลองหา token ใน cache ก่อน
const cachedToken = TokenCache.get(cacheKey);
if (cachedToken) {
return cachedToken;
}
// ถ้าไม่มีใน cache ให้ขอใหม่
try {
const formData = new FormData();
formData.append("ClientID", ClientID);
formData.append("ClientSecret", ClientSecret);
const res = await axios.post(API_URL_BANGKOK + "/authorize", formData, {
headers: {
"Content-Type": "application/json",
},
});
const token = res.data.token;
TokenCache.set(cacheKey, token);
return token;
} catch (error) {
return Promise.reject({ message: "Error occurred", error });
}
}

View file

@ -1,3 +1,9 @@
import { ProfileEmployee } from "./../entities/ProfileEmployee";
import { EmployeePosition } from "./../entities/EmployeePosition";
import { EmployeePosMaster } from "./../entities/EmployeePosMaster";
import { Position } from "./../entities/Position";
import { ProfileSalaryHistory } from "./../entities/ProfileSalaryHistory";
import { ProfileSalary } from "./../entities/ProfileSalary";
import {
Controller,
Get,
@ -31,7 +37,11 @@ import { sendToQueueOrg, sendToQueueOrgDraft } from "../services/rabbitmq";
import { PosType } from "../entities/PosType";
import { PosLevel } from "../entities/PosLevel";
import { PermissionOrg } from "../entities/PermissionOrg";
import { deleteUser, getToken } from "../keycloak";
import {
CreatePosMasterHistoryEmployee,
CreatePosMasterHistoryOfficer,
} from "../services/PositionService";
@Route("api/v1/org")
@Tags("Organization")
@Security("bearerAuth")
@ -51,7 +61,13 @@ export class OrganizationController extends Controller {
private posTypeRepository = AppDataSource.getRepository(PosType);
private posLevelRepository = AppDataSource.getRepository(PosLevel);
private permissionOrgRepository = AppDataSource.getRepository(PermissionOrg);
private profileSalaryRepository = AppDataSource.getRepository(ProfileSalary);
private salaryHistoryRepo = AppDataSource.getRepository(ProfileSalaryHistory);
private positionRepository = AppDataSource.getRepository(Position);
private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee);
private employeePosMasterRepository = AppDataSource.getRepository(EmployeePosMaster);
private employeePositionRepository = AppDataSource.getRepository(EmployeePosition);
/**
* API
*
@ -1136,26 +1152,6 @@ export class OrganizationController extends Controller {
*/
@Get("super-admin/{id}")
async detailSuperAdmin(@Path() id: string, @Request() request: RequestWithUser) {
// let _data: any = {
// root: null,
// child1: null,
// child2: null,
// child3: null,
// child4: null,
// };
// const orgRevision = await this.orgRevisionRepository.findOne({ where: { id } });
// if (!orgRevision) {
// throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
// }
// if (!request.user.role.includes("SUPER_ADMIN")) {
// if (orgRevision.orgRevisionIsDraft == true && orgRevision.orgRevisionIsCurrent == false) {
// _data = await this.listAuthSysOrgFuncByRevisionIdN(request, "SYS_ORG", orgRevision.id);
// } else {
// _data = await this.listAuthSysOrgFuncByRevisionIdC(request, "SYS_ORG", orgRevision.id);
// }
// }
const orgRevision = await this.orgRevisionRepository.findOne({
where: { id: id },
relations: ["posMasters"],
@ -7511,208 +7507,7 @@ export class OrganizationController extends Controller {
const check = orgRevision.orgRoots.find((x) => x.isDeputy == true);
return new HttpSuccess(check != null);
}
public async listAuthSysOrgFuncByRevisionIdN(
request: RequestWithUser,
system: string,
revisionId: string,
) {
let profile = await this.profileRepo.findOne({
where: {
keycloak: request.user.sub,
},
relations: ["next_holders", "next_holders.authRole", "next_holders.authRole.authRoles"],
});
let data: any = {
root: [null],
child1: [null],
child2: [null],
child3: [null],
child4: [null],
};
if (!profile) {
return {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
}
let attrOwnership =
profile?.next_holders
.filter((x) => x.orgRevisionId == revisionId)[0]
?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrOwnership || null;
let attrPrivilege =
profile?.next_holders
.filter((x) => x.orgRevisionId == revisionId)[0]
?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrPrivilege || null;
const posMaster = await this.posMasterRepository.findOne({
where: {
next_holderId: profile.id,
orgRevisionId: revisionId,
},
});
if (!posMaster) {
data = {
root: [null],
child1: [null],
child2: [null],
child3: [null],
child4: [null],
};
} else if (attrOwnership == "OWNER") {
data = {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
} else if (attrPrivilege == "ROOT") {
data = {
root: [posMaster.orgRootId],
child1: null,
child2: null,
child3: null,
child4: null,
privilege: "ROOT",
};
} else if (attrPrivilege == "CHILD") {
let node = 4;
if (posMaster.orgChild1Id == null) {
node = 0;
} else if (posMaster.orgChild2Id == null) {
node = 1;
} else if (posMaster.orgChild3Id == null) {
node = 2;
} else if (posMaster.orgChild4Id == null) {
node = 3;
}
data = {
root: node >= 0 ? [posMaster.orgRootId] : null,
child1: node >= 1 ? [posMaster.orgChild1Id] : null,
child2: node >= 2 ? [posMaster.orgChild2Id] : null,
child3: node >= 3 ? [posMaster.orgChild3Id] : null,
child4: node >= 4 ? [posMaster.orgChild4Id] : null,
};
} else if (attrPrivilege == "NORMAL") {
data = {
root: [posMaster.orgRootId],
child1: [posMaster.orgChild1Id],
child2: [posMaster.orgChild2Id],
child3: [posMaster.orgChild3Id],
child4: [posMaster.orgChild4Id],
};
} else if (attrPrivilege == "SPECIFIC") {
}
return data;
}
public async listAuthSysOrgFuncByRevisionIdC(
request: RequestWithUser,
system: string,
revisionId: string,
) {
let profile = await this.profileRepo.findOne({
where: {
keycloak: request.user.sub,
},
relations: [
"current_holders",
"current_holders.authRole",
"current_holders.authRole.authRoles",
],
});
let data: any = {
root: [null],
child1: [null],
child2: [null],
child3: [null],
child4: [null],
};
if (!profile) {
return {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
}
let attrOwnership =
profile?.current_holders
.filter((x) => x.orgRevisionId == revisionId)[0]
?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrOwnership || null;
let attrPrivilege =
profile?.current_holders
.filter((x) => x.orgRevisionId == revisionId)[0]
?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrPrivilege || null;
const posMaster = await this.posMasterRepository.findOne({
where: {
next_holderId: profile.id,
orgRevisionId: revisionId,
},
});
if (!posMaster) {
data = {
root: [null],
child1: [null],
child2: [null],
child3: [null],
child4: [null],
};
} else if (attrOwnership == "OWNER") {
data = {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
} else if (attrPrivilege == "ROOT") {
data = {
root: [posMaster.orgRootId],
child1: null,
child2: null,
child3: null,
child4: null,
privilege: "ROOT",
};
} else if (attrPrivilege == "CHILD") {
let node = 4;
if (posMaster.orgChild1Id == null) {
node = 0;
} else if (posMaster.orgChild2Id == null) {
node = 1;
} else if (posMaster.orgChild3Id == null) {
node = 2;
} else if (posMaster.orgChild4Id == null) {
node = 3;
}
data = {
root: node >= 0 ? [posMaster.orgRootId] : null,
child1: node >= 1 ? [posMaster.orgChild1Id] : null,
child2: node >= 2 ? [posMaster.orgChild2Id] : null,
child3: node >= 3 ? [posMaster.orgChild3Id] : null,
child4: node >= 4 ? [posMaster.orgChild4Id] : null,
};
} else if (attrPrivilege == "NORMAL") {
data = {
root: [posMaster.orgRootId],
child1: [posMaster.orgChild1Id],
child2: [posMaster.orgChild2Id],
child3: [posMaster.orgChild3Id],
child4: [posMaster.orgChild4Id],
};
} else if (attrPrivilege == "SPECIFIC") {
}
return data;
}
/**
* API 1
*
@ -7915,4 +7710,318 @@ export class OrganizationController extends Controller {
return new HttpSuccess();
}
/**
* API
*
* @summary - (ADMIN)
*
*/
@Get("delete/profile/org/{orgRevisionId}")
async deleteRetireInOrg(@Path() orgRevisionId: string, @Request() request: RequestWithUser) {
// const posMasters = await this.posMasterRepository.find({
// where: {
// orgRevisionId: orgRevisionId,
// current_holder: {
// isLeave: true,
// },
// },
// });
// let check = 0;
// await Promise.all(
// posMasters.map(async (posMaster) => {
// posMaster.current_holderId = null;
// await this.posMasterRepository.save(posMaster);
// check += 1;
// }),
// );
const posMastersEmployee = await this.employeePosMasterRepository.find({
where: {
orgRevisionId: orgRevisionId,
current_holder: {
isLeave: true,
leaveType: "RETIRE",
},
positions: { positionIsSelected: true },
},
});
let check = 0;
await Promise.all(
posMastersEmployee.map(async (posMaster) => {
posMaster.current_holderId = null;
if (posMaster.positions) {
for (const position of posMaster.positions) {
position.positionIsSelected = false;
await this.employeePositionRepository.save(position);
check += 1;
}
}
await this.employeePosMasterRepository.save(posMaster);
await CreatePosMasterHistoryEmployee(posMaster.id, null);
check += 1;
}),
);
// จำนวนคนที่ถูกลบออกจากโครงสร้าง
const total = posMastersEmployee.length;
return new HttpSuccess({ total, successAmount: check });
}
/**
* API
*
* @summary - (ADMIN)
*
*/
@Get("save/profile/position-history")
async saveRetireToPositionHistory(@Request() request: RequestWithUser) {
// const profileLeave = await this.profileRepo.find({
// where: {
// isLeave: true,
// leaveType: "RETIRE",
// },
// });
// let check: number = 0;
// await Promise.all(
// profileLeave.map(async (profile: any) => {
// const dest_item = await this.profileSalaryRepository.findOne({
// where: { profileId: profile.id },
// order: { order: "DESC" },
// });
// const data: any = {
// order: dest_item == null ? 1 : dest_item.order + 1,
// amount: null,
// positionSalaryAmount: null,
// mouthSalaryAmount: null,
// profileId: profile.id,
// posNo: null,
// positionExecutive: null,
// positionType: null,
// positionLevel: null,
// amountSpecial: null,
// orgRoot: null,
// orgChild1: null,
// orgChild2: null,
// orgChild3: null,
// orgChild4: null,
// commandYear: new Date().getFullYear() + 543,
// commandDateAffect: profile.dateLeave,
// commandCode: "16",
// commandName: "พ้นจากราชการ",
// posNoAbb: null,
// isEntry: false,
// positionName: "เกษียณอายุราชการ",
// createdUserId: request.user.sub,
// createdFullName: request.user.name,
// lastUpdateUserId: request.user.sub,
// lastUpdateFullName: request.user.name,
// createdAt: new Date(),
// lastUpdatedAt: new Date(),
// remark: "ประกาศคณะอนุกรรมการสามัญข้าราชการกรุงเทพมหานครสามัญ ลว. 31 มี.ค. 68", // script เกษียณจริง ๆ ให้เอา “วันที่ประกาศเกษียณฉบับแรก” มาลงในเอกสารอ้างอิง
// isGovernment: false,
// };
// const history = new ProfileSalaryHistory();
// Object.assign(history, { ...data, id: undefined });
// data.dateGovernment = profile.dateLeave;
// const savedData = await this.profileSalaryRepository.save(data);
// history.profileSalaryId = savedData.id;
// await this.salaryHistoryRepo.save(history);
// check += 1;
// }),
// );
const profileLeave = await this.profileEmployeeRepo.find({
where: {
isLeave: true,
leaveType: "RETIRE",
},
});
let check: number = 0;
await Promise.all(
profileLeave.map(async (profile: any) => {
const dest_item = await this.profileSalaryRepository.findOne({
where: { profileEmployeeId: profile.id },
order: { order: "DESC" },
});
const data: any = {
order: dest_item == null ? 1 : dest_item.order + 1,
amount: null,
positionSalaryAmount: null,
mouthSalaryAmount: null,
profileEmployeeId: profile.id,
posNo: null,
positionExecutive: null,
positionType: null,
positionLevel: null,
amountSpecial: null,
orgRoot: null,
orgChild1: null,
orgChild2: null,
orgChild3: null,
orgChild4: null,
commandYear: new Date().getFullYear() + 543,
commandDateAffect: profile.dateLeave,
commandCode: "16",
commandName: "พ้นจากราชการ",
posNoAbb: null,
isEntry: false,
positionName: "เกษียณอายุราชการ",
createdUserId: request.user.sub,
createdFullName: request.user.name,
lastUpdateUserId: request.user.sub,
lastUpdateFullName: request.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
remark: "ประกาศคณะอนุกรรมการสามัญข้าราชการกรุงเทพมหานครสามัญ ลว. 31 มี.ค. 68", // script เกษียณจริง ๆ ให้เอา “วันที่ประกาศเกษียณฉบับแรก” มาลงในเอกสารอ้างอิง
isGovernment: false,
};
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
data.dateGovernment = profile.dateLeave;
const savedData = await this.profileSalaryRepository.save(data);
history.profileSalaryId = savedData.id;
await this.salaryHistoryRepo.save(history);
check += 1;
}),
);
// จำนวนคนที่บันทึกลงประวัติตำแหน่ง
const total = profileLeave.length;
// จำนวนคนที่ถูกบันทึกลงประวัติตำแหน่งสำเร็จ
return new HttpSuccess({ total, successAmount: check });
}
/**
* API keycloak
*
* @summary - keycloak (ADMIN)
*
*/
@Get("update/profile/leave-reason")
async updateRetireReason() {
// const profileLeave = await this.profileRepo.find({
// where: {
// isLeave: true,
// leaveType: "RETIRE",
// },
// });
// let check: number = 0;
// let notDelete: string[] = [];
// await Promise.all(
// profileLeave.map(async (profile) => {
// profile.leaveReason = "เกษียณอายุราชการ";
// profile.isActive = false;
// if (profile.keycloak != null && profile.keycloak != "") {
// const delUserKeycloak = await deleteUser(profile.keycloak);
// if (delUserKeycloak) {
// profile.keycloak = "";
// profile.roleKeycloaks = [];
// check += 1;
// } else {
// // push array not delete
// notDelete.push(profile.keycloak);
// }
// }
// await this.profileRepo.save(profile);
// }),
// );
const [profileLeave, token] = await Promise.all([
this.profileEmployeeRepo.find({
where: {
isLeave: true,
leaveType: "RETIRE",
},
}),
getToken(),
]);
if (!token)
throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "ไม่สามารถเชื่อมต่อ Keycloak");
let check: number = 0;
let notDelete: string[] = [];
// loop batch at 50 profiles
const chunkSize = 50;
for (let i = 0; i < profileLeave.length; i += chunkSize) {
const chunk = profileLeave.slice(i, i + chunkSize);
await Promise.all(
chunk.map(async (profile) => {
profile.leaveReason = "เกษียณอายุราชการ";
profile.isActive = false;
if (profile.keycloak != null && profile.keycloak != "") {
const delUserKeycloak = await deleteUser(profile.keycloak, token);
if (delUserKeycloak) {
profile.keycloak = "";
profile.roleKeycloaks = [];
check += 1;
} else {
// push array not delete
notDelete.push(profile.keycloak);
}
}
await this.profileEmployeeRepo.save(profile);
}),
);
}
// จำนวนคนที่ถูกแก้ไขเหตุผลการลาออก
const total = profileLeave.length;
return new HttpSuccess({ total, successAmount: check, notDelete });
}
/**
* API
*
* @summary - (ADMIN)
*
*/
@Get("update/org/position/remove-select/{orgRevisionId}")
async updatePositionSelectOrg(
@Path() orgRevisionId: string,
@Request() request: RequestWithUser,
) {
const posMasters = await this.posMasterRepository.find({
where: {
orgRevisionId: orgRevisionId,
current_holderId: IsNull(),
positions: { positionIsSelected: true },
},
relations: ["positions"],
});
// update position positionIsSelected = 0
let check = 0;
await Promise.all(
posMasters.map(async (posMaster) => {
if (posMaster.positions && posMaster.positions.length > 0) {
for (const position of posMaster.positions) {
position.positionIsSelected = false;
await this.positionRepository.save(position);
check += 1;
}
await CreatePosMasterHistoryOfficer(posMaster.id, null);
}
}),
);
// จำนวนคนที่ถูกลบออกจากโครงสร้าง
const total = posMasters.length;
return new HttpSuccess({ total, successAmount: check });
}
}

View file

@ -73,29 +73,10 @@ export class OrganizationDotnetController extends Controller {
role?: string | null;
nodeId?: string | null;
node?: number | null;
page: number;
pageSize: number;
},
) {
// const profileRepository = AppDataSource.getRepository(Profile);
// const queryBuilder = profileRepository
// .createQueryBuilder("profile")
// .leftJoinAndSelect("profile.posLevel", "posLevel")
// .leftJoinAndSelect("profile.posType", "posType")
// if (body.citizenId || body.firstName || body.lastName) {
// queryBuilder.where(
// new Brackets((qb) => {
// if (body.citizenId) {
// qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
// }
// if (body.firstName) {
// qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
// }
// if (body.lastName) {
// qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
// }
// }),
// );
// }
// const profiles = await queryBuilder.getMany();
let condition = "1=1";
let conditionParams = {};
if (body.role === "CHILD") {
@ -120,12 +101,13 @@ export class OrganizationDotnetController extends Controller {
break;
}
conditionParams = { nodeId: body.nodeId };
}
else if (body.role === "ROOT") {
} else if (body.role === "ROOT") {
condition = "orgRoot.ancestorDNA = :nodeId";
conditionParams = { nodeId: body.nodeId };
}
else if (body.role === "NORMAL") {
} else if (body.role === "PARENT") {
condition = "orgRoot.ancestorDNA = :nodeId AND current_holders.orgChild1 IS NOT NULL";
conditionParams = { nodeId: body.nodeId };
} else if (body.role === "NORMAL") {
switch (body.node) {
case 0:
condition = "orgRoot.ancestorDNA = :nodeId AND current_holders.orgChild1 IS NULL";
@ -150,12 +132,12 @@ export class OrganizationDotnetController extends Controller {
}
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
});
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
const profiles = await this.profileRepo
const [profiles, total] = await this.profileRepo
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.posLevel", "posLevel")
.leftJoinAndSelect("profile.posType", "posType")
@ -169,20 +151,29 @@ export class OrganizationDotnetController extends Controller {
.andWhere(
new Brackets((qb) => {
if (body.citizenId) {
qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
qb.andWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
}
if (body.firstName) {
qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
qb.andWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
}
if (body.lastName) {
qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
qb.andWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
}
}),
)
.andWhere(condition, conditionParams)
.getMany()
return new HttpSuccess(profiles);
.select([
"profile.id",
"profile.citizenId",
"profile.prefix",
"profile.firstName",
"profile.lastName",
])
.skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
return new HttpSuccess({ data: profiles, total: total });
}
/**
@ -201,40 +192,10 @@ export class OrganizationDotnetController extends Controller {
role?: string | null;
nodeId?: string | null;
node?: number | null;
page: number;
pageSize: number;
},
) {
// const profileRepository = AppDataSource.getRepository(ProfileEmployee);
// const queryBuilder = profileRepository
// .createQueryBuilder("profile")
// .leftJoinAndSelect("profile.posLevel", "posLevel")
// .leftJoinAndSelect("profile.posType", "posType")
// .leftJoinAndSelect("profile.profileSalary", "profileSalary")
// .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")
// .orderBy("profileSalary.order", "DESC");
// if (body.citizenId || body.firstName || body.lastName) {
// queryBuilder.where(
// new Brackets((qb) => {
// if (body.citizenId) {
// qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
// }
// if (body.firstName) {
// qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
// }
// if (body.lastName) {
// qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
// }
// }),
// );
// }
// const profileEmp = await queryBuilder.getMany();
let condition = "1=1";
let conditionParams = {};
if (body.role === "CHILD") {
@ -259,12 +220,13 @@ export class OrganizationDotnetController extends Controller {
break;
}
conditionParams = { nodeId: body.nodeId };
}
else if (body.role === "ROOT") {
} else if (body.role === "ROOT") {
condition = "orgRoot.ancestorDNA = :nodeId";
conditionParams = { nodeId: body.nodeId };
}
else if (body.role === "NORMAL") {
} else if (body.role === "PARENT") {
condition = "orgRoot.ancestorDNA = :nodeId AND current_holders.orgChild1 IS NOT NULL";
conditionParams = { nodeId: body.nodeId };
} else if (body.role === "NORMAL") {
switch (body.node) {
case 0:
condition = "orgRoot.ancestorDNA = :nodeId AND current_holders.orgChild1 IS NULL";
@ -294,7 +256,7 @@ export class OrganizationDotnetController extends Controller {
if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
const profileEmp = await this.profileEmpRepo
const [profileEmp, total] = await this.profileEmpRepo
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.posLevel", "posLevel")
.leftJoinAndSelect("profile.posType", "posType")
@ -309,110 +271,30 @@ export class OrganizationDotnetController extends Controller {
.andWhere(
new Brackets((qb) => {
if (body.citizenId) {
qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
qb.andWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
}
if (body.firstName) {
qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
qb.andWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
}
if (body.lastName) {
qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
qb.andWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
}
}),
)
.andWhere(condition, conditionParams)
.orderBy("profileSalary.order", "DESC")
.getMany()
.select([
"profile.id",
"profile.citizenId",
"profile.prefix",
"profile.firstName",
"profile.lastName",
])
.skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
const profileEmp_ = await Promise.all(
profileEmp.map((item: ProfileEmployee) => {
const rootName =
item.current_holders.length == 0
? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgRoot
?.orgRootName;
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
? `${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
? `${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
? `${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
? `${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
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}`
: null;
return {
oc: rootName,
id: item.id,
createdAt: item.createdAt,
createdUserId: item.createdUserId,
lastUpdatedAt: item.lastUpdatedAt,
lastUpdateUserId: item.lastUpdateUserId,
createdFullName: item.createdFullName,
lastUpdateFullName: item.lastUpdateFullName,
avatar: item.avatar,
avatarName: item.avatarName,
rank: item.rank,
prefix: item.prefix,
firstName: item.firstName,
lastName: item.lastName,
citizenId: item.citizenId,
position: item.position,
posLevelId: item.posLevelId,
posTypeId: item.posTypeId,
email: item.email,
phone: item.phone,
keycloak: item.keycloak,
isProbation: item.isProbation,
isLeave: item.isLeave,
leaveReason: item.leaveReason,
dateLeave: item.dateLeave,
dateRetire: item.dateRetire,
dateAppoint: item.dateAppoint,
dateRetireLaw: item.dateRetireLaw,
dateStart: item.dateStart,
govAgeAbsent: item.govAgeAbsent,
govAgePlus: item.govAgePlus,
birthDate: item.birthDate ?? new Date(),
reasonSameDate: item.reasonSameDate,
ethnicity: item.ethnicity,
telephoneNumber: item.phone,
nationality: item.nationality,
gender: item.gender,
relationship: item.relationship,
religion: item.religion,
bloodGroup: item.bloodGroup,
registrationAddress: item.registrationAddress,
registrationProvinceId: item.registrationProvinceId,
registrationDistrictId: item.registrationDistrictId,
registrationSubDistrictId: item.registrationSubDistrictId,
registrationZipCode: item.registrationZipCode,
currentAddress: item.currentAddress,
currentProvinceId: item.currentProvinceId,
currentDistrictId: item.currentDistrictId,
currentSubDistrictId: item.currentSubDistrictId,
currentZipCode: item.currentZipCode,
posLevel: item.posLevel,
posType: item.posType,
posNo: shortName,
};
}),
);
return new HttpSuccess(profileEmp_);
return new HttpSuccess({ data: profileEmp, total: total });
}
/**
@ -693,10 +575,10 @@ export class OrganizationDotnetController extends Controller {
}
}
}
let positionLeaveName =
let positionLeaveName =
profile.posType == null && profile.posLevel == null
? ""
: `${profile.posType?.posTypeShortName ?? ""} ${profile.posLevel?.posLevelName ?? ""}`
? ""
: `${profile.posType?.posTypeShortName ?? ""} ${profile.posLevel?.posLevelName ?? ""}`;
const _profileCurrent = profile?.current_holders?.find(
(x) =>
@ -4077,27 +3959,27 @@ export class OrganizationDotnetController extends Controller {
// };
// }
// } else {
if (body.node === 0) {
typeCondition = {
orgRootId: body.nodeId,
};
} else if (body.node === 1) {
typeCondition = {
orgChild1Id: body.nodeId,
};
} else if (body.node === 2) {
typeCondition = {
orgChild2Id: body.nodeId,
};
} else if (body.node === 3) {
typeCondition = {
orgChild3Id: body.nodeId,
};
} else if (body.node === 4) {
typeCondition = {
orgChild4Id: body.nodeId,
};
}
if (body.node === 0) {
typeCondition = {
orgRootId: body.nodeId,
};
} else if (body.node === 1) {
typeCondition = {
orgChild1Id: body.nodeId,
};
} else if (body.node === 2) {
typeCondition = {
orgChild2Id: body.nodeId,
};
} else if (body.node === 3) {
typeCondition = {
orgChild3Id: body.nodeId,
};
} else if (body.node === 4) {
typeCondition = {
orgChild4Id: body.nodeId,
};
}
// }
let profile = await this.profileRepo.find({
where: { keycloak: Not(IsNull()) || Not(""), isLeave: false, current_holders: typeCondition },
@ -4123,10 +4005,7 @@ export class OrganizationDotnetController extends Controller {
// isLeave: false,
current_holders: typeCondition,
// isRetirement: true,
dateRetire: And(
Not(IsNull()),
Between(startOfYear, endOfYear)
)
dateRetire: And(Not(IsNull()), Between(startOfYear, endOfYear)),
},
relations: [
"posType",
@ -4397,15 +4276,15 @@ export class OrganizationDotnetController extends Controller {
},
) {
let findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
});
switch (body.node) {
case 0:
let orgRoot = await this.orgRootRepo.findOne({
where: {
where: {
id: body.nodeId,
orgRevisionId: findRevision?.id
}
orgRevisionId: findRevision?.id,
},
});
return new HttpSuccess({
rootName: orgRoot?.orgRootName ?? null,
@ -4418,10 +4297,10 @@ export class OrganizationDotnetController extends Controller {
case 1:
let orgChild1 = await this.orgChild1Repo.findOne({
relations: ["orgRoot"],
where: {
where: {
id: body.nodeId,
orgRevisionId: findRevision?.id
}
orgRevisionId: findRevision?.id,
},
});
return new HttpSuccess({
rootName: orgChild1?.orgRoot.orgRootName ?? null,
@ -4434,10 +4313,10 @@ export class OrganizationDotnetController extends Controller {
case 2:
let orgChild2 = await this.orgChild2Repo.findOne({
relations: ["orgRoot", "orgChild1"],
where: {
where: {
id: body.nodeId,
orgRevisionId: findRevision?.id
}
orgRevisionId: findRevision?.id,
},
});
return new HttpSuccess({
rootName: orgChild2?.orgRoot.orgRootName ?? null,
@ -4450,10 +4329,10 @@ export class OrganizationDotnetController extends Controller {
case 3:
let orgChild3 = await this.orgChild3Repo.findOne({
relations: ["orgRoot", "orgChild1", "orgChild2"],
where: {
where: {
id: body.nodeId,
orgRevisionId: findRevision?.id
}
orgRevisionId: findRevision?.id,
},
});
return new HttpSuccess({
rootName: orgChild3?.orgRoot.orgRootName ?? null,
@ -4466,10 +4345,10 @@ export class OrganizationDotnetController extends Controller {
case 4:
let orgChild4 = await this.orgChild4Repo.findOne({
relations: ["orgRoot", "orgChild1", "orgChild2", "orgChild3"],
where: {
where: {
id: body.nodeId,
orgRevisionId: findRevision?.id
}
orgRevisionId: findRevision?.id,
},
});
return new HttpSuccess({
rootName: orgChild4?.orgRoot.orgRootName ?? null,
@ -4486,7 +4365,7 @@ export class OrganizationDotnetController extends Controller {
child2Name: null,
child3Name: null,
child4Name: null,
});;
});
}
}
@ -4506,98 +4385,131 @@ export class OrganizationDotnetController extends Controller {
role: string;
isRetirement?: boolean;
revisionId?: string;
reqNode?: number;
reqNodeId?: string;
},
) {
let typeCondition: any = {};
const node = body.role === "OWNER" ? null : body.node;
if (body.role === "OWNER" || body.role === "CHILD") {
switch (node) {
if (body.role === "CHILD" || body.role === "PARENT" || body.role === "ROOT") {
switch (body.node) {
case 0:
typeCondition = {
orgRoot: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case 1:
typeCondition = {
orgChild1: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case 2:
typeCondition = {
orgChild2: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case 3:
typeCondition = {
orgChild3: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case 4:
typeCondition = {
orgChild4: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case null:
typeCondition = {};
break;
default:
typeCondition = {};
break;
}
} else if (body.role === "ROOT") {
typeCondition = {
orgRoot: {
ancestorDNA: body.nodeId
},
};
} else if (body.role === "NORMAL") {
switch (node) {
} else if (body.role === "OWNER") {
switch (body.reqNode) {
case 0:
typeCondition = {
orgRoot: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
orgChild1: IsNull()
};
break;
case 1:
typeCondition = {
orgChild1: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
orgChild2: IsNull()
};
break;
case 2:
typeCondition = {
orgChild2: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
orgChild3: IsNull()
};
break;
case 3:
typeCondition = {
orgChild3: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
orgChild4: IsNull()
};
break;
case 4:
typeCondition = {
orgChild4: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
};
break;
default:
typeCondition = {};
break;
}
} else if (body.role === "NORMAL") {
switch (body.node) {
case 0:
typeCondition = {
orgRoot: {
ancestorDNA: body.nodeId,
},
orgChild1: IsNull(),
};
break;
case 1:
typeCondition = {
orgChild1: {
ancestorDNA: body.nodeId,
},
orgChild2: IsNull(),
};
break;
case 2:
typeCondition = {
orgChild2: {
ancestorDNA: body.nodeId,
},
orgChild3: IsNull(),
};
break;
case 3:
typeCondition = {
orgChild3: {
ancestorDNA: body.nodeId,
},
orgChild4: IsNull(),
};
break;
case 4:
typeCondition = {
orgChild4: {
ancestorDNA: body.nodeId,
},
};
break;
@ -4637,8 +4549,8 @@ export class OrganizationDotnetController extends Controller {
orgChild4Order: "ASC",
},
posMasterNo: "ASC",
}
}
},
},
});
if (body.isRetirement) {
profile = await this.profileRepo.find({
@ -4660,7 +4572,7 @@ export class OrganizationDotnetController extends Controller {
});
}
let findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
});
if (body.revisionId) {
@ -4670,7 +4582,7 @@ export class OrganizationDotnetController extends Controller {
}
const profile_ = await Promise.all(
profile.map(async(item: Profile) => {
profile.map(async (item: Profile) => {
const shortName =
item.current_holders.length == 0
? null
@ -4714,8 +4626,8 @@ export class OrganizationDotnetController extends Controller {
let _posMaster = await this.posMasterRepository.findOne({
where: {
orgRevisionId: findRevision?.id,
current_holderId: item.id
}
current_holderId: item.id,
},
});
return {
@ -4736,7 +4648,7 @@ export class OrganizationDotnetController extends Controller {
orgChild1Id: _posMaster?.orgChild1Id,
orgChild2Id: _posMaster?.orgChild2Id,
orgChild3Id: _posMaster?.orgChild3Id,
orgChild4Id: _posMaster?.orgChild4Id
orgChild4Id: _posMaster?.orgChild4Id,
};
}),
);
@ -5068,45 +4980,46 @@ export class OrganizationDotnetController extends Controller {
role: string;
isRetirement?: boolean;
revisionId?: string;
reqNode?: number;
reqNodeId?: string;
},
) {
let typeCondition: any = {};
const node = body.role === "OWNER" ? null : body.node;
if (body.role === "OWNER" || body.role === "CHILD") {
switch (node) {
if (body.role === "CHILD" || body.role === "PARENT" || body.role === "ROOT") {
switch (body.node) {
case 0:
typeCondition = {
orgRoot: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case 1:
typeCondition = {
orgChild1: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case 2:
typeCondition = {
orgChild2: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case 3:
typeCondition = {
orgChild3: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case 4:
typeCondition = {
orgChild4: {
ancestorDNA: body.nodeId
}
ancestorDNA: body.nodeId,
},
};
break;
case null:
@ -5116,50 +5029,85 @@ export class OrganizationDotnetController extends Controller {
typeCondition = {};
break;
}
} else if (body.role === "ROOT") {
typeCondition = {
orgRoot: {
ancestorDNA: body.nodeId
},
};
} else if (body.role === "NORMAL") {
switch (node) {
} else if (body.role === "OWNER") {
switch (body.reqNode) {
case 0:
typeCondition = {
orgRoot: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
orgChild1: IsNull()
};
break;
case 1:
typeCondition = {
orgChild1: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
orgChild2: IsNull()
};
break;
case 2:
typeCondition = {
orgChild2: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
orgChild3: IsNull()
};
break;
case 3:
typeCondition = {
orgChild3: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
orgChild4: IsNull()
};
break;
case 4:
typeCondition = {
orgChild4: {
ancestorDNA: body.nodeId
id: body.reqNodeId,
},
};
break;
default:
typeCondition = {};
break;
}
} else if (body.role === "NORMAL") {
switch (body.node) {
case 0:
typeCondition = {
orgRoot: {
ancestorDNA: body.nodeId,
},
orgChild1: IsNull(),
};
break;
case 1:
typeCondition = {
orgChild1: {
ancestorDNA: body.nodeId,
},
orgChild2: IsNull(),
};
break;
case 2:
typeCondition = {
orgChild2: {
ancestorDNA: body.nodeId,
},
orgChild3: IsNull(),
};
break;
case 3:
typeCondition = {
orgChild3: {
ancestorDNA: body.nodeId,
},
orgChild4: IsNull(),
};
break;
case 4:
typeCondition = {
orgChild4: {
ancestorDNA: body.nodeId,
},
};
break;
@ -5199,8 +5147,8 @@ export class OrganizationDotnetController extends Controller {
orgChild4Order: "ASC",
},
posMasterNo: "ASC",
}
}
},
},
});
if (body.isRetirement) {
profile = await this.profileEmpRepo.find({
@ -5222,7 +5170,7 @@ export class OrganizationDotnetController extends Controller {
});
}
let findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
});
if (body.revisionId) {
@ -5232,7 +5180,7 @@ export class OrganizationDotnetController extends Controller {
}
const profile_ = await Promise.all(
profile.map(async(item: ProfileEmployee) => {
profile.map(async (item: ProfileEmployee) => {
const shortName =
item.current_holders.length == 0
? null
@ -5276,8 +5224,8 @@ export class OrganizationDotnetController extends Controller {
let _posMaster = await this.empPosMasterRepository.findOne({
where: {
orgRevisionId: findRevision?.id,
current_holderId: item.id
}
current_holderId: item.id,
},
});
return {
@ -5291,9 +5239,10 @@ export class OrganizationDotnetController extends Controller {
keycloak: item.keycloak,
posNo: shortName,
position: item.position,
positionLevel: item.posType?.posTypeShortName && item.posLevel?.posLevelName
? `${item.posType?.posTypeShortName} ${item.posLevel?.posLevelName}`
: null,
positionLevel:
item.posType?.posTypeShortName && item.posLevel?.posLevelName
? `${item.posType?.posTypeShortName} ${item.posLevel?.posLevelName}`
: null,
positionType: item.posType?.posTypeName ?? null,
oc: Oc,
orgRootId: _posMaster?.orgRootId,
@ -5511,7 +5460,7 @@ export class OrganizationDotnetController extends Controller {
}
const position = await AppDataSource.query("CALL GetProfileEmployeeSalaryPosition(?, ?)", [
profile.id,
_currentDate
_currentDate,
]);
const _position = position.length > 0 ? position[0] : [];
@ -5521,7 +5470,7 @@ export class OrganizationDotnetController extends Controller {
govAge: profile.dateAppoint
? `${Extension.CalculateGovAge(profile.dateAppoint, 0, 0)} ปี`
: "-",
age: profile.birthDate ? Extension.CalculateAgeStrV2(profile.birthDate, 0, 0) : "-",
age: profile.birthDate ? Extension.CalculateAgeStrV2(profile.birthDate, 0, 0, "GET") : "-",
dateAppoint: profile.dateAppoint,
dateCurrent: new Date(),
amount: profile.amount ?? "-",
@ -5623,11 +5572,13 @@ export class OrganizationDotnetController extends Controller {
}
}
if (profile && profile?.isLeave) {
_currentDate = profile && profile.leaveDate
? Extension.toDateOnlyString(profile.leaveDate)
: _currentDate
_currentDate =
profile && profile.leaveDate ? Extension.toDateOnlyString(profile.leaveDate) : _currentDate;
}
const position = await AppDataSource.query("CALL GetProfileSalaryPosition(?, ?)", [profile.id, _currentDate]);
const position = await AppDataSource.query("CALL GetProfileSalaryPosition(?, ?)", [
profile.id,
_currentDate,
]);
const _position = position.length > 0 ? position[0] : [];
const mapProfile = {
@ -5636,7 +5587,7 @@ export class OrganizationDotnetController extends Controller {
govAge: profile.dateAppoint
? `${Extension.CalculateGovAge(profile.dateAppoint, 0, 0)} ปี`
: "-",
age: profile.birthDate ? Extension.CalculateAgeStrV2(profile.birthDate, 0, 0) : "-",
age: profile.birthDate ? Extension.CalculateAgeStrV2(profile.birthDate, 0, 0, "GET") : "-",
dateAppoint: profile.dateAppoint,
dateCurrent: new Date(),
amount: profile.amount ?? "-",

View file

@ -732,6 +732,14 @@ export class PermissionController extends Controller {
child3: null,
child4: null,
};
} else if (privilege == "PARENT") {
data = {
root: [x.orgRootId],
child1: null,
child2: null,
child3: null,
child4: null,
};
} else if (privilege == "CHILD") {
data = {
root: node >= 0 ? [x.orgRootId] : null,

File diff suppressed because it is too large Load diff

View file

@ -13,6 +13,7 @@ import {
Response,
Get,
Query,
Example,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
@ -79,6 +80,7 @@ import { ProfileChangeName } from "../entities/ProfileChangeName";
import { ProfileChildren } from "../entities/ProfileChildren";
import { ProfileDuty } from "../entities/ProfileDuty";
import { getTopDegrees } from "../services/PositionService";
import { ProfileLeaveService } from "../services/ProfileLeaveService";
@Route("api/v1/org/profile-employee")
@Tags("ProfileEmployee")
@Security("bearerAuth")
@ -131,6 +133,9 @@ export class ProfileEmployeeController extends Controller {
private profileAbilityRepo = AppDataSource.getRepository(ProfileAbility);
private profileAssistanceRepository = AppDataSource.getRepository(ProfileAssistance);
// Services
private profileLeaveService = new ProfileLeaveService();
/**
* report
*
@ -2127,7 +2132,7 @@ export class ProfileEmployeeController extends Controller {
posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
dateEmployment: dateEmployment,
dateAppoint: _data.dateAppoint,
dateStart: _data.dateStart,
@ -2629,6 +2634,29 @@ export class ProfileEmployeeController extends Controller {
*
*/
@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,
},
})
async listProfileLeave(
@Request() request: RequestWithUser,
@Query("page") page: number = 1,
@ -2638,443 +2666,34 @@ export class ProfileEmployeeController extends Controller {
@Query() searchKeyword: string = "",
@Query() posType?: string,
@Query() posLevel?: string,
@Query() yearLeave?: number,
@Query() isProbation?: boolean,
// @Query() isRetire?: boolean,
@Query() type?: string,
@Query() node?: number,
@Query() nodeId?: string,
@Query() isAll?: boolean,
@Query() retireType?: string,
@Query() sortBy: string = "current_holders.posMasterNo",
@Query() sort: "ASC" | "DESC" = "ASC",
@Query() sortBy: string = "profileEmployee.dateLeave",
@Query() sort: "ASC" | "DESC" = "DESC",
) {
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") {
// 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
// `;
// }
else if (searchField == "posNo") {
queryLike = `
CONCAT(profileSalary.posNoAbb, profileSalary.posNo) LIKE :keyword
OR CONCAT(profileSalary.posNoAbb, " ", profileSalary.posNo) LIKE :keyword
OR profileSalary.posNo LIKE :keyword
`;
}
let nodeCondition = "1=1";
let nodeAll = "";
let orgRoot = null;
let orgChild1 = null;
let orgChild2 = null;
let orgChild3 = null;
let orgChild4 = null;
let pmsCondition = "1=1";
let orgRootPms = null;
let orgChild1Pms = null;
let orgChild2Pms = null;
let orgChild3Pms = null;
let orgChild4Pms = null;
const { data, total } = await this.profileLeaveService.getLeaveEmployees(request, {
page,
pageSize,
searchField,
searchKeyword,
posType,
posLevel,
isProbation,
node,
nodeId,
isAll,
retireType,
sortBy,
sort,
_data,
});
if (node === 0 && nodeId) {
orgRoot = await this.orgRootRepository.findOne({ where: { id: nodeId } });
if (orgRoot) {
nodeCondition = "profileSalary.orgRoot = :orgRoot";
}
if (isAll == false) nodeAll = " AND profileSalary.orgChild1 IS NULL";
} else if (node === 1 && nodeId) {
orgChild1 = await this.child1Repository.findOne({ where: { id: nodeId } });
if (orgChild1) {
nodeCondition = "profileSalary.orgChild1 = :orgChild1";
}
if (isAll == false) nodeAll = " AND profileSalary.orgChild2 IS NULL";
} else if (node === 2 && nodeId) {
orgChild2 = await this.child2Repository.findOne({ where: { id: nodeId } });
if (orgChild2) {
nodeCondition = "profileSalary.orgChild2 = :orgChild2";
}
if (isAll == false) nodeAll = " AND profileSalary.orgChild3 IS NULL";
} else if (node === 3 && nodeId) {
orgChild3 = await this.child3Repository.findOne({ where: { id: nodeId } });
if (orgChild3) {
nodeCondition = "profileSalary.orgChild3 = :orgChild3";
}
if (isAll == false) nodeAll = " AND profileSalary.orgChild4 IS NULL";
} else if (node === 4 && nodeId) {
orgChild4 = await this.child4Repository.findOne({ where: { id: nodeId } });
if (orgChild4) {
nodeCondition = "profileSalary.orgChild4 = :orgChild4";
}
}
nodeCondition = nodeCondition + nodeAll;
if (_data.root) {
orgRootPms = await this.orgRootRepository.findOne({ where: { id: _data.root } });
if (orgRootPms) {
pmsCondition = "profileSalary.orgRoot = :orgRootPms";
}
if (isAll == false) nodeAll = " AND profileSalary.orgChild1 IS NULL";
} else if (_data.child1) {
orgChild1Pms = await this.child1Repository.findOne({ where: { id: _data.child1 } });
if (orgChild1Pms) {
pmsCondition = "profileSalary.orgChild1 = :orgChild1Pms";
}
if (isAll == false) nodeAll = " AND profileSalary.orgChild2 IS NULL";
} else if (_data.child2) {
orgChild2Pms = await this.child2Repository.findOne({ where: { id: _data.child2 } });
if (orgChild2Pms) {
pmsCondition = "profileSalary.orgChild2 = :orgChild2Pms";
}
if (isAll == false) nodeAll = " AND profileSalary.orgChild3 IS NULL";
} else if (_data.child3) {
orgChild3Pms = await this.child3Repository.findOne({ where: { id: _data.child3 } });
if (orgChild3Pms) {
pmsCondition = "profileSalary.orgChild3 = :orgChild3Pms";
}
if (isAll == false) nodeAll = " AND profileSalary.orgChild4 IS NULL";
} else if (_data.child4) {
orgChild4Pms = await this.child4Repository.findOne({ where: { id: _data.child4 } });
if (orgChild4Pms) {
pmsCondition = "profileSalary.orgChild4 = :orgChild4Pms";
}
}
pmsCondition = pmsCondition + nodeAll;
// 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")
.leftJoinAndSelect("profileEmployee.profileEmployeeEmployment", "profileEmployeeEmployment")
// .leftJoinAndSelect("current_holders.positions", "positions")
.leftJoinAndSelect("profileEmployee.profileSalary", "profileSalary")
// .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(node && nodeId ? "current_holders.orgRevisionId = :orgRevisionId" : "1=1", {
// orgRevisionId: node && nodeId ? findRevision.id : undefined,
// })
.where(
new Brackets((qb) => {
qb.where("profileEmployee.isLeave = :isLeave", { isLeave: true }).orWhere(
"profileEmployee.isRetirement = :isRetirement",
{ isRetirement: true },
);
}),
)
// .andWhere("profileEmployee.leaveCommandId Is NOT NULL")
.andWhere(
"profileSalary.order = (SELECT MAX(ps.order) FROM profileSalary ps WHERE ps.profileEmployeeId = profileEmployee.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(
posType != undefined && posType != null && posType != ""
? "posType.posTypeName LIKE :keyword1"
: "1=1",
{
keyword1: `${posType}`,
},
)
.andWhere(
posLevel != undefined && posLevel != null && posLevel != ""
? `CONCAT(posType.posTypeShortName,' ',posLevel.posLevelName) LIKE :keyword2`
: "1=1",
{
keyword2: `${posLevel}`,
},
)
.andWhere(
isProbation != undefined && isProbation != null
? `profileEmployee.isProbation = ${isProbation}`
: "1=1",
)
.andWhere(
retireType != undefined && retireType != null
? `profileEmployee.leaveType = :retireType`
: "1=1",
{ retireType: retireType },
)
.andWhere("profileEmployee.employeeClass LIKE :type", {
type: "PERM",
})
.andWhere(
searchKeyword != undefined && searchKeyword != null && searchKeyword != ""
? queryLike
: "1=1",
{
keyword: `%${searchKeyword}%`,
},
)
.andWhere(pmsCondition, {
orgRootPms: orgRootPms ? orgRootPms.orgRootName : "",
orgChild1Pms: orgChild1Pms ? orgChild1Pms.orgChild1Name : "",
orgChild2Pms: orgChild2Pms ? orgChild2Pms.orgChild2Name : "",
orgChild3Pms: orgChild3Pms ? orgChild3Pms.orgChild3Name : "",
orgChild4Pms: orgChild4Pms ? orgChild4Pms.orgChild4Name : "",
})
.andWhere(nodeCondition, {
orgRoot: orgRoot ? orgRoot.orgRootName : "",
orgChild1: orgChild1 ? orgChild1.orgChild1Name : "",
orgChild2: orgChild2 ? orgChild2.orgChild2Name : "",
orgChild3: orgChild3 ? orgChild3.orgChild3Name : "",
orgChild4: orgChild4 ? orgChild4.orgChild4Name : "",
})
// .andWhere(`current_holders.orgRevisionId LIKE :orgRevisionId`, {
// orgRevisionId: findRevision.id,
// })
// .orderBy("current_holders.posMasterNo", "ASC")
// .orderBy(`${sortBy}`, sort)
.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 == findRevision.id) != null &&
// _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 !=
// null
// ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
// : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
// _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
// ?.orgChild3 != null
// ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
// : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
// _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
// ?.orgChild2 != null
// ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
// : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null &&
// _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
// ?.orgChild1 != null
// ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
// : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) !=
// null &&
// _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)
// ?.orgRoot != null
// ? `${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName}${_data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}`
// : null;
const dateEmployment =
_data.profileEmployeeEmployment.length == 0
? null
: _data.profileEmployeeEmployment.reduce((latest, current) => {
return latest.date > current.date ? latest : current;
}).date;
// 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;
// let _child1 = child1?.orgChild1Name;
// let _child2 = child2?.orgChild2Name;
// let _child3 = child3?.orgChild3Name;
// let _child4 = child4?.orgChild4Name;
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,
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,
positionId: _data.positionIdTemp,
posmasterId: _data.posmasterIdTemp,
position: _data.position,
posNo:
_data.profileSalary[0].posNoAbb && _data.profileSalary[0].posNo
? `${_data.profileSalary[0].posNoAbb} ${_data.profileSalary[0].posNo}`
: _data.profileSalary[0].posNo || "",
employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0),
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:
(_data.profileSalary[0].orgChild4 == null
? ""
: _data.profileSalary[0].orgChild4 + "\n") +
(_data.profileSalary[0].orgChild3 == null
? ""
: _data.profileSalary[0].orgChild3 + "\n") +
(_data.profileSalary[0].orgChild2 == null
? ""
: _data.profileSalary[0].orgChild2 + "\n") +
(_data.profileSalary[0].orgChild1 == null
? ""
: _data.profileSalary[0].orgChild1 + "\n") +
(_data.profileSalary[0].orgRoot == null ? "" : _data.profileSalary[0].orgRoot),
};
}),
);
return new HttpSuccess({ data: data, total });
return new HttpSuccess({ data, total });
}
/**
@ -3137,15 +2756,13 @@ export class ProfileEmployeeController extends Controller {
@Query() searchKeyword: string = "",
@Query() posType?: string,
@Query() posLevel?: string,
@Query() yearLeave?: number,
@Query() isProbation?: boolean,
@Query() isRetire?: boolean,
@Query() type?: string,
@Query() node?: number,
@Query() nodeId?: string,
@Query() isAll?: boolean,
@Query() retireType?: string,
@Query() sortBy: string = "current_holders.posMasterNo",
@Query() sortBy?: string,
@Query() sort: "ASC" | "DESC" = "ASC",
) {
let _data = await new permission().PermissionOrgList(request, "SYS_REGISTRY_EMP");
@ -3300,13 +2917,8 @@ export class ProfileEmployeeController extends Controller {
.andWhere(nodeCondition, {
nodeId: nodeId,
})
// .andWhere(`current_holders.orgRevisionId LIKE :orgRevisionId`, {
// orgRevisionId: findRevision.id,
// })
// .orderBy("current_holders.posMasterNo", "ASC")
// .orderBy(`${sortBy}`, sort)
.addSelect("CASE WHEN current_holders.posMasterNo IS NULL THEN 1 ELSE 0 END", "sort_order")
.orderBy("sort_order", "ASC")
.orderBy(sortBy ? sortBy : "sort_order", sort)
.addOrderBy("orgRoot.orgRootOrder", sort)
.addOrderBy("orgChild1.orgChild1Order", sort)
.addOrderBy("orgChild2.orgChild2Order", sort)
@ -3417,7 +3029,7 @@ export class ProfileEmployeeController extends Controller {
posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
dateEmployment: dateEmployment,
dateAppoint: _data.dateAppoint,
dateStart: _data.dateStart,
@ -4981,6 +4593,8 @@ export class ProfileEmployeeController extends Controller {
rootId?: string;
year: number;
period: string;
sortBy?: string;
descending?: boolean;
},
) {
const findRevision = await this.orgRevisionRepo.findOne({
@ -4990,7 +4604,7 @@ export class ProfileEmployeeController extends Controller {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
}
const [findPosMaster, total] = await AppDataSource.getRepository(EmployeePosMaster)
let query = await AppDataSource.getRepository(EmployeePosMaster)
.createQueryBuilder("employeePosMaster")
.leftJoinAndSelect("employeePosMaster.current_holder", "current_holder")
.leftJoinAndSelect("employeePosMaster.orgRoot", "orgRoot")
@ -5121,11 +4735,35 @@ export class ProfileEmployeeController extends Controller {
},
);
}),
)
.orderBy("current_holder.citizenId", "ASC")
);
if (body.sortBy) {
if (body.sortBy === "posType") {
query = query.orderBy(`posType.posTypeName`, body.descending ? "DESC" : "ASC");
} else if (body.sortBy === "posLevel") {
query = query
.orderBy(`posType.posTypeShortName`, body.descending ? "DESC" : "ASC")
.addOrderBy(`posLevel.posLevelName`, body.descending ? "DESC" : "ASC");
} else if (body.sortBy === "orgShortName" || body.sortBy === "posMasterNo") {
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");
}
} else {
query = query.orderBy("current_holder.citizenId", "ASC");
}
const [findPosMaster, total] = await query
.skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
if (!findPosMaster) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. PosMaster");
}

View file

@ -1189,7 +1189,7 @@ export class ProfileEmployeeTempController extends Controller {
posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
dateEmployment: dateEmployment,
dateAppoint: _data.dateAppoint,
dateStart: _data.dateStart,
@ -1724,7 +1724,7 @@ export class ProfileEmployeeTempController extends Controller {
posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
dateEmployment: dateEmployment,
dateAppoint: _data.dateAppoint,
dateStart: _data.dateStart,

View file

@ -237,14 +237,37 @@ export class ProfileGovernmentHistoryController extends Controller {
}
}
let _OrgLeave:any = []
let _profileSalary:any = null;
if (record?.isLeave && record?.profileSalary.length > 0) {
_OrgLeave = [
record?.profileSalary[0].orgChild4 ? record?.profileSalary[0].orgChild4 : null,
record?.profileSalary[0].orgChild3 ? record?.profileSalary[0].orgChild3 : null,
record?.profileSalary[0].orgChild2 ? record?.profileSalary[0].orgChild2 : null,
record?.profileSalary[0].orgChild1 ? record?.profileSalary[0].orgChild1 : null,
record?.profileSalary[0].orgRoot ? record?.profileSalary[0].orgRoot : null,
];
// _OrgLeave = [
// record?.profileSalary[0].orgChild4 ? record?.profileSalary[0].orgChild4 : null,
// record?.profileSalary[0].orgChild3 ? record?.profileSalary[0].orgChild3 : null,
// record?.profileSalary[0].orgChild2 ? record?.profileSalary[0].orgChild2 : null,
// record?.profileSalary[0].orgChild1 ? record?.profileSalary[0].orgChild1 : null,
// record?.profileSalary[0].orgRoot ? record?.profileSalary[0].orgRoot : null,
// ];
if (record.leaveType == "RETIRE") {
_profileSalary = record?.profileSalary.length > 1
? record?.profileSalary[1]
: record?.profileSalary.length > 0
? record?.profileSalary[0]
: null;
} else {
_profileSalary = record?.profileSalary.length > 0
? record?.profileSalary[0]
: null;
}
if (_profileSalary) {
_OrgLeave = [
_profileSalary.orgChild4 ?? null,
_profileSalary.orgChild3 ?? null,
_profileSalary.orgChild2 ?? null,
_profileSalary.orgChild1 ?? null,
_profileSalary.orgRoot ?? null,
];
} else {
_OrgLeave = [];
}
}
const orgLeave = _OrgLeave.filter((x:any) => x !== undefined && x !== null).join("\n");
const data = {
@ -254,8 +277,8 @@ export class ProfileGovernmentHistoryController extends Controller {
posLevel: record?.posLevel == null ? null : record?.posLevel.posLevelName, //ระดับ
posMasterNo: record?.isLeave == false
? posMaster == null ? null : `${orgShortName} ${posMaster.posMasterNo}`
: record && record?.profileSalary.length > 0
? `${record?.profileSalary[0].posNoAbb} ${record?.profileSalary[0].posNo}`
: _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: null, //เลขที่ตำแหน่ง
posType: record?.posType == null ? null : record?.posType.posTypeName, //ประเภท
posExecutive:
@ -373,14 +396,37 @@ export class ProfileGovernmentHistoryController extends Controller {
}
}
let _OrgLeave:any = []
let _profileSalary:any = null;
if (record?.isLeave && record?.profileSalary.length > 0) {
_OrgLeave = [
record?.profileSalary[0].orgChild4 ? record?.profileSalary[0].orgChild4 : null,
record?.profileSalary[0].orgChild3 ? record?.profileSalary[0].orgChild3 : null,
record?.profileSalary[0].orgChild2 ? record?.profileSalary[0].orgChild2 : null,
record?.profileSalary[0].orgChild1 ? record?.profileSalary[0].orgChild1 : null,
record?.profileSalary[0].orgRoot ? record?.profileSalary[0].orgRoot : null,
];
// _OrgLeave = [
// record?.profileSalary[0].orgChild4 ? record?.profileSalary[0].orgChild4 : null,
// record?.profileSalary[0].orgChild3 ? record?.profileSalary[0].orgChild3 : null,
// record?.profileSalary[0].orgChild2 ? record?.profileSalary[0].orgChild2 : null,
// record?.profileSalary[0].orgChild1 ? record?.profileSalary[0].orgChild1 : null,
// record?.profileSalary[0].orgRoot ? record?.profileSalary[0].orgRoot : null,
// ];
if (record.leaveType == "RETIRE") {
_profileSalary = record?.profileSalary.length > 1
? record?.profileSalary[1]
: record?.profileSalary.length > 0
? record?.profileSalary[0]
: null;
} else {
_profileSalary = record?.profileSalary.length > 0
? record?.profileSalary[0]
: null;
}
if (_profileSalary) {
_OrgLeave = [
_profileSalary.orgChild4 ?? null,
_profileSalary.orgChild3 ?? null,
_profileSalary.orgChild2 ?? null,
_profileSalary.orgChild1 ?? null,
_profileSalary.orgRoot ?? null,
];
} else {
_OrgLeave = [];
}
}
const orgLeave = _OrgLeave.filter((x:any) => x !== undefined && x !== null).join("\n");
const data = {
@ -393,8 +439,8 @@ export class ProfileGovernmentHistoryController extends Controller {
? posMaster == null
? null
: `${orgShortName} ${posMaster.posMasterNo}`
: record && record.profileSalary.length > 0
? `${record?.profileSalary[0].posNoAbb} ${record?.profileSalary[0].posNo}`
: _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: null, //เลขที่ตำแหน่ง
posType: record?.posType == null ? null : record?.posType.posTypeName, //ประเภท
posExecutive:

View file

@ -220,6 +220,7 @@ export class ProfileGovernmentEmployeeController extends Controller {
let _OrgLeave:any = []
let orgLeave:string = ""
let posNoLeave:string = ""
let _profileSalary:any = null;
if (record?.isLeave /*&& record?.profileSalary.length > 0*/) {
const profileSalary = await this.salaryRepo.find({
select: [
@ -255,16 +256,38 @@ export class ProfileGovernmentEmployeeController extends Controller {
createdAt: "DESC"
}
});
_OrgLeave = [
profileSalary.length > 0 && profileSalary[0].orgChild4 ? profileSalary[0].orgChild4 : null,
profileSalary.length > 0 && profileSalary[0].orgChild3 ? profileSalary[0].orgChild3 : null,
profileSalary.length > 0 && profileSalary[0].orgChild2 ? profileSalary[0].orgChild2 : null,
profileSalary.length > 0 && profileSalary[0].orgChild1 ? profileSalary[0].orgChild1 : null,
profileSalary.length > 0 && profileSalary[0].orgRoot ? profileSalary[0].orgRoot : null,
];
// _OrgLeave = [
// profileSalary.length > 0 && profileSalary[0].orgChild4 ? profileSalary[0].orgChild4 : null,
// profileSalary.length > 0 && profileSalary[0].orgChild3 ? profileSalary[0].orgChild3 : null,
// profileSalary.length > 0 && profileSalary[0].orgChild2 ? profileSalary[0].orgChild2 : null,
// profileSalary.length > 0 && profileSalary[0].orgChild1 ? profileSalary[0].orgChild1 : null,
// profileSalary.length > 0 && profileSalary[0].orgRoot ? profileSalary[0].orgRoot : null,
// ];
if (record.leaveType == "RETIRE") {
_profileSalary = profileSalary.length > 1
? profileSalary[1]
: profileSalary.length > 0
? profileSalary[0]
: null;
} else {
_profileSalary = profileSalary.length > 0
? profileSalary[0]
: null
}
if (_profileSalary) {
_OrgLeave = [
_profileSalary.orgChild4 ?? null,
_profileSalary.orgChild3 ?? null,
_profileSalary.orgChild2 ?? null,
_profileSalary.orgChild1 ?? null,
_profileSalary.orgRoot ?? null,
];
} else {
_OrgLeave = [];
}
orgLeave = _OrgLeave.filter((x:any) => x !== undefined && x !== null).join("\n");
posNoLeave = profileSalary.length > 0
? `${profileSalary[0].posNoAbb} ${profileSalary[0].posNo}`
posNoLeave = _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: ""
}
const data = {
@ -372,6 +395,7 @@ export class ProfileGovernmentEmployeeController extends Controller {
let _OrgLeave:any = []
let orgLeave:string = ""
let posNoLeave:string = ""
let _profileSalary:any = null;
if (record?.isLeave /*&& record?.profileSalary.length > 0*/) {
const profileSalary = await this.salaryRepo.find({
select: [
@ -407,16 +431,38 @@ export class ProfileGovernmentEmployeeController extends Controller {
createdAt: "DESC"
}
});
_OrgLeave = [
profileSalary.length > 0 && profileSalary[0].orgChild4 ? profileSalary[0].orgChild4 : null,
profileSalary.length > 0 && profileSalary[0].orgChild3 ? profileSalary[0].orgChild3 : null,
profileSalary.length > 0 && profileSalary[0].orgChild2 ? profileSalary[0].orgChild2 : null,
profileSalary.length > 0 && profileSalary[0].orgChild1 ? profileSalary[0].orgChild1 : null,
profileSalary.length > 0 && profileSalary[0].orgRoot ? profileSalary[0].orgRoot : null,
];
// _OrgLeave = [
// profileSalary.length > 0 && profileSalary[0].orgChild4 ? profileSalary[0].orgChild4 : null,
// profileSalary.length > 0 && profileSalary[0].orgChild3 ? profileSalary[0].orgChild3 : null,
// profileSalary.length > 0 && profileSalary[0].orgChild2 ? profileSalary[0].orgChild2 : null,
// profileSalary.length > 0 && profileSalary[0].orgChild1 ? profileSalary[0].orgChild1 : null,
// profileSalary.length > 0 && profileSalary[0].orgRoot ? profileSalary[0].orgRoot : null,
// ];
if (record.leaveType == "RETIRE") {
_profileSalary = profileSalary.length > 1
? profileSalary[1]
: profileSalary.length > 0
? profileSalary[0]
: null;
} else {
_profileSalary = profileSalary.length > 0
? profileSalary[0]
: null;
}
if (_profileSalary) {
_OrgLeave = [
_profileSalary.orgChild4 ?? null,
_profileSalary.orgChild3 ?? null,
_profileSalary.orgChild2 ?? null,
_profileSalary.orgChild1 ?? null,
_profileSalary.orgRoot ?? null,
];
} else {
_OrgLeave = [];
}
orgLeave = _OrgLeave.filter((x:any) => x !== undefined && x !== null).join("\n");
posNoLeave = profileSalary.length > 0
? `${profileSalary[0].posNoAbb} ${profileSalary[0].posNo}`
posNoLeave = _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: ""
}
const data = {

View file

@ -878,7 +878,7 @@ export class ProfileSalaryTempController extends Controller {
posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName,
employeeClass: _data.employeeClass == null ? null : _data.employeeClass,
govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0),
age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0, "GET"),
dateEmployment: dateEmployment,
dateAppoint: _data.dateAppoint,
dateStart: _data.dateStart,

View file

@ -470,15 +470,21 @@ export class KeycloakController extends Controller {
throw new Error("Failed. Cannot get user list.");
}*/
@Get("user")
@Post("user/admin")
async listUserKeycloak(
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query() keyword: string = "",
@Query() type: string = "",
@Request() req: RequestWithUser,
@Request() req: RequestWithUser,
@Body()
body:{
page: number,
pageSize: number,
keyword: string | null,
type: string,
isAll: boolean,
node: number | null,
nodeId: string | null,
}
) {
let condition: any = {};
let checkChildFromRole: any = {};
if (req.user.role.includes("ADMIN") && !req.user.role.includes("SUPER_ADMIN")) {
const profile = await this.profileRepo.findOne({
@ -493,109 +499,107 @@ export class KeycloakController extends Controller {
},
},
});
if (
profile?.current_holders[0]?.orgRootId &&
profile?.current_holders[0]?.orgChild1Id == null
) {
condition = `current_holders.orgRootId = '${profile?.current_holders[0]?.orgRootId}'
and current_holders.orgChild1Id IS NULL
and current_holders.orgChild2Id IS NULL
and current_holders.orgChild3Id IS NULL
and current_holders.orgChild4Id IS NULL`;
} else if (
profile?.current_holders[0]?.orgChild1Id &&
profile?.current_holders[0]?.orgChild2Id == null
) {
condition = `current_holders.orgRootId = '${profile?.current_holders[0]?.orgRootId}'
and current_holders.orgChild1Id = '${profile?.current_holders[0]?.orgChild1Id}'
and current_holders.orgChild2Id IS NULL
and current_holders.orgChild3Id IS NULL
and current_holders.orgChild4Id IS NULL`;
} else if (
profile?.current_holders[0]?.orgChild2Id &&
profile?.current_holders[0]?.orgChild3Id == null
) {
condition = `current_holders.orgRootId = '${profile?.current_holders[0]?.orgRootId}'
and current_holders.orgChild1Id = '${profile?.current_holders[0]?.orgChild1Id}'
and current_holders.orgChild2Id = '${profile?.current_holders[0]?.orgChild2Id}'
and current_holders.orgChild3Id IS NULL
and current_holders.orgChild4Id IS NULL`;
} else if (
profile?.current_holders[0]?.orgChild3Id &&
profile?.current_holders[0]?.orgChild4Id == null
) {
condition = `current_holders.orgRootId = '${profile?.current_holders[0]?.orgRootId}'
and current_holders.orgChild1Id = '${profile?.current_holders[0]?.orgChild1Id}'
and current_holders.orgChild2Id = '${profile?.current_holders[0]?.orgChild2Id}'
and current_holders.orgChild3Id = '${profile?.current_holders[0]?.orgChild3Id}'
and current_holders.orgChild4Id IS NULL`;
} else if (profile?.current_holders[0]?.orgChild4Id) {
condition = `current_holders.orgRootId = '${profile?.current_holders[0]?.orgRootId}'
and current_holders.orgChild1Id = '${profile?.current_holders[0]?.orgChild1Id}'
and current_holders.orgChild2Id = '${profile?.current_holders[0]?.orgChild2Id}'
and current_holders.orgChild3Id = '${profile?.current_holders[0]?.orgChild3Id}'
and current_holders.orgChild4Id = '${profile?.current_holders[0]?.orgChild4Id}'`;
//ADMIN เห็นทั้งหน่วยงานที่สังกัด
if (profile?.current_holders[0]?.orgRootId) {
checkChildFromRole = `current_holders.orgRootId = '${profile?.current_holders[0]?.orgRootId}'`;
}
}
let typeCondition = "";
let checkChildConditions = "";
let conditions:any = {};
if(body.nodeId !== null && body.nodeId !== "" && body.nodeId !== undefined){
if (body.node === 0) {
typeCondition = `current_holders.orgRootId = '${body.nodeId}'`;
if (!body.isAll) {
checkChildConditions = `and current_holders.orgChild1Id IS NULL`;
}
} else if (body.node === 1) {
typeCondition = `current_holders.orgChild1Id = '${body.nodeId}'`;
if (!body.isAll) {
checkChildConditions = `and current_holders.orgChild2Id IS NULL`;
}
} else if (body.node === 2) {
typeCondition = `current_holders.orgChild2Id = '${body.nodeId}'`;
if (!body.isAll) {
checkChildConditions = `and current_holders.orgChild3Id IS NULL`;
}
} else if (body.node === 3) {
typeCondition = `current_holders.orgChild3Id = '${body.nodeId}'`;
if (!body.isAll) {
checkChildConditions = `and current_holders.orgChild4Id IS NULL`;
}
} else if (body.node === 4) {
typeCondition = `current_holders.orgChild4Id = '${body.nodeId}'`;
}
conditions = typeCondition;
if(checkChildConditions){
conditions += checkChildConditions;
}
}
let profiles: any = [];
let total: any;
if (type.trim().toUpperCase() == "OFFICER") {
if (body.type.trim().toUpperCase() == "OFFICER") {
[profiles, total] = await this.profileRepo
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.roleKeycloaks", "roleKeycloaks")
.leftJoinAndSelect("profile.current_holders", "current_holders")
.where("profile.keycloak IS NOT NULL AND profile.keycloak != ''")
.andWhere(condition)
.andWhere(checkChildFromRole)
.andWhere(conditions)
.andWhere(
new Brackets((qb) => {
qb.orWhere(
keyword != null && keyword != "" ? `profile.citizenId like '%${keyword}%'` : "1=1",
body.keyword != null && body.keyword != "" ? `profile.citizenId like '%${body.keyword}%'` : "1=1",
)
.orWhere(
keyword != null && keyword != "" ? `profile.email like '%${keyword}%'` : "1=1",
body.keyword != null && body.keyword != "" ? `profile.email like '%${body.keyword}%'` : "1=1",
)
.orWhere(
keyword != null && keyword != ""
? `CONCAT(profile.prefix, profile.firstName," ",profile.lastName) like '%${keyword}%'`
body.keyword != null && body.keyword != ""
? `CONCAT(profile.prefix, profile.firstName," ",profile.lastName) like '%${body.keyword}%'`
: "1=1",
);
}),
)
.orderBy("profile.citizenId", "ASC")
.skip((page - 1) * pageSize)
.take(pageSize)
.skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
} else if (type.trim().toUpperCase() == "EMPLOYEE") {
} else if (body.type.trim().toUpperCase() == "EMPLOYEE") {
[profiles, total] = await this.profileEmpRepo
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.roleKeycloaks", "roleKeycloaks")
.leftJoinAndSelect("profileEmployee.current_holders", "current_holders")
.where("profileEmployee.keycloak IS NOT NULL AND profileEmployee.keycloak != ''")
.andWhere(condition)
.andWhere(checkChildFromRole)
.andWhere(conditions)
.andWhere({ employeeClass: "PERM" })
.andWhere(
new Brackets((qb) => {
qb.orWhere(
keyword != null && keyword != ""
? `profileEmployee.citizenId like '%${keyword}%'`
body.keyword != null && body.keyword != ""
? `profileEmployee.citizenId like '%${body.keyword}%'`
: "1=1",
)
.orWhere(
keyword != null && keyword != ""
? `profileEmployee.email like '%${keyword}%'`
body.keyword != null && body.keyword != ""
? `profileEmployee.email like '%${body.keyword}%'`
: "1=1",
)
.orWhere(
keyword != null && keyword != ""
? `CONCAT(profileEmployee.prefix, profileEmployee.firstName," ",profileEmployee.lastName) like '%${keyword}%'`
body.keyword != null && body.keyword != ""
? `CONCAT(profileEmployee.prefix, profileEmployee.firstName," ",profileEmployee.lastName) like '%${body.keyword}%'`
: "1=1",
);
}),
)
.orderBy("profileEmployee.citizenId", "ASC")
.skip((page - 1) * pageSize)
.take(pageSize)
.skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
}
@ -908,66 +912,82 @@ export class KeycloakController extends Controller {
) {
const profiles = await this.profileEmpRepo.find({
where: {
keycloak: IsNull(),
// keycloak: IsNull(),
isLeave: false,
},
order: { citizenId: "ASC" },
relations: ["roleKeycloaks"],
});
for await (const _item of profiles) {
let password = _item.citizenId;
if (_item.birthDate != null) {
// const gregorianYear = _item.birthDate.getFullYear() + 543;
// ดึงข้อมูลที่ใช้บ่อยก่อน (cache)
const rolesList = await getRoles();
if (!Array.isArray(rolesList))
throw new Error("Failed. Cannot get role(s) data from the server.");
// const formattedDate =
// _item.birthDate.toISOString().slice(8, 10) +
// _item.birthDate.toISOString().slice(5, 7) +
// gregorianYear;
// password = formattedDate;
const _date = new Date(_item.birthDate.toDateString())
.getDate()
.toString()
.padStart(2, "0");
const _month = (new Date(_item.birthDate.toDateString()).getMonth() + 1)
.toString()
.padStart(2, "0");
const _year = new Date(_item.birthDate.toDateString()).getFullYear() + 543;
password = `${_date}${_month}${_year}`;
}
const checkUser = await getUserByUsername(_item.citizenId);
let userId: any = "";
if (checkUser.length == 0) {
userId = await createUser(_item.citizenId, password, {
firstName: _item.firstName,
lastName: _item.lastName,
// email: _item.email,
});
if (typeof userId !== "string") {
throw new Error(userId.errorMessage);
}
} else {
userId = checkUser[0].id;
}
const roleKeycloak = await this.roleKeycloakRepo.find({
where: { id: "8a1a0dc9-304c-4e5b-a90a-65f841048212" },
});
const list = await getRoles();
if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server.");
const result = await addUserRoles(
userId,
list.filter((v) => v.id == "8a1a0dc9-304c-4e5b-a90a-65f841048212"),
// Process แบบ batch เพื่อลดการเรียก API ทีละตัว
const batchSize = 100;
const batches = [];
for (let i = 0; i < profiles.length; i += batchSize) {
batches.push(profiles.slice(i, i + batchSize));
}
for (const batch of batches) {
await Promise.all(
batch.map(async (_item) => {
let password = _item.citizenId;
if (_item.birthDate != null) {
const _date = new Date(_item.birthDate.toDateString())
.getDate()
.toString()
.padStart(2, "0");
const _month = (new Date(_item.birthDate.toDateString()).getMonth() + 1)
.toString()
.padStart(2, "0");
const _year = new Date(_item.birthDate.toDateString()).getFullYear() + 543;
password = `${_date}${_month}${_year}`;
}
try {
const checkUser = await getUserByUsername(_item.citizenId);
let userId: any = "";
if (checkUser.length == 0) {
userId = await createUser(_item.citizenId, password, {
firstName: _item.firstName,
lastName: _item.lastName,
});
if (typeof userId !== "string") {
console.error(`Failed to create user for ${_item.citizenId}:`, userId.errorMessage);
return;
}
} else {
userId = checkUser[0].id;
}
const result = await addUserRoles(
userId,
rolesList.filter((v) => v.id == "8a1a0dc9-304c-4e5b-a90a-65f841048212"),
);
if (!result) {
console.error(`Failed to set role for user ${_item.citizenId}`);
return;
}
if (typeof userId === "string") {
_item.keycloak = userId;
}
if (_item) {
_item.roleKeycloaks = Array.from(new Set([..._item.roleKeycloaks, ...roleKeycloak]));
await this.profileEmpRepo.save(_item);
}
} catch (error) {
console.error(`Error processing ${_item.citizenId}:`, error);
}
}),
);
if (!result) {
throw new Error("Failed. Cannot set user's role.");
}
if (typeof userId === "string") {
_item.keycloak = userId;
}
const roleKeycloak = await this.roleKeycloakRepo.find({
where: { id: "8a1a0dc9-304c-4e5b-a90a-65f841048212" },
});
if (_item) {
_item.roleKeycloaks = Array.from(new Set([..._item.roleKeycloaks, ...roleKeycloak]));
this.profileEmpRepo.save(_item);
}
}
return "";
}
@ -1079,4 +1099,83 @@ export class KeycloakController extends Controller {
}
return "";
}
@Post("add-role-staff/user-emp/{child1Id}")
@Security("bearerAuth", ["system", "admin"])
async addroleStaffToUserEmp(
@Path() child1Id: string,
@Request() request: { user: { sub: string; preferred_username: string } },
) {
const profiles = await this.profileEmpRepo.find({
where: {
keycloak: Not(IsNull()),
isLeave: false,
current_holders: {
orgChild1Id: child1Id,
},
},
relations: ["roleKeycloaks"],
});
// return profiles.length;
for await (const _item of profiles) {
let password = _item.citizenId;
if (_item.birthDate != null) {
const _date = new Date(_item.birthDate.toDateString())
.getDate()
.toString()
.padStart(2, "0");
const _month = (new Date(_item.birthDate.toDateString()).getMonth() + 1)
.toString()
.padStart(2, "0");
const _year = new Date(_item.birthDate.toDateString()).getFullYear() + 543;
password = `${_date}${_month}${_year}`;
}
const checkUser = await getUserByUsername(_item.citizenId);
let userId: any = "";
if (checkUser.length == 0) {
userId = await createUser(_item.citizenId, password, {
firstName: _item.firstName,
lastName: _item.lastName,
});
if (typeof userId !== "string") {
throw new Error(userId.errorMessage);
}
} else {
userId = checkUser[0].id;
}
const list = await getRoles();
if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server.");
const resultUser = await addUserRoles(
userId,
list.filter((v) => v.id == "8a1a0dc9-304c-4e5b-a90a-65f841048212"),
);
const resultStaff = await addUserRoles(
userId,
list.filter((v) => v.id == "f1fff8db-0795-47c1-9952-f3c18d5b6172"),
);
// if (!resultUser) {
// throw new Error("Failed. Cannot set user's role.");
// }
// if (!resultStaff) {
// throw new Error("Failed. Cannot set staff's role.");
// }
if (typeof userId === "string") {
_item.keycloak = userId;
}
const roleKeycloakUser = await this.roleKeycloakRepo.find({
where: { id: "8a1a0dc9-304c-4e5b-a90a-65f841048212" },
});
const roleKeycloakStaff = await this.roleKeycloakRepo.find({
where: { id: "f1fff8db-0795-47c1-9952-f3c18d5b6172" },
});
if (_item) {
_item.roleKeycloaks = Array.from(new Set([...roleKeycloakUser, ...roleKeycloakStaff]));
this.profileEmpRepo.save(_item);
}
}
return "";
}
}

View file

@ -55,29 +55,35 @@ export class WorkflowController extends Controller {
fullName?: string | null;
},
) {
// ขั้นที่ 1: ทำการค้นหา profile และ metaWorkflow แบบ parallel
const [userProfileOfficer, userProfileEmployee, metaWorkflow] = await Promise.all([
this.profileRepo.findOne({
where: { keycloak: req.user.sub },
select: ["id", "keycloak"],
}),
this.profileEmployeeRepo.findOne({
where: { keycloak: req.user.sub },
select: ["id", "keycloak"],
}),
this.metaWorkflowRepo.findOne({
where: {
sysName: body.sysName,
posLevelName: body.posLevelName,
posTypeName: body.posTypeName,
},
}),
]);
// กำหนด profile type และ profile
let profileType = "OFFICER";
let profile: any = await this.profileRepo.findOne({
where: {
keycloak: req.user.sub,
},
});
let profile: any = userProfileOfficer;
if (!profile) {
profileType = "EMPLOYEE";
profile = await this.profileEmployeeRepo.findOne({
where: {
keycloak: req.user.sub,
},
});
profile = userProfileEmployee;
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลผู้ใช้งาน");
}
const metaWorkflow = await this.metaWorkflowRepo.findOne({
where: {
sysName: body.sysName,
posLevelName: body.posLevelName,
posTypeName: body.posTypeName,
},
});
if (!metaWorkflow) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบกระบวนการนี้ได้");
const meta = {
@ -88,6 +94,8 @@ export class WorkflowController extends Controller {
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
// ขั้นที่ 2: สร้าง workflow และดึง metaState แบบ parallel
const workflow = new Workflow();
Object.assign(workflow, {
...metaWorkflow,
@ -97,117 +105,130 @@ export class WorkflowController extends Controller {
profileType: profileType,
system: body.sysName,
});
await this.workflowRepo.save(workflow);
const metaState = await this.metaStateRepo.find({
where: {
metaWorkflowId: metaWorkflow.id,
},
order: { order: "ASC" },
const [savedWorkflow, metaStates] = await Promise.all([
this.workflowRepo.save(workflow),
this.metaStateRepo.find({
where: { metaWorkflowId: metaWorkflow.id },
order: { order: "ASC" },
}),
]);
// ขั้นที่ 3: สร้าง states ทั้งหมดในครั้งเดียว
const statesToCreate = metaStates.map((item) => {
const state = new State();
Object.assign(state, { ...item, id: undefined, workflowId: savedWorkflow.id, ...meta });
return state;
});
await Promise.all(
metaState.map(async (item) => {
const state = new State();
Object.assign(state, { ...item, id: undefined, workflowId: workflow.id, ...meta });
await this.stateRepo.save(state);
if (state.order == 1) {
workflow.stateId = state.id;
await this.workflowRepo.save(workflow);
}
const metaStateOperator = await this.metaStateOperatorRepo.find({
where: {
metaStateId: item.id,
},
const savedStates = await this.stateRepo.save(statesToCreate);
// ขั้นที่ 4: อัปเดต workflow.stateId กับ state แรก
const firstState = savedStates.find((state) => state.order === 1);
if (firstState) {
savedWorkflow.stateId = firstState.id;
await this.workflowRepo.save(savedWorkflow);
}
// ขั้นที่ 5: ดึง metaStateOperators ทั้งหมดและสร้าง stateOperators
const metaStateIds = metaStates.map((item) => item.id);
const allMetaStateOperators = await this.metaStateOperatorRepo.find({
where: { metaStateId: In(metaStateIds) },
});
// สร้าง stateOperators ทั้งหมดในครั้งเดียว
const stateOperatorsToCreate: StateOperator[] = [];
allMetaStateOperators.forEach((metaStateOp) => {
const correspondingState = savedStates.find(
(state) =>
metaStates.find((metaState) => metaState.id === metaStateOp.metaStateId)?.order ===
state.order,
);
if (correspondingState) {
const stateOperator = new StateOperator();
Object.assign(stateOperator, {
...metaStateOp,
id: undefined,
stateId: correspondingState.id,
...meta,
});
await Promise.all(
metaStateOperator.map(async (item1) => {
const stateOperator = new StateOperator();
Object.assign(stateOperator, { ...item1, id: undefined, stateId: state.id, ...meta });
await this.stateOperatorRepo.save(stateOperator);
}),
);
}),
);
let num = 1;
const stateOperatorUser = new StateOperatorUser();
stateOperatorsToCreate.push(stateOperator);
}
});
await this.stateOperatorRepo.save(stateOperatorsToCreate);
// ขั้นที่ 6: สร้าง StateOperatorUsers แบบ bulk
const stateOperatorUsersToCreate: StateOperatorUser[] = [];
let orderNum = 1;
// เพิ่ม Owner ก่อน
if (profile) {
Object.assign(stateOperatorUser, {
profileId: profileType == "OFFICER" ? profile.id : null,
profileEmployeeId: profileType != "OFFICER" ? profile.id : null,
const ownerStateOperatorUser = new StateOperatorUser();
Object.assign(ownerStateOperatorUser, {
profileId: profileType === "OFFICER" ? profile.id : null,
profileEmployeeId: profileType !== "OFFICER" ? profile.id : null,
profileType: profileType,
operator: "Owner",
order: num,
workflowId: workflow.id,
order: orderNum,
workflowId: savedWorkflow.id,
...meta,
});
stateOperatorUsersToCreate.push(ownerStateOperatorUser);
}
await this.stateOperatorUserRepo.save(stateOperatorUser);
const profileOfficer = await this.posMasterRepo.find({
// ดึงข้อมูล profileOfficers และสร้าง StateOperatorUsers
const profileOfficers = await this.posMasterRepo.find({
where: {
posMasterAssigns: { assignId: body.sysName },
orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true },
current_holderId: Not(IsNull()), // เพิ่มเงื่อนไขนี้เพื่อกรองเฉพาะที่มี current_holder
},
relations: ["orgChild1"],
select: ["current_holderId", "orgChild1"], // เลือกเฉพาะ field ที่จำเป็น
});
await Promise.all(
profileOfficer.map(async (item, i) => {
if (item.current_holderId) {
num = num + 1;
if (item.orgChild1 == null || item.orgChild1.isOfficer == false) {
const stateOperatorUser = new StateOperatorUser();
Object.assign(stateOperatorUser, {
profileId: item.current_holderId,
operator: "Officer",
profileType: "OFFICER",
order: num,
workflowId: workflow.id,
...meta,
});
await this.stateOperatorUserRepo.save(stateOperatorUser);
} else {
const stateOperatorUser = new StateOperatorUser();
Object.assign(stateOperatorUser, {
profileId: item.current_holderId,
operator: "PersonnelOfficer",
profileType: "OFFICER",
order: num,
workflowId: workflow.id,
...meta,
});
await this.stateOperatorUserRepo.save(stateOperatorUser);
}
}
}),
// สร้าง StateOperatorUsers สำหรับ officers
profileOfficers.forEach((item) => {
if (item.current_holderId) {
orderNum += 1;
const isPersonnelOfficer = item.orgChild1?.isOfficer === true;
const officerStateOperatorUser = new StateOperatorUser();
Object.assign(officerStateOperatorUser, {
profileId: item.current_holderId,
operator: isPersonnelOfficer ? "PersonnelOfficer" : "Officer",
profileType: "OFFICER",
order: orderNum,
workflowId: savedWorkflow.id,
...meta,
});
stateOperatorUsersToCreate.push(officerStateOperatorUser);
}
});
// บันทึก StateOperatorUsers ทั้งหมดในครั้งเดียว
await this.stateOperatorUserRepo.save(stateOperatorUsersToCreate);
// ขั้นที่ 7: ส่ง notification (ใช้ข้อมูลที่มีอยู่แล้วแทนการ query ใหม่)
const firstStateOperators = stateOperatorsToCreate.filter((so) =>
savedStates.find((state) => state.id === so.stateId && state.order === 1),
);
const _workflow = await this.workflowRepo.findOne({
where: { id: workflow.id },
relations: ["stateOperatorUsers"],
});
if (!_workflow) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่สามารถดำเนินการกระบวนการนี้ได้");
const _state = await this.stateRepo.findOne({
where: {
id: _workflow.stateId,
},
relations: ["stateOperators"],
});
if (!_state) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลขั้นตอนการอนุมัติ");
let profileNow = _workflow.stateOperatorUsers
.filter((x) => _state.stateOperators.map((s) => s.operator).includes(x.operator))
.map((x) => ({
receiverUserId: x.profileType == "OFFICER" ? x.profileId : x.profileEmployeeId,
const notificationReceivers = stateOperatorUsersToCreate
.filter((user) => firstStateOperators.some((op) => op.operator === user.operator))
.map((user) => ({
receiverUserId: user.profileType === "OFFICER" ? user.profileId : user.profileEmployeeId,
notiLink: "",
}));
await new CallAPI()
// ส่ง notification แบบ fire-and-forget
new CallAPI()
.PostData(req, "/placement/noti/profiles", {
// subject: `รายการถูกส่ง`,
// body: `รายการถูกส่ง`,
subject: `แจ้ง${workflow.name}ของ ${body.fullName}`,
body: `แจ้ง${workflow.name}ของ ${body.fullName}`,
receiverUserIds: profileNow,
payload: "", //แนบไฟล์
subject: `แจ้ง${savedWorkflow.name}ของ ${body.fullName}`,
body: `แจ้ง${savedWorkflow.name}ของ ${body.fullName}`,
receiverUserIds: notificationReceivers,
payload: "",
isSendMail: true,
isSendInbox: true,
isSendNotification: true,
@ -809,8 +830,8 @@ export class WorkflowController extends Controller {
pageSize: number;
keycloakId?: string | null;
type?: string | null;
sortBy?: string | null,
descending?: boolean,
sortBy?: string | null;
descending?: boolean;
},
) {
const userKeycloak = body.keycloakId ?? request.user.sub;
@ -990,10 +1011,10 @@ export class WorkflowController extends Controller {
if (body.sortBy) {
queryBuilder = queryBuilder.orderBy(
`entity.${body.sortBy}`,
body.descending ? "DESC" : "ASC"
body.descending ? "DESC" : "ASC",
);
}
// 7. Execute พร้อมกัน - ใช้ Promise.all
const [data, total] = await Promise.all([
queryBuilder

View file

@ -309,11 +309,13 @@ class Extension {
return years;
}
public static CalculateAgeStrV2(date: Date, plusYear: number = 0, subtractYear: number = 0) {
public static CalculateAgeStrV2(date: Date, plusYear: number = 0, subtractYear: number = 0, method?:string) {
if (date == null || date == undefined) return "";
const currentDate = new Date();
if (date > currentDate) {
if (date > currentDate && method !== "GET") {
throw new Error("วันเกิดต้องไม่มากกว่าวันที่ปัจจุบัน");
}else if(date > currentDate && method === "GET"){
return ""
}
let years = currentDate.getFullYear() - date.getFullYear();

View file

@ -94,6 +94,15 @@ class CheckAuth {
child4: null,
privilege: "ROOT",
};
} else if (privilege == "PARENT") {
data = {
root: [x.orgRootId],
child1: null,
child2: null,
child3: null,
child4: null,
privilege: "PARENT",
};
} else if (privilege == "CHILD") {
data = {
root: node >= 0 ? [x.orgRootId] : null,

View file

@ -56,7 +56,7 @@ export async function getToken() {
if (data && data.access_token) {
token = data.access_token;
}
console.log(`token: ${token}`);
return token;
}
@ -360,11 +360,11 @@ export async function enableStatus(userId: string, status: boolean) {
*
* @returns user true if success, false otherwise.
*/
export async function deleteUser(userId: string) {
export async function deleteUser(userId: string, token?: string) {
const res = await fetch(`${KC_URL}/admin/realms/${KC_REALMS}/users/${userId}`, {
// prettier-ignore
headers: {
"authorization": `Bearer ${await getToken()}`,
"authorization": `Bearer ${token || await getToken()}`,
"content-type": `application/json`,
},
method: "DELETE",

View file

@ -0,0 +1,742 @@
import { AppDataSource } from "../database/data-source";
import { Profile } from "./../entities/Profile";
import { ProfileEmployee } from "../entities/ProfileEmployee";
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 { Brackets, Repository } from "typeorm";
import Extension from "../interfaces/extension";
import { RequestWithUser } from "../middlewares/user";
interface LeaveFilter {
page: number;
pageSize: number;
searchField?: "firstName" | "lastName" | "fullName" | "citizenId" | "position" | "posNo";
searchKeyword?: string;
posType?: string;
posLevel?: string;
isProbation?: boolean;
node?: number;
nodeId?: string;
isAll?: boolean;
retireType?: string;
sortBy?: string;
sort: "ASC" | "DESC";
_data: DataPermission;
}
interface DataPermission {
root: string | null;
child1: string | null;
child2: string | null;
child3: string | null;
child4: string | null;
privilege: string;
}
interface OrganizationCondition {
condition: string;
params: Record<string, any>;
}
interface NodeConfig {
repository: Repository<any>;
nameField: string;
condition: string;
isAllTrue: string;
paramKey: string;
parentIdField: string;
}
interface NodeParams {
[key: string]: string | null | undefined;
}
interface OrgParentName {
orgRootName: string | null;
orgChild1Name: string | null;
orgChild2Name: string | null;
orgChild3Name: string | null;
orgChild4Name: string | null;
}
export class ProfileLeaveService {
private profileEmployeeRepo: Repository<ProfileEmployee>;
private profileRepo: Repository<Profile>;
private orgRootRepository: Repository<OrgRoot>;
private child1Repository: Repository<OrgChild1>;
private child2Repository: Repository<OrgChild2>;
private child3Repository: Repository<OrgChild3>;
private child4Repository: Repository<OrgChild4>;
private readonly nodeConfigs: NodeConfig[];
constructor() {
this.profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee);
this.profileRepo = AppDataSource.getRepository(Profile);
this.orgRootRepository = AppDataSource.getRepository(OrgRoot);
this.child1Repository = AppDataSource.getRepository(OrgChild1);
this.child2Repository = AppDataSource.getRepository(OrgChild2);
this.child3Repository = AppDataSource.getRepository(OrgChild3);
this.child4Repository = AppDataSource.getRepository(OrgChild4);
this.nodeConfigs = [
{
repository: this.orgRootRepository,
nameField: "orgRootName",
condition: "profileSalary.orgRoot = :orgRoot",
isAllTrue: "profileSalary.orgChild1 IS NULL",
paramKey: "orgRoot",
parentIdField: "",
},
{
repository: this.child1Repository,
nameField: "orgChild1Name",
condition: "profileSalary.orgChild1 = :orgChild1",
isAllTrue: "profileSalary.orgChild2 IS NULL",
paramKey: "orgChild1",
parentIdField: "orgRootId",
},
{
repository: this.child2Repository,
nameField: "orgChild2Name",
condition: "profileSalary.orgChild2 = :orgChild2",
isAllTrue: "profileSalary.orgChild3 IS NULL",
paramKey: "orgChild2",
parentIdField: "orgChild1Id",
},
{
repository: this.child3Repository,
nameField: "orgChild3Name",
condition: "profileSalary.orgChild3 = :orgChild3",
isAllTrue: "profileSalary.orgChild4 IS NULL",
paramKey: "orgChild3",
parentIdField: "orgChild2Id",
},
{
repository: this.child4Repository,
nameField: "orgChild4Name",
condition: "profileSalary.orgChild4 = :orgChild4",
isAllTrue: "",
paramKey: "orgChild4",
parentIdField: "orgChild3Id",
},
];
}
/** สร้าง query สำหรับการค้นหาตามฟิลด์ต่างๆ */
buildSearchQuery(searchField?: string, type: string = "profile"): string {
switch (searchField) {
case "citizenId":
return `${type}.citizenId LIKE :keyword`;
case "position":
return `${type}.position LIKE :keyword`;
case "posNo":
return `
(CONCAT(profileSalary.posNoAbb, profileSalary.posNo) LIKE :keyword)
OR (CONCAT(profileSalary.posNoAbb, " ", profileSalary.posNo) LIKE :keyword)
OR (profileSalary.posNo LIKE :keyword)
`;
default:
return `CONCAT(${type}.prefix, ${type}.firstName, ' ', ${type}.lastName) LIKE :keyword`;
}
}
async findOrgNodeParentAll(node: number, nodeId: string): Promise<OrgParentName> {
const orgNames: OrgParentName = {
orgRootName: null,
orgChild1Name: null,
orgChild2Name: null,
orgChild3Name: null,
orgChild4Name: null,
};
if (!nodeId || node < 0 || node >= this.nodeConfigs.length) {
return orgNames;
}
let currentNode = node;
let currentNodeId = nodeId;
while (currentNode >= 0) {
const config = this.nodeConfigs[currentNode];
// Build select fields dynamically, excluding empty parentIdField
const selectFields = [config.nameField, "id"];
if (config.parentIdField && config.parentIdField.trim() !== "") {
selectFields.push(config.parentIdField);
}
const orgData = await config.repository.findOne({
where: { id: currentNodeId },
select: selectFields,
});
if (!orgData) {
break;
}
const orgName = orgData[config.nameField] || null;
if (orgName) {
orgNames[config.nameField as keyof OrgParentName] = orgName;
}
// Check if parentIdField exists and is not empty before accessing it
if (config.parentIdField && config.parentIdField.trim() !== "") {
currentNodeId = orgData[config.parentIdField];
currentNode -= 1;
} else {
// If no parent field (root level), break the loop
break;
}
}
return orgNames;
}
/** สร้างเงื่อนไขการค้นหาตาม node และ nodeId และเช็คกับ permission */
async buildNodeCondition(
node: number,
nodeId: string,
isAll?: boolean,
): Promise<OrganizationCondition> {
// Early return สำหรับ edge cases
if (!nodeId || node < 0 || node >= this.nodeConfigs.length) {
return { condition: "1=1", params: {} };
}
let nodeCondition = "";
let params: NodeParams = {};
const orgLists = await this.findOrgNodeParentAll(node, nodeId);
console.log("Org Hierarchy for Node Condition:", orgLists);
await Promise.all(
this.nodeConfigs.map(async (config, index) => {
if (index <= node) {
const orgName = orgLists[config.nameField as keyof OrgParentName] || null;
if (orgName) {
nodeCondition += index > 0 ? ` AND ${config.condition}` : config.condition;
nodeCondition += isAll === false && config.isAllTrue ? ` AND ${config.isAllTrue}` : "";
params[config.paramKey] = orgName;
}
}
}),
);
return {
condition: nodeCondition,
params,
};
}
async getOrgNameFromId(orgIds: {
root: string | null;
child1: string | null;
child2: string | null;
child3: string | null;
child4: string | null;
}): Promise<OrgParentName> {
const orgNames: OrgParentName = {
orgRootName: null,
orgChild1Name: null,
orgChild2Name: null,
orgChild3Name: null,
orgChild4Name: null,
};
if (orgIds.root) {
const rootName = await this.orgRootRepository.findOne({
where: { id: orgIds.root },
select: ["orgRootName"],
});
orgNames.orgRootName = rootName ? rootName.orgRootName : null;
}
if (orgIds.child1) {
const child1 = await this.child1Repository.findOne({
where: { id: orgIds.child1 },
select: ["orgChild1Name"],
});
orgNames.orgChild1Name = child1 ? child1.orgChild1Name : null;
}
if (orgIds.child2) {
const child2 = await this.child2Repository.findOne({
where: { id: orgIds.child2 },
select: ["orgChild2Name"],
});
orgNames.orgChild2Name = child2 ? child2.orgChild2Name : null;
}
if (orgIds.child3) {
const child3 = await this.child3Repository.findOne({
where: { id: orgIds.child3 },
select: ["orgChild3Name"],
});
orgNames.orgChild3Name = child3 ? child3.orgChild3Name : null;
}
if (orgIds.child4) {
const child4 = await this.child4Repository.findOne({
where: { id: orgIds.child4 },
select: ["orgChild4Name"],
});
orgNames.orgChild4Name = child4 ? child4.orgChild4Name : null;
}
return orgNames;
}
/** สร้างเงื่อนไขการค้นหาตาม node และ nodeId และเช็คกับ permission */
async buildPermissionCondition(
_data: DataPermission,
isAll?: boolean,
): Promise<OrganizationCondition> {
// Early return สำหรับ OWNER privilege
if (_data.privilege === "OWNER") {
return { condition: "1=1", params: {} };
}
// const nodeFields = ["root", "child1", "child2", "child3", "child4"] as const;
let nodeCondition = "";
let params: NodeParams = {};
const orgLists = await this.getOrgNameFromId({
root: _data.root,
child1: _data.child1,
child2: _data.child2,
child3: _data.child3,
child4: _data.child4,
});
// console.log("Org Hierarchy for Permission Condition:", orgLists);
// check orgLists has at least one non-null value
if (
!orgLists.orgRootName &&
!orgLists.orgChild1Name &&
!orgLists.orgChild2Name &&
!orgLists.orgChild3Name &&
!orgLists.orgChild4Name
) {
return { condition: "1=0", params: {} }; // no access
}
await Promise.all(
this.nodeConfigs.map(async (config, index) => {
const orgName = orgLists[config.nameField as keyof OrgParentName] || null;
if (orgName) {
nodeCondition += index > 0 ? ` AND ${config.condition}` : config.condition;
nodeCondition += isAll === false && config.isAllTrue ? ` AND ${config.isAllTrue}` : "";
params[config.paramKey] = orgName;
}
}),
);
return {
condition: nodeCondition,
params,
};
}
/** แปลงข้อมูลลูกจ้างก่อน response */
transformEmployeeData(employee: ProfileEmployee): any {
const dateEmployment =
employee.profileEmployeeEmployment?.length === 0 || !employee.profileEmployeeEmployment
? null
: employee.profileEmployeeEmployment.reduce((latest, current) => {
return latest.date > current.date ? latest : current;
}).date;
// ตรวจสอบว่า profileSalary มีข้อมูลหรือไม่
const salary =
employee.profileSalary && employee.profileSalary.length > 0
? employee.profileSalary[0]
: null;
const posNo =
salary?.posNoAbb && salary?.posNo
? `${salary.posNoAbb} ${salary.posNo}`
: salary?.posNo || "";
// สร้าง organization hierarchy - ใช้ข้อมูลจาก temp fields ถ้า salary ไม่มี
const org = salary
? [salary.orgChild4, salary.orgChild3, salary.orgChild2, salary.orgChild1, salary.orgRoot]
.filter(Boolean)
.join("\n")
: [
employee.child4Temp,
employee.child3Temp,
employee.child2Temp,
employee.child1Temp,
employee.rootTemp,
]
.filter(Boolean)
.join("\n");
// สร้าง node information
const getNodeInfo = (nodeTemp: string) => {
switch (nodeTemp) {
case "0":
return {
name: employee.rootTemp,
shortName: employee.rootShortNameTemp,
};
case "1":
return {
name: employee.child1Temp,
shortName: employee.child1ShortNameTemp,
};
case "2":
return {
name: employee.child2Temp,
shortName: employee.child2ShortNameTemp,
};
case "3":
return {
name: employee.child3Temp,
shortName: employee.child3ShortNameTemp,
};
case "4":
return {
name: employee.child4Temp,
shortName: employee.child4ShortNameTemp,
};
default:
return { name: null, shortName: null };
}
};
const nodeInfo = getNodeInfo(employee.nodeTemp || "0");
return {
id: employee.id,
avatar: employee.avatar,
avatarName: employee.avatarName,
prefix: employee.prefix,
rank: employee.rank,
firstName: employee.firstName,
lastName: employee.lastName,
citizenId: employee.citizenId,
posLevel: employee.posLevel?.posLevelName || null,
posType: employee.posType?.posTypeName || null,
posTypeShortName: employee.posType?.posTypeShortName || null,
posLevelId: employee.posLevel?.id || null,
posTypeId: employee.posType?.id || null,
positionId: employee.positionIdTemp,
posmasterId: employee.posmasterIdTemp,
position: employee.position,
posNo,
employeeClass: employee.employeeClass,
govAge: Extension.CalculateGovAge(employee.dateAppoint, 0, 0),
age: Extension.CalculateAgeStrV2(employee.birthDate, 0, 0, "GET"),
dateEmployment,
dateAppoint: employee.dateAppoint,
dateStart: employee.dateStart,
createdAt: employee.createdAt,
dateRetireLaw: employee.dateRetireLaw,
draftOrganizationOrganization: nodeInfo.name,
draftPositionEmployee: employee.positionTemp,
draftOrgEmployeeStatus: employee.statusTemp,
node: employee.nodeTemp,
nodeId: employee.nodeIdTemp,
nodeName: nodeInfo.name,
nodeShortName: nodeInfo.shortName,
root: employee.rootTemp || null,
rootId: employee.rootIdTemp || null,
rootShortName: employee.rootShortNameTemp || null,
child1: employee.child1Temp || null,
child1Id: employee.child1IdTemp || null,
child1ShortName: employee.child1ShortNameTemp || null,
child2: employee.child2Temp || null,
child2Id: employee.child2IdTemp || null,
child2ShortName: employee.child2ShortNameTemp || null,
child3: employee.child3Temp || null,
child3Id: employee.child3IdTemp || null,
child3ShortName: employee.child3ShortNameTemp || null,
child4: employee.child4Temp || null,
child4Id: employee.child4IdTemp || null,
child4ShortName: employee.child4ShortNameTemp || null,
org,
};
}
/** ค้นหาลูกจ้างที่พ้นจากราชการ */
async getLeaveEmployees(
request: RequestWithUser,
filter: LeaveFilter,
): Promise<{ data: any[]; total: number }> {
const {
page,
pageSize,
searchField,
searchKeyword = "",
posType,
posLevel,
isProbation,
node,
nodeId,
isAll,
retireType,
sortBy = "profileEmployee.dateLeave",
sort,
_data,
} = filter;
const searchQuery = this.buildSearchQuery(searchField, "profileEmployee");
// สร้าง main query - เปลี่ยนจาก leftJoinAndSelect เป็น leftJoin สำหรับ profileSalary
const queryBuilder = this.profileEmployeeRepo
.createQueryBuilder("profileEmployee")
.leftJoinAndSelect("profileEmployee.posLevel", "posLevel")
.leftJoinAndSelect("profileEmployee.posType", "posType")
.leftJoinAndSelect("profileEmployee.profileEmployeeEmployment", "profileEmployeeEmployment")
.leftJoin(
"profileEmployee.profileSalary",
"profileSalary",
"profileSalary.order = (SELECT MAX(ps.order) FROM profileSalary ps WHERE ps.profileEmployeeId = profileEmployee.id and ps.positionName != 'เกษียณอายุราชการ')",
)
.addSelect([
"profileSalary.id",
"profileSalary.order",
"profileSalary.posNo",
"profileSalary.posNoAbb",
"profileSalary.orgRoot",
"profileSalary.orgChild1",
"profileSalary.orgChild2",
"profileSalary.orgChild3",
"profileSalary.orgChild4",
])
.where(
new Brackets((qb) => {
qb.where("profileEmployee.isLeave = :isLeave", { isLeave: true }).orWhere(
"profileEmployee.isRetirement = :isRetirement",
{ isRetirement: true },
);
}),
)
.andWhere("profileEmployee.employeeClass LIKE :type", { type: "PERM" })
.andWhere(
new Brackets((qb) => {
qb.orWhere(searchKeyword && searchKeyword != "" ? searchQuery : "1=1", {
keyword: `%${searchKeyword}%`,
});
}),
);
// เพิ่มเงื่อนไขการค้นหา
if (posType) {
queryBuilder.andWhere("posType.posTypeName LIKE :keyword1", { keyword1: `${posType}` });
}
if (posLevel) {
queryBuilder.andWhere(
"CONCAT(posType.posTypeShortName, ' ', posLevel.posLevelName) LIKE :keyword2",
{ keyword2: `${posLevel}` },
);
}
if (isProbation) {
queryBuilder.andWhere(`profileEmployee.isProbation = ${isProbation}`);
}
if (retireType) {
queryBuilder.andWhere("profileEmployee.leaveType = :retireType", { retireType });
}
if (node !== null && node !== undefined && nodeId) {
const [nodeCondition, permissionCondition] = await Promise.all([
this.buildNodeCondition(node, nodeId, isAll),
this.buildPermissionCondition(_data, isAll),
]);
// console.log("Permission Condition:", permissionCondition);
// console.log("Node Condition:", nodeCondition);
queryBuilder.andWhere(nodeCondition.condition, nodeCondition.params);
if (_data.privilege !== "OWNER") {
queryBuilder.andWhere(permissionCondition.condition, permissionCondition.params);
}
}
// เพิ่ม sorting และ pagination
queryBuilder
.orderBy(sortBy, sort)
.skip((page - 1) * pageSize)
.take(pageSize);
const [records, total] = await queryBuilder.getManyAndCount();
// print query for debug
// console.log("SQL Query:", queryBuilder.getSql());
const data = await Promise.all(
records.map((record) => Promise.resolve(this.transformEmployeeData(record))),
);
return { data, total };
}
/**
* response
*/
transformOfficerData(employee: Profile) {
// ตรวจสอบว่า profileSalary มีข้อมูลหรือไม่
const salary =
employee.profileSalary && employee.profileSalary.length > 0
? employee.profileSalary[0]
: null;
const posNo =
salary?.posNoAbb && salary?.posNo
? `${salary.posNoAbb} ${salary.posNo}`
: salary?.posNo || "";
const posExecutive = salary?.positionExecutive ? salary.positionExecutive : null;
const root = salary?.orgRoot ? salary.orgRoot : null;
// สร้าง organization hierarchy - ใช้ข้อมูลจาก temp fields ถ้า salary ไม่มี
const org = salary
? [salary.orgChild4, salary.orgChild3, salary.orgChild2, salary.orgChild1, salary.orgRoot]
.filter(Boolean)
.join("\n")
: ["", "", "", "", ""].filter(Boolean).join("\n");
const orgRootShortName = salary?.posNoAbb ? salary.posNoAbb : null;
return {
id: employee.id,
avatar: employee.avatar,
avatarName: employee.avatarName,
dateAppoint: employee.dateAppoint,
prefix: employee.prefix,
rank: employee.rank,
firstName: employee.firstName,
lastName: employee.lastName,
citizenId: employee.citizenId,
posLevel: employee.posLevel?.posLevelName || null,
posType: employee.posType?.posTypeName || null,
posLevelId: employee.posLevel?.id || null,
posTypeId: employee.posType?.id || null,
position: employee.position,
posExecutive,
posNo,
rootId: null,
root,
orgRootShortName,
orgRevisionId: null,
org,
};
}
/**
*
*/
async getLeaveOfficer(
request: RequestWithUser,
filter: LeaveFilter,
): Promise<{ data: any[]; total: number }> {
const {
page,
pageSize,
searchField,
searchKeyword = "",
posType,
posLevel,
isProbation,
node,
nodeId,
isAll,
retireType,
sortBy = "profile.dateLeave",
sort,
_data,
} = filter;
const searchQuery = this.buildSearchQuery(searchField);
// สร้าง main query - เปลี่ยนจาก leftJoinAndSelect เป็น leftJoin สำหรับ profileSalary
const queryBuilder = this.profileRepo
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.posLevel", "posLevel")
.leftJoinAndSelect("profile.posType", "posType")
.leftJoin(
"profile.profileSalary",
"profileSalary",
"profileSalary.order = (SELECT MAX(ps.order) FROM profileSalary ps WHERE ps.profileId = profile.id and ps.positionName != 'เกษียณอายุราชการ')",
)
.addSelect([
"profileSalary.id",
"profileSalary.order",
"profileSalary.posNo",
"profileSalary.posNoAbb",
"profileSalary.orgRoot",
"profileSalary.orgChild1",
"profileSalary.orgChild2",
"profileSalary.orgChild3",
"profileSalary.orgChild4",
"profileSalary.positionExecutive",
])
.where(
new Brackets((qb) => {
qb.where("profile.isLeave = :isLeave", { isLeave: true }).orWhere(
"profile.isRetirement = :isRetirement",
{ isRetirement: true },
);
}),
)
.andWhere(
new Brackets((qb) => {
qb.orWhere(searchKeyword && searchKeyword != "" ? searchQuery : "1=1", {
keyword: `%${searchKeyword}%`,
});
}),
);
if (posType) {
queryBuilder.andWhere("posType.posTypeName LIKE :keyword1", { keyword1: `${posType}` });
}
if (posLevel) {
queryBuilder.andWhere("posLevel.posLevelName LIKE :keyword2", { keyword2: `${posLevel}` });
}
if (isProbation) {
queryBuilder.andWhere(`profile.isProbation = ${isProbation}`);
}
if (retireType) {
queryBuilder.andWhere("profile.leaveType = :retireType", { retireType });
}
// เพิ่ม permission และ node conditions
if (node !== null && node !== undefined && nodeId) {
// สร้าง query conditions แบบ parallel
const [nodeCondition, permissionCondition] = await Promise.all([
this.buildNodeCondition(node, nodeId, isAll),
this.buildPermissionCondition(_data, isAll),
]);
console.log("Permission Condition:", permissionCondition);
console.log("Node Condition:", nodeCondition);
queryBuilder.andWhere(nodeCondition.condition, nodeCondition.params);
if (_data.privilege !== "OWNER") {
queryBuilder.andWhere(permissionCondition.condition, permissionCondition.params);
}
}
// เพิ่ม sorting และ pagination
queryBuilder
.orderBy(sortBy, sort)
.skip((page - 1) * pageSize)
.take(pageSize);
const [records, total] = await queryBuilder.getManyAndCount();
// print query for debug
// console.log("SQL Query:", queryBuilder.getSql());
const data = await Promise.all(
records.map((record) => Promise.resolve(this.transformOfficerData(record))),
);
return { data, total };
}
}