diff --git a/src/app.ts b/src/app.ts index 1ed0839f..36df20ea 100644 --- a/src/app.ts +++ b/src/app.ts @@ -56,6 +56,16 @@ async function main() { console.error("Error executing function from controller:", error); } }); + + const cronTime_Oct = "0 0 1 10 *"; + cron.schedule(cronTime_Oct, async () => { + try { + const commandController = new CommandController(); + await commandController.cronjobUpdateRetirementStatus(); + } catch (error) { + console.error("Error executing function from controller:", error); + } + }); // app.listen(APP_PORT, APP_HOST, () => console.log(`Listening on: http://localhost:${APP_PORT}`)); app.listen( diff --git a/src/controllers/CommandController.ts b/src/controllers/CommandController.ts index d1afbb40..7d5d851c 100644 --- a/src/controllers/CommandController.ts +++ b/src/controllers/CommandController.ts @@ -53,7 +53,15 @@ import { PosMasterAct } from "../entities/PosMasterAct"; import { sendToQueue } from "../services/rabbitmq"; import { PosLevel } from "../entities/PosLevel"; import { PosType } from "../entities/PosType"; -import { addUserRoles, createUser, getRoles, deleteUser, enableStatus } from "../keycloak"; +import { + addUserRoles, + createUser, + getRoles, + deleteUser, + enableStatus, + getUserByUsername, + getRoleMappings, +} from "../keycloak"; import { ProfileEducation, CreateProfileEducation } from "../entities/ProfileEducation"; import { ProfileEducationHistory } from "../entities/ProfileEducationHistory"; import { CreateProfileCertificate, ProfileCertificate } from "../entities/ProfileCertificate"; @@ -452,6 +460,9 @@ export class CommandController extends Controller { amountSpecial: x.amountSpecial, positionSalaryAmount: x.positionSalaryAmount, mouthSalaryAmount: x.mouthSalaryAmount, + position: x.position, + posType: x.posType, + posLevel: x.posLevel, })), }; return new HttpSuccess(_command); @@ -870,10 +881,24 @@ export class CommandController extends Controller { @Request() request: RequestWithUser, ) { await new permission().PermissionUpdate(request, "COMMAND"); - const command = await this.commandRepository.findOne({ where: { id: id } }); + const command = await this.commandRepository.findOne({ + where: { id: id }, + relations: ["commandType", "commandRecives"], + }); if (!command) { throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้"); } + + const path = commandTypePath(command.commandType.code); + if (path == null) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ"); + await new CallAPI() + .PostData(request, path + "/delete", { + refIds: command.commandRecives.map((x) => x.refId), + }) + .then(async (res) => {}) + .catch(() => {}); + + await this.commandReciveRepository.delete({ commandId: command.id }); command.status = "CANCEL"; command.lastUpdateUserId = request.user.sub; command.lastUpdateFullName = request.user.name; @@ -1270,7 +1295,7 @@ export class CommandController extends Controller { // get admin token const response = await axios.post( - `${process.env.KC_URL}/realms/${process.env.KC_REALM}/protocol/openid-connect/token`, + `${process.env.KC_URL}/realms/${process.env.KC_REALMS}/protocol/openid-connect/token`, postData, { headers: { @@ -1304,6 +1329,93 @@ export class CommandController extends Controller { return new HttpSuccess(); } + async cronjobUpdateRetirementStatus() { + let body = { + client_id: "gettoken", + client_secret: process.env.AUTH_ACCOUNT_SECRET, + grant_type: "client_credentials", + }; + const postData = querystring.stringify(body); + const response = await axios.post( + `${process.env.KC_URL}/realms/${process.env.KC_REALMS}/protocol/openid-connect/token`, + postData, + { + headers: { + "Content-Type": "application/x-www-form-urlencoded", + api_key: process.env.API_KEY, + }, + }, + ); + const adminToken = response.data.access_token; + const today = new Date(); + today.setUTCHours(0, 0, 0, 0); + let type: string = "OFFICER" + try { + const response_ = await axios.get( + process.env.API_URL + `/retirement/update-status/${type}/${today.getFullYear()}`, + { + headers: { + Authorization: `Bearer ${adminToken}`, + "Content-Type": "application/json", + api_key: process.env.API_KEY, + }, + } + ); + if (response && response_.data.result.length > 0) { + let profiles: Profile[] = []; + await Promise.all( + response_.data.result.map(async (x:any) => { + const _profile = await this.profileRepository.findOneBy({ id: x.profileId }); + if (_profile) { + _profile.isRetirement = true; + _profile.isLeave = true; + _profile.leaveType = "RETIRE"; + _profile.leaveDate = new Date(); + _profile.dateLeave = new Date(); + _profile.lastUpdatedAt = new Date(); + profiles.push(_profile); + } + }) + ); + await this.profileRepository.save(profiles); + } + } catch {} + + type = "EMPLOYEE" + try { + const response_ = await axios.get( + process.env.API_URL + `/retirement/update-status/${type}/${today.getFullYear()}`, + { + headers: { + Authorization: `Bearer ${adminToken}`, + "Content-Type": "application/json", + api_key: process.env.API_KEY, + }, + } + ); + if (response && response_.data.result.length > 0) { + let profiles: ProfileEmployee[] = []; + await Promise.all( + response_.data.result.map(async (x:any) => { + const _profileEmp = await this.profileEmployeeRepository.findOneBy({ id: x.profileId }); + if (_profileEmp) { + _profileEmp.isRetirement = true; + _profileEmp.isLeave = true; + _profileEmp.leaveType = "RETIRE"; + _profileEmp.leaveDate = new Date(); + _profileEmp.dateLeave = new Date(); + _profileEmp.lastUpdatedAt = new Date(); + profiles.push(_profileEmp); + } + }) + ); + await this.profileEmployeeRepository.save(profiles); + } + } catch {} + + return new HttpSuccess(); + } + /** * API รายละเอียดรายการคำสั่ง tab4 คำสั่ง * @@ -1819,13 +1931,16 @@ export class CommandController extends Controller { amountSpecial?: Double | null; positionSalaryAmount?: Double | null; mouthSalaryAmount?: Double | null; + position?: string | null; + posType?: string | null; + posLevel?: string | null; }[]; }, @Request() request: RequestWithUser, ) { let command = new Command(); let commandCode: string = ""; - let null_: any = null; + let _null: any = null; if ( requestBody.commandId != undefined && requestBody.commandId != null && @@ -1867,10 +1982,10 @@ export class CommandController extends Controller { command.issue = commandType.name; (command.commandAffectDate = requestBody.commandAffectDate ? new Date(requestBody.commandAffectDate) - : null_), + : _null), (command.commandExcecuteDate = requestBody.commandExcecuteDate ? new Date(requestBody.commandExcecuteDate) - : null_), + : _null), (command.createdUserId = request.user.sub); command.createdFullName = request.user.name; command.createdAt = new Date(); @@ -1904,7 +2019,7 @@ export class CommandController extends Controller { let commandRecive = new CommandRecive(); commandRecive = Object.assign(new CommandRecive(), item); commandRecive.order = order; - let salaryData = null_; + let salaryData = _null; // const excludedCommands = ["C-PM-33", "C-PM-34", "C-PM-35", "C-PM-36", "C-PM-37"]; // if (!excludedCommands.includes(commandCode)) { @@ -1914,7 +2029,7 @@ export class CommandController extends Controller { id: item.profileId, }, }); - let null_: any = 0; + let _setZero: any = 0; if (!salaryData) { salaryData = await this.profileEmployeeRepository.findOne({ where: { @@ -1922,30 +2037,25 @@ export class CommandController extends Controller { }, }); } - commandRecive.amount = item.amount ?? (salaryData ? salaryData.amount : null_); + commandRecive.amount = item.amount ?? (salaryData ? salaryData.amount : _setZero); commandRecive.amountSpecial = - item.amountSpecial ?? (salaryData ? salaryData.amountSpecial : null_); + item.amountSpecial ?? (salaryData ? salaryData.amountSpecial : _setZero); commandRecive.positionSalaryAmount = - item.positionSalaryAmount ?? (salaryData ? salaryData.positionSalaryAmount : null_); + item.positionSalaryAmount ?? + (salaryData ? salaryData.positionSalaryAmount : _setZero); commandRecive.mouthSalaryAmount = - item.mouthSalaryAmount ?? (salaryData ? salaryData.mouthSalaryAmount : null_); + item.mouthSalaryAmount ?? (salaryData ? salaryData.mouthSalaryAmount : _setZero); } else { - commandRecive.amount = null_; - commandRecive.amountSpecial = null_; - commandRecive.positionSalaryAmount = null_; - commandRecive.mouthSalaryAmount = null_; + commandRecive.amount = _null; + commandRecive.amountSpecial = _null; + commandRecive.positionSalaryAmount = _null; + commandRecive.mouthSalaryAmount = _null; } - // } else { - // commandRecive.amount = item.amount ?? null_; - // commandRecive.amountSpecial = item.amountSpecial ?? null_; - // commandRecive.positionSalaryAmount = item.positionSalaryAmount ?? null_; - // commandRecive.mouthSalaryAmount = item.mouthSalaryAmount ?? null_; - // } commandRecive.remarkVertical = - item.remarkVertical == null ? null_ : item.remarkVertical; + item.remarkVertical == null ? _null : item.remarkVertical; commandRecive.remarkHorizontal = - item.remarkHorizontal == null ? null_ : item.remarkHorizontal; + item.remarkHorizontal == null ? _null : item.remarkHorizontal; commandRecive.order = order; commandRecive.commandId = command.id; commandRecive.createdUserId = request.user.sub; @@ -1959,129 +2069,70 @@ export class CommandController extends Controller { ); }) .catch(() => {}); - - if (requestBody.persons != undefined && requestBody.persons.length > 0) { - let posMaster: any; - if (["C-PM-36", "C-PM-37"].includes(commandCode)) { - posMaster = await this.employeePosMasterRepository.find({ - where: { - current_holderId: In(requestBody.persons.map((x) => x.profileId)), - orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, - }, - select: ["orgRootId"], - }); - } else { - var posMasterOfficer = await this.posMasterRepository.find({ - where: { - current_holderId: In(requestBody.persons.map((x) => x.profileId)), - orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, - }, - select: ["orgRootId"], - }); - var posMasterEmployee = await this.employeePosMasterRepository.find({ - where: { - current_holderId: In(requestBody.persons.map((x) => x.profileId)), - orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, - }, - select: ["orgRootId"], - }); - posMaster = [...posMasterOfficer, ...posMasterEmployee]; - } - - let _posMaster: any; - if (["C-PM-38", "C-PM-40"].includes(commandCode)) { - _posMaster = await this.posMasterRepository.find({ - where: { - orgRootId: In(posMaster.map((x: any) => x.orgRootId)), - orgChild1: IsNull(), - orgChild2: IsNull(), - orgChild3: IsNull(), - orgChild4: IsNull(), - orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, - isDirector: true, - current_holderId: Not(IsNull()), - }, - relations: ["current_holder", "orgRoot"], - }); - } else { - _posMaster = await this.posMasterRepository.find({ - where: { - orgRootId: In(posMaster.map((x: any) => x.orgRootId)), - orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, - isDirector: true, - current_holderId: Not(IsNull()), - }, - relations: ["current_holder", "orgRoot"], - }); - } - await Promise.all( - _posMaster.map(async (item: any) => { - const _commandSend = await this.commandSendRepository.findOne({ + if (!["C-PM-10"].includes(commandCode)) { + if (requestBody.persons != undefined && requestBody.persons.length > 0) { + let posMaster: any; + if (["C-PM-36", "C-PM-37"].includes(commandCode)) { + posMaster = await this.employeePosMasterRepository.find({ where: { - commandId: command.id, - profileId: item.current_holder.id, + current_holderId: In(requestBody.persons.map((x) => x.profileId)), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, }, + select: ["orgRootId"], }); - if (_commandSend) return; - let commandSend = new CommandSend(); - commandSend.citizenId = item.current_holder.citizenId; - commandSend.prefix = item.current_holder.prefix; - commandSend.firstName = item.current_holder.firstName; - commandSend.lastName = item.current_holder.lastName; - commandSend.position = item.current_holder.position; - commandSend.org = item.orgRoot.orgRootName; - commandSend.profileId = item.current_holder.id; - commandSend.commandId = command.id; - commandSend.createdUserId = request.user.sub; - commandSend.createdFullName = request.user.name; - commandSend.createdAt = new Date(); - commandSend.lastUpdateUserId = request.user.sub; - commandSend.lastUpdateFullName = request.user.name; - commandSend.lastUpdatedAt = new Date(); - await this.commandSendRepository.save(commandSend); - if (commandSend && commandSend.id) { - let _ccName = new Array("EMAIL", "INBOX"); - let _dataSendCC = new Array(); - for (let i = 0; i < _ccName.length; i++) { - _dataSendCC.push({ - commandSendId: commandSend.id, - name: _ccName[i], - createdUserId: request.user.sub, - createdFullName: request.user.name, - createdAt: new Date(), - lastUpdateUserId: request.user.sub, - lastUpdateFullName: request.user.name, - lastUpdatedAt: new Date(), - }); - } - await this.commandSendCCRepository.save(_dataSendCC); - } - }), - ); - - const _posMasterNext = await this.posMasterRepository.find({ - where: { - orgRootId: In( - requestBody.persons - .filter((x) => x.rootId != undefined && x.rootId != null && x.rootId != "") - .map((x) => x.rootId), - ), - orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, - isDirector: true, - current_holderId: Not(IsNull()), - }, - relations: ["current_holder", "orgRoot"], - }); - await Promise.all( - _posMasterNext.map(async (item) => { - const _commandSend = await this.commandSendRepository.findOne({ + } else { + var posMasterOfficer = await this.posMasterRepository.find({ where: { - commandId: command.id, - profileId: item.current_holder.id, + current_holderId: In(requestBody.persons.map((x) => x.profileId)), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, }, + select: ["orgRootId"], }); - // if (_commandSend) return; - if (!_commandSend) { + var posMasterEmployee = await this.employeePosMasterRepository.find({ + where: { + current_holderId: In(requestBody.persons.map((x) => x.profileId)), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + }, + select: ["orgRootId"], + }); + posMaster = [...posMasterOfficer, ...posMasterEmployee]; + } + + let _posMaster: any; + if (["C-PM-38", "C-PM-40"].includes(commandCode)) { + _posMaster = await this.posMasterRepository.find({ + where: { + orgRootId: In(posMaster.map((x: any) => x.orgRootId)), + orgChild1: IsNull(), + orgChild2: IsNull(), + orgChild3: IsNull(), + orgChild4: IsNull(), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + isDirector: true, + current_holderId: Not(IsNull()), + }, + relations: ["current_holder", "orgRoot"], + }); + } else { + _posMaster = await this.posMasterRepository.find({ + where: { + orgRootId: In(posMaster.map((x: any) => x.orgRootId)), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + isDirector: true, + current_holderId: Not(IsNull()), + }, + relations: ["current_holder", "orgRoot"], + }); + } + await Promise.all( + _posMaster.map(async (item: any) => { + const _commandSend = await this.commandSendRepository.findOne({ + where: { + commandId: command.id, + profileId: item.current_holder.id, + }, + }); + if (_commandSend) return; let commandSend = new CommandSend(); commandSend.citizenId = item.current_holder.citizenId; commandSend.prefix = item.current_holder.prefix; @@ -2115,42 +2166,40 @@ export class CommandController extends Controller { } await this.commandSendCCRepository.save(_dataSendCC); } - } - }), - ); + }), + ); - if (["C-PM-10"].includes(commandCode)) { + const _posMasterNext = await this.posMasterRepository.find({ + where: { + orgRootId: In( + requestBody.persons + .filter((x) => x.rootId != undefined && x.rootId != null && x.rootId != "") + .map((x) => x.rootId), + ), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + isDirector: true, + current_holderId: Not(IsNull()), + }, + relations: ["current_holder", "orgRoot"], + }); await Promise.all( - requestBody.persons.map(async (item: any) => { - const _posMasterDirector = await this.posMasterRepository.findOne({ - where: { - orgRootId: item.rootId, - orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, - current_holderId: item.profileId, - }, - relations: ["current_holder", "orgRoot", "positions"], - }); + _posMasterNext.map(async (item) => { const _commandSend = await this.commandSendRepository.findOne({ where: { commandId: command.id, - profileId: item.profileId ?? null_, + profileId: item.current_holder.id, }, }); + // if (_commandSend) return; if (!_commandSend) { let commandSend = new CommandSend(); - commandSend.citizenId = item.citizenId; - commandSend.prefix = item.prefix; - commandSend.firstName = item.firstName; - commandSend.lastName = item.lastName; - commandSend.position = - _posMasterDirector && _posMasterDirector.positions.length > 0 - ? _posMasterDirector.positions[0].positionName - : null_; - commandSend.org = - _posMasterDirector && _posMasterDirector.orgRoot - ? _posMasterDirector.orgRoot.orgRootName - : null_; - commandSend.profileId = item.profileId; + commandSend.citizenId = item.current_holder.citizenId; + commandSend.prefix = item.current_holder.prefix; + commandSend.firstName = item.current_holder.firstName; + commandSend.lastName = item.current_holder.lastName; + commandSend.position = item.current_holder.position; + commandSend.org = item.orgRoot.orgRootName; + commandSend.profileId = item.current_holder.id; commandSend.commandId = command.id; commandSend.createdUserId = request.user.sub; commandSend.createdFullName = request.user.name; @@ -2181,6 +2230,254 @@ export class CommandController extends Controller { ); } } + if (["C-PM-10"].includes(commandCode)) { + await Promise.all( + requestBody.persons.map(async (item: any) => { + const _posMasterDirector = await this.posMasterRepository.findOne({ + where: { + orgRootId: item.rootId, + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + current_holderId: item.profileId, + }, + relations: ["current_holder", "orgRoot", "positions"], + }); + const _commandSend = await this.commandSendRepository.findOne({ + where: { + commandId: command.id, + profileId: item.profileId ?? _null, + }, + }); + if (!_commandSend) { + let commandSend = new CommandSend(); + commandSend.citizenId = item.citizenId; + commandSend.prefix = item.prefix; + commandSend.firstName = item.firstName; + commandSend.lastName = item.lastName; + commandSend.position = _posMasterDirector?.current_holder.position ?? _null; + commandSend.org = + _posMasterDirector && _posMasterDirector.orgRoot + ? _posMasterDirector.orgRoot.orgRootName + : _null; + commandSend.profileId = item.profileId; + commandSend.commandId = command.id; + commandSend.createdUserId = request.user.sub; + commandSend.createdFullName = request.user.name; + commandSend.createdAt = new Date(); + commandSend.lastUpdateUserId = request.user.sub; + commandSend.lastUpdateFullName = request.user.name; + commandSend.lastUpdatedAt = new Date(); + await this.commandSendRepository.save(commandSend); + if (commandSend && commandSend.id) { + let _ccName = new Array("EMAIL", "INBOX"); + let _dataSendCC = new Array(); + for (let i = 0; i < _ccName.length; i++) { + _dataSendCC.push({ + commandSendId: commandSend.id, + name: _ccName[i], + createdUserId: request.user.sub, + createdFullName: request.user.name, + createdAt: new Date(), + lastUpdateUserId: request.user.sub, + lastUpdateFullName: request.user.name, + lastUpdatedAt: new Date(), + }); + } + await this.commandSendCCRepository.save(_dataSendCC); + } + } + }), + ); + } + + if ( + [ + "C-PM-01", + "C-PM-02", + "C-PM-03", + "C-PM-04", + "C-PM-05", + "C-PM-07", + "C-PM-08", + "C-PM-09", + "C-PM-13", + "C-PM-14", + "C-PM-15", + "C-PM-16", + "C-PM-21", + "C-PM-22", + "C-PM-24", + "C-PM-39", + ].includes(commandCode) + ) { + const _posMasterCommission = await this.posMasterRepository.findOne({ + where: { + orgRoot: { + isCommission: true, + }, + isDirector: true, + orgChild1: IsNull(), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + current_holderId: Not(IsNull()), + }, + relations: ["current_holder", "orgRoot", "positions"], + }); + let _commandSend = await this.commandSendRepository.findOne({ + where: { + commandId: command.id, + profileId: _posMasterCommission?.current_holder.id ?? _null, + }, + }); + if (!_commandSend && _posMasterCommission != null) { + let commandSend = new CommandSend(); + commandSend.citizenId = _posMasterCommission?.current_holder.citizenId ?? _null; + commandSend.prefix = _posMasterCommission?.current_holder.prefix ?? _null; + commandSend.firstName = _posMasterCommission?.current_holder.firstName ?? _null; + commandSend.lastName = _posMasterCommission?.current_holder.lastName ?? _null; + commandSend.position = _posMasterCommission?.current_holder.position ?? _null; + commandSend.org = + _posMasterCommission && _posMasterCommission.orgRoot + ? _posMasterCommission.orgRoot.orgRootName + : _null; + commandSend.profileId = _posMasterCommission?.current_holderId ?? _null; + commandSend.commandId = command.id; + commandSend.createdUserId = request.user.sub; + commandSend.createdFullName = request.user.name; + commandSend.createdAt = new Date(); + commandSend.lastUpdateUserId = request.user.sub; + commandSend.lastUpdateFullName = request.user.name; + commandSend.lastUpdatedAt = new Date(); + await this.commandSendRepository.save(commandSend); + if (commandSend && commandSend.id) { + let _ccName = new Array("EMAIL", "INBOX"); + let _dataSendCC = new Array(); + for (let i = 0; i < _ccName.length; i++) { + _dataSendCC.push({ + commandSendId: commandSend.id, + name: _ccName[i], + createdUserId: request.user.sub, + createdFullName: request.user.name, + createdAt: new Date(), + lastUpdateUserId: request.user.sub, + lastUpdateFullName: request.user.name, + lastUpdatedAt: new Date(), + }); + } + await this.commandSendCCRepository.save(_dataSendCC); + } + } + const _posMasterInformation = await this.posMasterRepository.findOne({ + where: { + orgChild1: { + isInformation: true, + }, + isDirector: true, + orgChild2: IsNull(), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + current_holderId: Not(IsNull()), + }, + relations: ["current_holder", "orgRoot", "positions"], + }); + _commandSend = await this.commandSendRepository.findOne({ + where: { + commandId: command.id, + profileId: _posMasterInformation?.current_holder.id ?? _null, + }, + }); + if (!_commandSend && _posMasterInformation != null) { + let commandSend = new CommandSend(); + commandSend.citizenId = _posMasterInformation?.current_holder.citizenId ?? _null; + commandSend.prefix = _posMasterInformation?.current_holder.prefix ?? _null; + commandSend.firstName = _posMasterInformation?.current_holder.firstName ?? _null; + commandSend.lastName = _posMasterInformation?.current_holder.lastName ?? _null; + commandSend.position = _posMasterInformation?.current_holder.position ?? _null; + commandSend.org = + _posMasterInformation && _posMasterInformation.orgRoot + ? _posMasterInformation.orgRoot.orgRootName + : _null; + commandSend.profileId = _posMasterInformation?.current_holderId ?? _null; + commandSend.commandId = command.id; + commandSend.createdUserId = request.user.sub; + commandSend.createdFullName = request.user.name; + commandSend.createdAt = new Date(); + commandSend.lastUpdateUserId = request.user.sub; + commandSend.lastUpdateFullName = request.user.name; + commandSend.lastUpdatedAt = new Date(); + await this.commandSendRepository.save(commandSend); + if (commandSend && commandSend.id) { + let _ccName = new Array("EMAIL", "INBOX"); + let _dataSendCC = new Array(); + for (let i = 0; i < _ccName.length; i++) { + _dataSendCC.push({ + commandSendId: commandSend.id, + name: _ccName[i], + createdUserId: request.user.sub, + createdFullName: request.user.name, + createdAt: new Date(), + lastUpdateUserId: request.user.sub, + lastUpdateFullName: request.user.name, + lastUpdatedAt: new Date(), + }); + } + await this.commandSendCCRepository.save(_dataSendCC); + } + } + const _posMasterOfficer = await this.posMasterRepository.findOne({ + where: { + orgChild1: { + isOfficer: true, + }, + isDirector: true, + orgChild2: IsNull(), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + current_holderId: Not(IsNull()), + }, + relations: ["current_holder", "orgRoot", "positions"], + }); + _commandSend = await this.commandSendRepository.findOne({ + where: { + commandId: command.id, + profileId: _posMasterOfficer?.current_holder.id ?? _null, + }, + }); + if (!_commandSend && _posMasterOfficer != null) { + let commandSend = new CommandSend(); + commandSend.citizenId = _posMasterOfficer?.current_holder.citizenId ?? _null; + commandSend.prefix = _posMasterOfficer?.current_holder.prefix ?? _null; + commandSend.firstName = _posMasterOfficer?.current_holder.firstName ?? _null; + commandSend.lastName = _posMasterOfficer?.current_holder.lastName ?? _null; + commandSend.position = _posMasterOfficer?.current_holder.position ?? _null; + commandSend.org = + _posMasterOfficer && _posMasterOfficer.orgRoot + ? _posMasterOfficer.orgRoot.orgRootName + : _null; + commandSend.profileId = _posMasterOfficer?.current_holderId ?? _null; + commandSend.commandId = command.id; + commandSend.createdUserId = request.user.sub; + commandSend.createdFullName = request.user.name; + commandSend.createdAt = new Date(); + commandSend.lastUpdateUserId = request.user.sub; + commandSend.lastUpdateFullName = request.user.name; + commandSend.lastUpdatedAt = new Date(); + await this.commandSendRepository.save(commandSend); + if (commandSend && commandSend.id) { + let _ccName = new Array("EMAIL", "INBOX"); + let _dataSendCC = new Array(); + for (let i = 0; i < _ccName.length; i++) { + _dataSendCC.push({ + commandSendId: commandSend.id, + name: _ccName[i], + createdUserId: request.user.sub, + createdFullName: request.user.name, + createdAt: new Date(), + lastUpdateUserId: request.user.sub, + lastUpdateFullName: request.user.name, + lastUpdatedAt: new Date(), + }); + } + await this.commandSendCCRepository.save(_dataSendCC); + } + } + } return new HttpSuccess(command.id); } @@ -2547,7 +2844,7 @@ export class CommandController extends Controller { await removeProfileInOrganize(profile.id, "OFFICER"); } const clearProfile = await checkCommandType(String(item.commandId)); - if (clearProfile) { + if (clearProfile.status) { if (profile.keycloak != null) { const delUserKeycloak = await deleteUser(profile.keycloak); if (delUserKeycloak) { @@ -2556,55 +2853,65 @@ export class CommandController extends Controller { profile.isActive = false; } } + profile.leaveCommandId = item.commandId ?? _null; + profile.leaveCommandNo = item.refCommandNo ?? _null; + profile.leaveRemark = clearProfile.leaveRemark ?? _null; + profile.leaveDate = item.date ?? _null; + profile.leaveType = clearProfile.LeaveType ?? _null; profile.position = _null; profile.posTypeId = _null; profile.posLevelId = _null; } - const returnWork = await checkReturnCommandType(String(item.commandId)); - //คำสั่งบรรจุกลับเข้ารับราชการ หรือ ผู้ออกไปรับราชการทหารกลับเข้ารับราชการ solutionเดิม ให้ enable user เปลี่ยนเป็นสร้าง user ใหม่เลยเพราะยังไงตอนถูกพักก็ถูกลบ user - if (returnWork && item.isGovernment) { + if (item.isGovernment == true) { + const returnWork = await checkReturnCommandType(String(item.commandId)); + if (returnWork) { + profile.leaveReason = _null; + profile.leaveCommandId = _null; + profile.leaveCommandNo = _null; + profile.leaveRemark = _null; + profile.leaveDate = _null; + profile.leaveType = _null; + } let userKeycloakId; - userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { - firstName: profile.firstName, - lastName: profile.lastName, - }); - // กรณี Keycloak ไม่ถูกลบ ให้ลบซ้ำอีกรอบแล้วสร้างใหม่ และหากยังไม่สามารถลบได้ให้แสดง Error - if ( - profile.keycloak != null && - userKeycloakId && - userKeycloakId.errorMessage === "User exists with same username" - ) { - const delUserKeycloak = await deleteUser(profile.keycloak); - if (delUserKeycloak) { - userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { - firstName: profile.firstName, - lastName: profile.lastName, - }); - } else { - throw new HttpError( - HttpStatus.BAD_REQUEST, - "พบข้อผิดพลาด ไม่สามารถจัดการผู้ใช้งานได้", + const checkUser = await getUserByUsername(profile.citizenId); + //ถ้ายังไม่มี user keycloak ให้สร้างใหม่ + if (checkUser.length == 0) { + userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { + firstName: profile.firstName, + lastName: profile.lastName, + }); + const list = await getRoles(); + let result = false; + if (Array.isArray(list) && userKeycloakId) { + result = await addUserRoles( + userKeycloakId, + list + .filter((v) => v.name === "USER") + .map((x) => ({ + id: x.id, + name: x.name, + })), ); } + profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : []; + profile.keycloak = + userKeycloakId && typeof userKeycloakId === "string" ? userKeycloakId : ""; } - const list = await getRoles(); - let result = false; - if (Array.isArray(list) && userKeycloakId) { - result = await addUserRoles( - userKeycloakId, - list - .filter((v) => v.name === "USER") - .map((x) => ({ - id: x.id, - name: x.name, - })), - ); + //ถ้ามีอยู่แล้วให้ใช้อันเดิม + else { + const rolesData = await getRoleMappings(checkUser[0].id); + if (rolesData) { + const _roleKeycloak = await this.roleKeycloakRepo.find({ + where: { name: In(rolesData.map((x: any) => x.name)) }, + }); + profile.roleKeycloaks = + _roleKeycloak && _roleKeycloak.length > 0 ? _roleKeycloak : []; + } + profile.keycloak = checkUser[0].id; } profile.amount = item.amount ?? _null; profile.amountSpecial = item.amountSpecial ?? _null; profile.isActive = true; - profile.keycloak = typeof userKeycloakId === "string" ? userKeycloakId : ""; - profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : []; } await this.profileRepository.save(profile); }), @@ -2622,6 +2929,7 @@ export class CommandController extends Controller { profileId: string; date?: Date | null; amount?: Double | null; + amountSpecial?: Double | null; positionSalaryAmount?: Double | null; mouthSalaryAmount?: Double | null; posNo: string | null; @@ -2643,6 +2951,9 @@ export class CommandController extends Controller { mpCee?: string | null; refCommandCode?: string | null; refCommandName?: string | null; + positionLine?: string | null; + positionPathSide?: string | null; + positionExecutive?: string | null; }[]; }, ) { @@ -2699,7 +3010,7 @@ export class CommandController extends Controller { await removeProfileInOrganize(profile.id, "EMPLOYEE"); } const clearProfile = await checkCommandType(String(item.commandId)); - if (clearProfile) { + if (clearProfile.status) { if (profile.keycloak != null) { const delUserKeycloak = await deleteUser(profile.keycloak); if (delUserKeycloak) { @@ -2708,6 +3019,11 @@ export class CommandController extends Controller { profile.isActive = false; } } + profile.leaveCommandId = item.commandId ?? _null; + profile.leaveCommandNo = item.refCommandNo ?? _null; + profile.leaveRemark = clearProfile.leaveRemark ?? _null; + profile.leaveDate = item.date ?? _null; + profile.leaveType = clearProfile.LeaveType ?? _null; profile.position = _null; profile.posTypeId = _null; profile.posLevelId = _null; @@ -2787,7 +3103,7 @@ export class CommandController extends Controller { } const clearProfile = await checkCommandType(String(item.commandId)); const _null: any = null; - if (clearProfile) { + if (clearProfile.status) { if (profile.keycloak != null) { const delUserKeycloak = await deleteUser(profile.keycloak); if (delUserKeycloak) { @@ -2796,6 +3112,11 @@ export class CommandController extends Controller { profile.isActive = false; } } + profile.leaveCommandId = item.commandId ?? _null; + profile.leaveCommandNo = item.refCommandNo ?? _null; + profile.leaveRemark = clearProfile.leaveRemark ?? _null; + profile.leaveDate = item.date ?? _null; + profile.leaveType = clearProfile.LeaveType ?? _null; profile.position = _null; profile.posTypeId = _null; profile.posLevelId = _null; @@ -2828,6 +3149,7 @@ export class CommandController extends Controller { profileId: string; date?: Date | null; amount?: Double | null; + amountSpecial?: Double | null; positionSalaryAmount?: Double | null; mouthSalaryAmount?: Double | null; posNo: string | null; @@ -2910,6 +3232,7 @@ export class CommandController extends Controller { unStigma?: string | null; commandId?: string | null; amount?: Double | null; + amountSpecial?: Double | null; positionSalaryAmount?: Double | null; mouthSalaryAmount?: Double | null; isGovernment?: boolean | null; @@ -2999,14 +3322,15 @@ export class CommandController extends Controller { refCommandNo: item.refCommandNo, templateDoc: item.salaryRef, position: profile.position, - positionType: profile.posType.posTypeName, - positionLevel: profile.posLevel.posLevelName, + positionType: profile?.posType?.posTypeName ?? null, + positionLevel: profile?.posLevel?.posLevelName ?? null, posNo: shortName ? shortName : null, positionLine: position?.positionField ?? null, positionPathSide: position?.positionArea ?? null, positionExecutive: position?.posExecutive?.posExecutiveName ?? null, amount: item.amount ? item.amount : null, positionSalaryAmount: item.positionSalaryAmount ? item.positionSalaryAmount : null, + amountSpecial: item.amountSpecial ? item.amountSpecial : null, mouthSalaryAmount: item.mouthSalaryAmount ? item.mouthSalaryAmount : null, order: profile.profileSalary.length >= 0 @@ -3075,23 +3399,20 @@ export class CommandController extends Controller { _profile.lastUpdateUserId = req.user.sub; _profile.lastUpdateFullName = req.user.name; _profile.lastUpdatedAt = new Date(); - const exceptClear = await checkExceptCommandType(String(item.commandId)); - if (item.isLeave == true && !exceptClear) { + if (item.isLeave == true) { await removeProfileInOrganize(_profile.id, "OFFICER"); - } - //คำสั่งพักราชการ หรือ ให้ออกจากราชการไว้ก่อน solutionเดิม ให้ disable user ไว้แต่ยังไม่ลบ เปลี่ยนเป็นลบ user ออกเลย - else if (item.isLeave == true && exceptClear && _profile.keycloak != null) { - // const enableActive = await enableStatus(_profile.keycloak, false); - // if (!enableActive) throw new Error("Failed. Cannot change enable status."); - const delUserKeycloak = await deleteUser(_profile.keycloak); - if (delUserKeycloak) { - _profile.keycloak = _null; - _profile.roleKeycloaks = []; - _profile.isActive = false; + const exceptClear = await checkExceptCommandType(String(item.commandId)); + if (exceptClear.status) { + _profile.leaveReason = item.leaveReason ?? _null; + _profile.leaveCommandId = item.commandId ?? _null; + _profile.leaveCommandNo = item.refCommandNo ?? _null; + _profile.leaveRemark = exceptClear.leaveRemark ?? _null; + _profile.leaveDate = item.date ?? _null; + _profile.leaveType = exceptClear.LeaveType ?? _null; } } const clearProfile = await checkCommandType(String(item.commandId)); - if (clearProfile) { + if (clearProfile.status) { if (_profile.keycloak != null) { const delUserKeycloak = await deleteUser(_profile.keycloak); if (delUserKeycloak) { @@ -3100,6 +3421,11 @@ export class CommandController extends Controller { _profile.isActive = false; } } + _profile.leaveCommandId = item.commandId ?? _null; + _profile.leaveCommandNo = item.refCommandNo ?? _null; + _profile.leaveRemark = clearProfile.leaveRemark ?? _null; + _profile.leaveDate = item.date ?? _null; + _profile.leaveType = clearProfile.LeaveType ?? _null; _profile.position = _null; _profile.posTypeId = _null; _profile.posLevelId = _null; @@ -3183,8 +3509,8 @@ export class CommandController extends Controller { refCommandNo: item.refCommandNo, templateDoc: item.salaryRef, position: profile.position, - positionType: profile.posType.posTypeName, - positionLevel: profile.posLevel.posLevelName, + positionType: profile?.posType?.posTypeName ?? null, + positionLevel: profile?.posLevel?.posLevelName ?? null, posNo: shortName ? shortName : null, // positionLine: position?.positionField ?? "-", // positionPathSide: position?.positionArea ?? "-", @@ -3264,23 +3590,20 @@ export class CommandController extends Controller { _profile.lastUpdateUserId = req.user.sub; _profile.lastUpdateFullName = req.user.name; _profile.lastUpdatedAt = new Date(); - const exceptClear = await checkExceptCommandType(String(item.commandId)); - if (item.isLeave == true && !exceptClear) { + if (item.isLeave == true) { await removeProfileInOrganize(_profile.id, "EMPLOYEE"); - } - //คำสั่งพักราชการ หรือ ให้ออกจากราชการไว้ก่อน solutionเดิม ให้ disable user ไว้แต่ยังไม่ลบ เปลี่ยนเป็นลบ user ออกเลย - else if (item.isLeave == true && exceptClear && _profile.keycloak != null) { - // const enableActive = await enableStatus(_profile.keycloak, false); - // if (!enableActive) throw new Error("Failed. Cannot change enable status."); - const delUserKeycloak = await deleteUser(_profile.keycloak); - if (delUserKeycloak) { - _profile.keycloak = _null; - _profile.roleKeycloaks = []; - _profile.isActive = false; + const exceptClear = await checkExceptCommandType(String(item.commandId)); + if (exceptClear.status) { + _profile.leaveReason = item.leaveReason ?? _null; + _profile.leaveCommandId = item.commandId ?? _null; + _profile.leaveCommandNo = item.refCommandNo ?? _null; + _profile.leaveRemark = exceptClear.leaveRemark ?? _null; + _profile.leaveDate = item.date ?? _null; + _profile.leaveType = exceptClear.LeaveType ?? _null; } } const clearProfile = await checkCommandType(String(item.commandId)); - if (clearProfile) { + if (clearProfile.status) { if (_profile.keycloak != null) { const delUserKeycloak = await deleteUser(_profile.keycloak); if (delUserKeycloak) { @@ -3289,6 +3612,11 @@ export class CommandController extends Controller { _profile.isActive = false; } } + _profile.leaveCommandId = item.commandId ?? _null; + _profile.leaveCommandNo = item.refCommandNo ?? _null; + _profile.leaveRemark = clearProfile.leaveRemark ?? _null; + _profile.leaveDate = item.date ?? _null; + _profile.leaveType = clearProfile.LeaveType ?? _null; _profile.position = _null; _profile.posTypeId = _null; _profile.posLevelId = _null; @@ -3320,6 +3648,7 @@ export class CommandController extends Controller { unStigma?: string | null; commandId?: string | null; amount?: Double | null; + amountSpecial?: Double | null; positionSalaryAmount?: Double | null; mouthSalaryAmount?: Double | null; isGovernment?: boolean | null; @@ -3406,13 +3735,14 @@ export class CommandController extends Controller { refCommandNo: item.refCommandNo, templateDoc: item.salaryRef, position: profile.position, - positionType: profile.posType.posTypeName, - positionLevel: profile.posLevel.posLevelName, + positionType: profile?.posType?.posTypeName ?? null, + positionLevel: profile?.posLevel?.posLevelName ?? null, posNo: shortName ? shortName : null, // positionLine: position?.positionField ?? "-", // positionPathSide: position?.positionArea ?? "-", // positionExecutive: position?.posExecutive?.posExecutiveName ?? "-", amount: item.amount ? item.amount : null, + amountSpecial: item.amountSpecial ? item.amountSpecial : null, positionSalaryAmount: item.positionSalaryAmount ? item.positionSalaryAmount : null, mouthSalaryAmount: item.mouthSalaryAmount ? item.mouthSalaryAmount : null, order: @@ -3487,23 +3817,20 @@ export class CommandController extends Controller { _profile.lastUpdateUserId = req.user.sub; _profile.lastUpdateFullName = req.user.name; _profile.lastUpdatedAt = new Date(); - const exceptClear = await checkExceptCommandType(String(item.commandId)); - if (item.isLeave == true && !exceptClear) { + if (item.isLeave == true) { await removeProfileInOrganize(_profile.id, "EMPLOYEE"); - } - //คำสั่งพักราชการ หรือ ให้ออกจากราชการไว้ก่อน solutionเดิม ให้ disable user ไว้แต่ยังไม่ลบ เปลี่ยนเป็นลบ user ออกเลย - else if (item.isLeave == true && exceptClear && _profile.keycloak != null) { - // const enableActive = await enableStatus(_profile.keycloak, false); - // if (!enableActive) throw new Error("Failed. Cannot change enable status."); - const delUserKeycloak = await deleteUser(_profile.keycloak); - if (delUserKeycloak) { - _profile.keycloak = _null; - _profile.roleKeycloaks = []; - _profile.isActive = false; + const exceptClear = await checkExceptCommandType(String(item.commandId)); + if (exceptClear.status) { + _profile.leaveReason = item.leaveReason ?? _null; + _profile.leaveCommandId = item.commandId ?? _null; + _profile.leaveCommandNo = item.refCommandNo ?? _null; + _profile.leaveRemark = exceptClear.leaveRemark ?? _null; + _profile.leaveDate = item.date ?? _null; + _profile.leaveType = exceptClear.LeaveType ?? _null; } } const clearProfile = await checkCommandType(String(item.commandId)); - if (clearProfile) { + if (clearProfile.status) { if (_profile.keycloak != null) { const delUserKeycloak = await deleteUser(_profile.keycloak); if (delUserKeycloak) { @@ -3512,6 +3839,11 @@ export class CommandController extends Controller { _profile.isActive = false; } } + _profile.leaveCommandId = item.commandId ?? _null; + _profile.leaveCommandNo = item.refCommandNo ?? _null; + _profile.leaveRemark = clearProfile.leaveRemark ?? _null; + _profile.leaveDate = item.date ?? _null; + _profile.leaveType = clearProfile.LeaveType ?? _null; _profile.position = _null; _profile.posTypeId = _null; _profile.posLevelId = _null; @@ -3536,6 +3868,7 @@ export class CommandController extends Controller { salaryRef?: string | null; commandId?: string | null; amount?: Double | null; + amountSpecial?: Double | null; positionSalaryAmount?: Double | null; mouthSalaryAmount?: Double | null; mpCee?: string | null; @@ -3622,13 +3955,14 @@ export class CommandController extends Controller { templateDoc: item.salaryRef, commandId: item.commandId, position: profile.position, - positionType: profile.posType.posTypeName, - positionLevel: profile.posLevel.posLevelName, + positionType: profile?.posType?.posTypeName ?? null, + positionLevel: profile?.posLevel?.posLevelName ?? null, posNo: shortName ? shortName : null, positionLine: position?.positionField ?? null, positionPathSide: position?.positionArea ?? null, positionExecutive: position?.posExecutive?.posExecutiveName ?? null, amount: item.amount ? item.amount : null, + amountSpecial: item.amountSpecial ? item.amountSpecial : null, positionSalaryAmount: item.positionSalaryAmount ? item.positionSalaryAmount : null, mouthSalaryAmount: item.mouthSalaryAmount ? item.mouthSalaryAmount : null, order: @@ -3690,6 +4024,7 @@ export class CommandController extends Controller { salaryRef?: string | null; commandId?: string | null; amount?: Double | null; + amountSpecial?: Double | null; positionSalaryAmount?: Double | null; mouthSalaryAmount?: Double | null; isGovernment?: boolean | null; @@ -3791,13 +4126,14 @@ export class CommandController extends Controller { templateDoc: item.salaryRef, commandId: item.commandId, position: profile.position, - positionType: profile.posType.posTypeName, - positionLevel: profile.posLevel.posLevelName, + positionType: profile?.posType?.posTypeName ?? null, + positionLevel: profile?.posLevel?.posLevelName ?? null, posNo: shortName, positionLine: position?.positionField ?? null, positionPathSide: position?.positionArea ?? null, positionExecutive: position?.posExecutive?.posExecutiveName ?? null, amount: item.amount ? item.amount : null, + amountSpecial: item.amountSpecial ? item.amountSpecial : null, positionSalaryAmount: item.positionSalaryAmount ? item.positionSalaryAmount : null, mouthSalaryAmount: item.mouthSalaryAmount ? item.mouthSalaryAmount : null, order: @@ -3826,7 +4162,7 @@ export class CommandController extends Controller { await removeProfileInOrganize(profile.id, "OFFICER"); const clearProfile = await checkCommandType(String(item.commandId)); const _null: any = null; - if (clearProfile) { + if (clearProfile.status) { if (_profile.keycloak != null) { const delUserKeycloak = await deleteUser(_profile.keycloak); if (delUserKeycloak) { @@ -3835,6 +4171,11 @@ export class CommandController extends Controller { _profile.isActive = false; } } + _profile.leaveCommandId = item.commandId ?? _null; + _profile.leaveCommandNo = item.refCommandNo ?? _null; + _profile.leaveRemark = clearProfile.leaveRemark ?? _null; + _profile.leaveDate = item.date ?? _null; + _profile.leaveType = clearProfile.LeaveType ?? _null; _profile.position = _null; _profile.posTypeId = _null; _profile.posLevelId = _null; @@ -3873,7 +4214,7 @@ export class CommandController extends Controller { const roleKeycloak = await this.roleKeycloakRepo.findOne({ where: { name: Like("USER") }, }); - const null_: any = null; + const _null: any = null; await Promise.all( body.data.map(async (item) => { const before = null; @@ -3916,63 +4257,76 @@ export class CommandController extends Controller { item.bodyProfile.birthDate == null ? _null : calculateRetireLaw(item.bodyProfile.birthDate); - const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { - firstName: profile.firstName, - lastName: profile.lastName, - }); - // if (typeof userKeycloakId !== "string") { - // throw new Error(userKeycloakId.errorMessage); - // } - const list = await getRoles(); - if (!Array.isArray(list)) - throw new Error("Failed. Cannot get role(s) data from the server."); - const result = await addUserRoles( - userKeycloakId, - list - .filter((v) => v.name === "USER") - .map((x) => ({ - id: x.id, - name: x.name, - })), - ); - // if (!result) throw new Error("Failed. Cannot set user's role."); + + const checkUser = await getUserByUsername(profile.citizenId); + if (checkUser.length == 0) { + const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { + firstName: profile.firstName, + lastName: profile.lastName, + }); + const list = await getRoles(); + if (!Array.isArray(list)) + throw new Error("Failed. Cannot get role(s) data from the server."); + const result = await addUserRoles( + userKeycloakId, + list + .filter((v) => v.name === "USER") + .map((x) => ({ + id: x.id, + name: x.name, + })), + ); + profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : []; + profile.keycloak = + userKeycloakId && typeof userKeycloakId === "string" ? userKeycloakId : ""; + } else { + const rolesData = await getRoleMappings(checkUser[0].id); + if (rolesData) { + const _roleKeycloak = await this.roleKeycloakRepo.find({ + where: { name: In(rolesData.map((x: any) => x.name)) }, + }); + profile.roleKeycloaks = + _roleKeycloak && _roleKeycloak.length > 0 ? _roleKeycloak : []; + } + profile.keycloak = checkUser[0].id; + } + let registrationProvinceId = await this.provinceRepo.findOneBy({ id: profile.registrationProvinceId, }); profile.registrationProvinceId = registrationProvinceId ? registrationProvinceId.id - : null_; + : _null; let registrationDistrictId = await this.districtRepo.findOneBy({ id: profile.registrationDistrictId, }); profile.registrationDistrictId = registrationDistrictId ? registrationDistrictId.id - : null_; + : _null; let registrationSubDistrictId = await this.subDistrictRepo.findOneBy({ id: profile.registrationSubDistrictId, }); profile.registrationSubDistrictId = registrationSubDistrictId ? registrationSubDistrictId.id - : null_; + : _null; let currentProvinceId = await this.provinceRepo.findOneBy({ id: profile.currentProvinceId, }); - profile.currentProvinceId = currentProvinceId ? currentProvinceId.id : null_; + profile.currentProvinceId = currentProvinceId ? currentProvinceId.id : _null; let currentDistrictId = await this.districtRepo.findOneBy({ id: profile.currentDistrictId, }); - profile.currentDistrictId = currentDistrictId ? currentDistrictId.id : null_; + profile.currentDistrictId = currentDistrictId ? currentDistrictId.id : _null; let currentSubDistrictId = await this.subDistrictRepo.findOneBy({ id: profile.currentSubDistrictId, }); - profile.currentSubDistrictId = currentSubDistrictId ? currentSubDistrictId.id : null_; - profile.keycloak = typeof userKeycloakId === "string" ? userKeycloakId : ""; - profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : []; + profile.currentSubDistrictId = currentSubDistrictId ? currentSubDistrictId.id : _null; profile.email = item.bodyProfile.email; profile.dateStart = item.bodyProfile.dateStart; profile.amount = item.bodyProfile.amount ?? null; profile.amountSpecial = item.bodyProfile.amountSpecial ?? null; + profile.isProbation = item.bodyProfile.isProbation; await this.profileRepository.save(profile); setLogDataDiff(req, { before, after: profile }); } @@ -4304,30 +4658,44 @@ export class CommandController extends Controller { if (positionNew != null) { // Create Keycloak - const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { - firstName: profile.firstName, - lastName: profile.lastName, - // email: profile.email, - }); - // if (typeof userKeycloakId !== "string") { - // throw new Error(userKeycloakId.errorMessage); - // } - const list = await getRoles(); - if (!Array.isArray(list)) - throw new Error("Failed. Cannot get role(s) data from the server."); - const result = await addUserRoles( - userKeycloakId, - list - .filter((v) => v.name === "USER") - .map((x) => ({ - id: x.id, - name: x.name, - })), - ); - // if (!result) throw new Error("Failed. Cannot set user's role."); - profile.keycloak = typeof userKeycloakId == "string" ? userKeycloakId : ""; - profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : []; - // End Create Keycloak + const checkUser = await getUserByUsername(profile.citizenId); + if (checkUser.length == 0) { + const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { + firstName: profile.firstName, + lastName: profile.lastName, + // email: profile.email, + }); + // if (typeof userKeycloakId !== "string") { + // throw new Error(userKeycloakId.errorMessage); + // } + const list = await getRoles(); + if (!Array.isArray(list)) + throw new Error("Failed. Cannot get role(s) data from the server."); + const result = await addUserRoles( + userKeycloakId, + list + .filter((v) => v.name === "USER") + .map((x) => ({ + id: x.id, + name: x.name, + })), + ); + // if (!result) throw new Error("Failed. Cannot set user's role."); + profile.keycloak = + userKeycloakId && typeof userKeycloakId == "string" ? userKeycloakId : ""; + profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : []; + // End Create Keycloak + } else { + const rolesData = await getRoleMappings(checkUser[0].id); + if (rolesData) { + const _roleKeycloak = await this.roleKeycloakRepo.find({ + where: { name: In(rolesData.map((x: any) => x.name)) }, + }); + profile.roleKeycloaks = + _roleKeycloak && _roleKeycloak.length > 0 ? _roleKeycloak : []; + } + profile.keycloak = checkUser[0].id; + } positionNew.positionIsSelected = true; profile.posLevelId = positionNew.posLevelId; @@ -4432,6 +4800,7 @@ export class CommandController extends Controller { FirstName?: any | null; LastName?: any | null; Amount?: any | null; + amountSpecial?: Double | null; PositionSalaryAmount?: any | null; MouthSalaryAmount?: any | null; RemarkHorizontal?: any | null; @@ -4480,7 +4849,7 @@ export class CommandController extends Controller { ]; const _organization = organization .filter((part) => part !== undefined && part !== null) - .join("/"); + .join(" "); const organizationNew = [ posMasterAct.posMaster?.current_holder?.position ?? null, @@ -4492,7 +4861,7 @@ export class CommandController extends Controller { ]; const _organizationNew = organizationNew .filter((part) => part !== undefined && part !== null) - .join("/"); + .join(" "); var _data = { no: Extension.ToThaiNumber((i + 1).toString()), fullName: `${item.Prefix ?? ""}${item.FirstName ?? ""} ${item.LastName ?? ""}`, @@ -4500,8 +4869,8 @@ export class CommandController extends Controller { /*(posMasterAct.posMasterChild?.current_holder?.position ?? "-") + "/" +*/ _organization ?? "-", - postype: posMasterAct.posMasterChild?.current_holder?.posType?.posTypeName ?? "-", - poslevel: posMasterAct.posMasterChild?.current_holder?.posLevel?.posLevelName ?? "-", + postype: posMasterAct?.posMasterChild?.current_holder?.posType?.posTypeName ?? "-", + poslevel: posMasterAct?.posMasterChild?.current_holder?.posLevel?.posLevelName ?? "-", organizationNew: /*(posMasterAct.posMaster?.current_holder?.position ?? "-") + "/" +*/ @@ -4609,8 +4978,8 @@ export class CommandController extends Controller { mouthSalaryAmount: item.mouthSalaryAmount, posNo: shortName ?? null, position: position?.positionName ?? null, - positionType: position?.posType.posTypeName ?? null, - positionLevel: position?.posLevel.posLevelName ?? null, + positionType: position?.posType?.posTypeName ?? null, + positionLevel: position?.posLevel?.posLevelName ?? null, refCommandNo: `${item.commandNo}/${Extension.ToThaiYear(item.commandYear)}`, templateDoc: item.templateDoc, order: dest_item == null ? 1 : dest_item.order + 1, diff --git a/src/controllers/InsigniaTypeController.ts b/src/controllers/InsigniaTypeController.ts index f3c6d076..b5379eee 100644 --- a/src/controllers/InsigniaTypeController.ts +++ b/src/controllers/InsigniaTypeController.ts @@ -144,9 +144,9 @@ export class InsigniaTypeController extends Controller { @Get("active") async GetInsigniaType_Active() { const insigniaType_Active = await this.insigniaTypeRepository.find({ - select: ["id", "name", "createdAt", "lastUpdatedAt", "lastUpdateFullName", "isActive"], - where: { isActive: true }, - order: { name: "ASC" }, + where: { isActive: true, insignias: { isActive: true } }, + order: { name: "ASC", insignias: { level: "ASC" } }, + relations: ["insignias"], }); return new HttpSuccess(insigniaType_Active); } diff --git a/src/controllers/OrganizationController.ts b/src/controllers/OrganizationController.ts index 0cee1ae4..edb35874 100644 --- a/src/controllers/OrganizationController.ts +++ b/src/controllers/OrganizationController.ts @@ -5625,6 +5625,7 @@ export class OrganizationController extends Controller { } return new HttpSuccess({ rootId: data.id, + rootDnaId: data.ancestorDNA, root: data.orgRootName, rootShortName: data.orgRootShortName, }); @@ -5641,9 +5642,11 @@ export class OrganizationController extends Controller { } return new HttpSuccess({ rootId: data.orgRootId, + rootDnaId: data.ancestorDNA, root: data.orgRoot == null ? null : data.orgRoot.orgRootName, rootShortName: data.orgRoot == null ? null : data.orgRoot.orgRootShortName, child1Id: data.id, + child1DnaId: data.ancestorDNA, child1: data.orgChild1Name, child1ShortName: data.orgChild1ShortName, }); @@ -5661,12 +5664,15 @@ export class OrganizationController extends Controller { } return new HttpSuccess({ rootId: data.orgRootId, + rootDnaId: data.ancestorDNA, root: data.orgRoot == null ? null : data.orgRoot.orgRootName, rootShortName: data.orgRoot == null ? null : data.orgRoot.orgRootShortName, child1Id: data.orgChild1Id, + child1DnaId: data.ancestorDNA, child1: data.orgChild1 == null ? null : data.orgChild1.orgChild1Name, child1ShortName: data.orgChild1 == null ? null : data.orgChild1.orgChild1ShortName, child2Id: data.id, + child2DnaId: data.ancestorDNA, child2: data.orgChild2Name, child2ShortName: data.orgChild2ShortName, }); @@ -5685,15 +5691,19 @@ export class OrganizationController extends Controller { } return new HttpSuccess({ rootId: data.orgRootId, + rootDnaId: data.ancestorDNA, root: data.orgRoot == null ? null : data.orgRoot.orgRootName, rootShortName: data.orgRoot == null ? null : data.orgRoot.orgRootShortName, child1Id: data.orgChild1Id, + child1DnaId: data.ancestorDNA, child1: data.orgChild1 == null ? null : data.orgChild1.orgChild1Name, child1ShortName: data.orgChild1 == null ? null : data.orgChild1.orgChild1ShortName, child2Id: data.orgChild2Id, + child2DnaId: data.ancestorDNA, child2: data.orgChild2 == null ? null : data.orgChild2.orgChild2Name, child2ShortName: data.orgChild2 == null ? null : data.orgChild2.orgChild2ShortName, child3Id: data.id, + child3DnaId: data.ancestorDNA, child3: data.orgChild3Name, child3ShortName: data.orgChild3ShortName, }); @@ -5713,18 +5723,23 @@ export class OrganizationController extends Controller { } return new HttpSuccess({ rootId: data.orgRootId, + rootDnaId: data.ancestorDNA, root: data.orgRoot == null ? null : data.orgRoot.orgRootName, rootShortName: data.orgRoot == null ? null : data.orgRoot.orgRootShortName, child1Id: data.orgChild1Id, + child1DnaId: data.ancestorDNA, child1: data.orgChild1 == null ? null : data.orgChild1.orgChild1Name, child1ShortName: data.orgChild1 == null ? null : data.orgChild1.orgChild1ShortName, child2Id: data.orgChild2Id, + child2DnaId: data.ancestorDNA, child2: data.orgChild2 == null ? null : data.orgChild2.orgChild2Name, child2ShortName: data.orgChild2 == null ? null : data.orgChild2.orgChild2ShortName, child3Id: data.orgChild3Id, + child3DnaId: data.ancestorDNA, child3: data.orgChild3 == null ? null : data.orgChild3.orgChild3Name, child3ShortName: data.orgChild3 == null ? null : data.orgChild3.orgChild3ShortName, child4Id: data.id, + child4DnaId: data.ancestorDNA, child4: data.orgChild4Name, child4ShortName: data.orgChild4ShortName, }); @@ -6380,6 +6395,7 @@ export class OrganizationController extends Controller { ) .select([ "orgRoot.id", + "orgRoot.ancestorDNA", "orgRoot.orgRootName", "orgRoot.orgRootShortName", "orgRoot.orgRootCode", @@ -6412,6 +6428,7 @@ export class OrganizationController extends Controller { ) .select([ "orgChild1.id", + "orgChild1.ancestorDNA", "orgChild1.orgChild1Name", "orgChild1.orgChild1ShortName", "orgChild1.orgChild1Code", @@ -6446,6 +6463,7 @@ export class OrganizationController extends Controller { ) .select([ "orgChild2.id", + "orgChild2.ancestorDNA", "orgChild2.orgChild2Name", "orgChild2.orgChild2ShortName", "orgChild2.orgChild2Code", @@ -6481,6 +6499,7 @@ export class OrganizationController extends Controller { ) .select([ "orgChild3.id", + "orgChild3.ancestorDNA", "orgChild3.orgChild3Name", "orgChild3.orgChild3ShortName", "orgChild3.orgChild3Code", @@ -6516,6 +6535,7 @@ export class OrganizationController extends Controller { ) .select([ "orgChild4.id", + "orgChild4.ancestorDNA", "orgChild4.orgChild4Name", "orgChild4.orgChild4ShortName", "orgChild4.orgChild4Code", @@ -6538,6 +6558,7 @@ export class OrganizationController extends Controller { orgRootData.map(async (orgRoot) => { return { orgTreeId: orgRoot.id, + orgTreeDnaId: orgRoot.ancestorDNA, orgLevel: 0, orgName: orgRoot.orgRootName, orgTreeName: orgRoot.orgRootName, @@ -6646,7 +6667,9 @@ export class OrganizationController extends Controller { .filter((orgChild1) => orgChild1.orgRootId === orgRoot.id) .map(async (orgChild1) => ({ orgTreeId: orgChild1.id, + orgTreeDnaId: orgChild1.ancestorDNA, orgRootId: orgRoot.id, + orgRootDnaId: orgRoot.ancestorDNA, orgLevel: 1, orgName: `${orgChild1.orgChild1Name}/${orgRoot.orgRootName}`, orgTreeName: orgChild1.orgChild1Name, @@ -6768,7 +6791,9 @@ export class OrganizationController extends Controller { .filter((orgChild2) => orgChild2.orgChild1Id === orgChild1.id) .map(async (orgChild2) => ({ orgTreeId: orgChild2.id, + orgTreeDnaId: orgChild2.ancestorDNA, orgRootId: orgChild1.id, + orgRootDnaId: orgChild1.ancestorDNA, orgLevel: 2, orgName: `${orgChild2.orgChild2Name}/${orgChild1.orgChild1Name}/${orgRoot.orgRootName}`, orgTreeName: orgChild2.orgChild2Name, @@ -6900,7 +6925,9 @@ export class OrganizationController extends Controller { .filter((orgChild3) => orgChild3.orgChild2Id === orgChild2.id) .map(async (orgChild3) => ({ orgTreeId: orgChild3.id, + orgTreeDnaId: orgChild3.ancestorDNA, orgRootId: orgChild2.id, + orgRootDnaId: orgChild2.ancestorDNA, orgLevel: 3, orgName: `${orgChild3.orgChild3Name}/${orgChild2.orgChild2Name}/${orgChild1.orgChild1Name}/${orgRoot.orgRootName}`, orgTreeName: orgChild3.orgChild3Name, @@ -7039,7 +7066,9 @@ export class OrganizationController extends Controller { .filter((orgChild4) => orgChild4.orgChild3Id === orgChild3.id) .map(async (orgChild4) => ({ orgTreeId: orgChild4.id, + orgTreeDnaId: orgChild4.ancestorDNA, orgRootId: orgChild3.id, + orgRootDnaId: orgChild3.ancestorDNA, orgLevel: 4, orgName: `${orgChild4.orgChild4Name}/${orgChild3.orgChild3Name}/${orgChild2.orgChild2Name}/${orgChild1.orgChild1Name}/${orgRoot.orgRootName}`, orgTreeName: orgChild4.orgChild4Name, diff --git a/src/controllers/OrganizationDotnetController.ts b/src/controllers/OrganizationDotnetController.ts index 4836a11d..969d9ebe 100644 --- a/src/controllers/OrganizationDotnetController.ts +++ b/src/controllers/OrganizationDotnetController.ts @@ -18,7 +18,7 @@ import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; import { RequestWithUser } from "../middlewares/user"; import { Profile } from "../entities/Profile"; -import { Brackets, IsNull, Not } from "typeorm"; +import { Brackets, In, IsNull, Not } from "typeorm"; import { OrgRevision } from "../entities/OrgRevision"; import { OrgRoot } from "../entities/OrgRoot"; import { ProfileEmployee } from "../entities/ProfileEmployee"; @@ -26,6 +26,7 @@ import { Position } from "../entities/Position"; import { Insignia } from "../entities/Insignia"; import { CreateProfileInsignia, ProfileInsignia } from "../entities/ProfileInsignia"; import { PosMaster } from "../entities/PosMaster"; +import { EmployeePosDict } from "../entities/EmployeePosDict"; @Route("api/v1/org/dotnet") @Tags("Dotnet") @@ -43,6 +44,7 @@ export class OrganizationDotnetController extends Controller { private positionRepository = AppDataSource.getRepository(Position); private posMasterRepository = AppDataSource.getRepository(PosMaster); private insigniaRepo = AppDataSource.getRepository(ProfileInsignia); + private employeePosDictRepository = AppDataSource.getRepository(EmployeePosDict); /** * 1. API Search Profile @@ -294,6 +296,9 @@ export class OrganizationDotnetController extends Controller { }, }, }); + let fullname = ""; + let commanderId = ""; + let commanderKeycloak = ""; if (!profile) { const profile = await this.profileEmpRepo.findOne({ @@ -354,7 +359,6 @@ export class OrganizationDotnetController extends Controller { x.orgRevision?.orgRevisionIsCurrent == true, )?.orgChild4?.id ?? null, }; - let fullname = ""; let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], where: { @@ -377,6 +381,8 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], @@ -399,6 +405,8 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], @@ -421,6 +429,8 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], @@ -443,6 +453,8 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], @@ -465,8 +477,12 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { fullname = ""; + commanderId = ""; + commanderKeycloak = ""; } } } @@ -579,6 +595,8 @@ export class OrganizationDotnetController extends Controller { x.orgRevision?.orgRevisionIsCurrent == true, )?.orgChild4Id ?? null, commander: fullname, + commanderId, + commanderKeycloak, posLevel: profile.posLevel?.posLevelName ?? null, posType: profile.posType?.posTypeName ?? null, profileSalary: profile.profileSalary.length > 0 ? profile.profileSalary[0] : null, @@ -622,7 +640,6 @@ export class OrganizationDotnetController extends Controller { )?.orgChild4?.id ?? null, }; - let fullname = ""; let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], where: { @@ -646,6 +663,8 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], @@ -669,6 +688,8 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], @@ -692,6 +713,8 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], @@ -715,6 +738,8 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { let pos = await this.posMasterRepository.findOne({ relations: ["current_holder"], @@ -738,8 +763,12 @@ export class OrganizationDotnetController extends Controller { pos.current_holder.firstName + " " + pos.current_holder.lastName; + commanderId = pos.current_holder.id; + commanderKeycloak = pos.current_holder.keycloak; } else { fullname = ""; + commanderId = ""; + commanderKeycloak = ""; } } } @@ -852,13 +881,14 @@ export class OrganizationDotnetController extends Controller { x.orgRevision?.orgRevisionIsCurrent == true, )?.orgChild4Id ?? null, commander: fullname, + commanderId, + commanderKeycloak, posLevel: profile.posLevel?.posLevelName ?? null, posType: profile.posType?.posTypeName ?? null, profileSalary: profile.profileSalary.length > 0 ? profile.profileSalary[0] : null, profileInsignia: profile.profileInsignias.length > 0 ? profile.profileInsignias[0] : null, profileType: "OFFICER", }; - console.log("11111111111111131"); return new HttpSuccess(mapProfile); } @@ -2325,6 +2355,158 @@ export class OrganizationDotnetController extends Controller { return new HttpSuccess(mapProfile); } + /** + * 3. API Get Profile จาก keycloak id + * + * @summary 3. API Get Profile จาก keycloak id + * + * @param {string} keycloakId Id keycloak + */ + @Post("find/employee/position") + async GetProfileByPositionEmpAsync( + @Request() req: RequestWithUser, + @Body() + body: { + empPosId: string[]; + rootId: string; + }, + ) { + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + const employeePosDict = await this.employeePosDictRepository.find({ + where: { id: In(body.empPosId) }, + }); + + const profiles = await this.profileEmpRepo.find({ + relations: [ + "posLevel", + "posType", + "profileSalary", + "profileInsignias", + "profileInsignias.insignia", + "current_holders", + "current_holders.orgRevision", + "current_holders.orgRoot", + "current_holders.orgChild1", + "current_holders.orgChild2", + "current_holders.orgChild3", + "current_holders.orgChild4", + ], + where: employeePosDict.map((entry) => ({ + posLevelId: entry.posLevelId, + posTypeId: entry.posTypeId, + position: entry.posDictName, + current_holders: { orgRootId: body.rootId }, + })), + order: { + profileSalary: { + date: "DESC", + }, + profileInsignias: { + receiveDate: "DESC", + }, + }, + }); + + const mapProfile = profiles.map((profile) => { + const shortName = + profile.current_holders.length == 0 + ? null + : profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgChild4 != + null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgChild4.orgChild4ShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) + ?.orgChild3 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgChild3.orgChild3ShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) + ?.orgChild2 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgChild2.orgChild2ShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) != + null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) + ?.orgChild1 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgChild1.orgChild1ShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) != + null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id) + ?.orgRoot != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgRoot.orgRootShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}` + : null; + return { + id: profile.id, + avatar: profile.avatar, + avatarName: profile.avatarName, + rank: profile.rank ?? "", + prefix: profile.prefix ?? "", + firstName: profile.firstName ?? "", + lastName: profile.lastName ?? "", + citizenId: profile.citizenId ?? "", + position: profile.position ?? "", + posLevelId: profile.posLevelId, + email: profile.email, + phone: profile.phone, + keycloak: profile.keycloak, + isProbation: profile.isProbation, + isLeave: profile.isLeave, + leaveReason: profile.leaveReason, + dateRetire: profile.dateRetire, + dateAppoint: profile.dateAppoint, + dateRetireLaw: profile.dateRetireLaw, + dateStart: profile.dateStart, + govAgeAbsent: profile.govAgeAbsent, + govAgePlus: profile.govAgePlus, + birthDate: profile.birthDate ?? new Date(), + reasonSameDate: profile.reasonSameDate, + telephoneNumber: profile.telephoneNumber, + nationality: profile.nationality, + gender: profile.gender ?? "", + relationship: profile.relationship ?? "", + religion: profile.religion ?? "", + bloodGroup: profile.bloodGroup ?? "", + registrationAddress: profile.registrationAddress, + registrationProvinceId: profile.registrationProvinceId, + registrationDistrictId: profile.registrationDistrictId, + registrationSubDistrictId: profile.registrationSubDistrictId, + registrationZipCode: profile.registrationZipCode, + currentAddress: profile.currentAddress, + currentProvinceId: profile.currentProvinceId, + currentSubDistrictId: profile.currentSubDistrictId, + currentZipCode: profile.currentZipCode, + // dutyTimeId: profile.dutyTimeId, + // dutyTimeEffectiveDate: profile.dutyTimeEffectiveDate, + posLevel: profile.posLevel?.posLevelName ?? "", + posType: profile.posType?.posTypeName ?? "", + profileSalary: profile.profileSalary, + profileInsignia: profile.profileInsignias.map((x) => { + return { ...x, insignia: x.insignia.name }; + }), + amount: profile.amount, + positionSalaryAmount: profile.positionSalaryAmount, + mouthSalaryAmount: profile.mouthSalaryAmount, + profileType: "EMPLOYEE", + root: + profile?.current_holders?.find( + (x) => + x.orgRevision?.orgRevisionIsDraft == false && + x.orgRevision?.orgRevisionIsCurrent == true, + )?.orgRoot?.orgRootName ?? null, + rootId: + profile?.current_holders?.find( + (x) => + x.orgRevision?.orgRevisionIsDraft == false && + x.orgRevision?.orgRevisionIsCurrent == true, + )?.orgRootId ?? null, + posNo: shortName ?? "", + }; + }); + + return new HttpSuccess(mapProfile); + } + /** * 7.1 Get ข้อมูล GetUserFullName * diff --git a/src/controllers/OrganizationUnauthorizeController.ts b/src/controllers/OrganizationUnauthorizeController.ts index 424a30eb..9ecc7d87 100644 --- a/src/controllers/OrganizationUnauthorizeController.ts +++ b/src/controllers/OrganizationUnauthorizeController.ts @@ -1,4 +1,4 @@ -import { Controller, Get, Post, Route, Tags, Body, Path, Response } from "tsoa"; +import { Controller, Get, Post, Route, Tags, Body, Path, Response, Patch } from "tsoa"; import { OrgRevision } from "../entities/OrgRevision"; import { AppDataSource } from "../database/data-source"; import HttpSuccess from "../interfaces/http-success"; @@ -1159,4 +1159,60 @@ export class OrganizationUnauthorizeController extends Controller { await this.profileRepo.save(profile); return new HttpSuccess("Email verified successfully."); } + + // @Patch("retirement") + // public async updateStatusRetirement( + // @Body() + // body: { + // data: { + // profileId: string; + // }[]; + // }, + // ) { + // let profiles: Profile[] = []; + // let _null: any = null; + // await Promise.all( + // body.data.map(async (item) => { + // const _profile = await this.profileRepo.findOneBy({ id: item.profileId }); + // if (!_profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + // _profile.isRetirement = true; + // _profile.isLeave = true; + // _profile.leaveType = "RETIRE"; + // _profile.leaveDate = new Date(); + // _profile.dateLeave = new Date(); + // _profile.lastUpdatedAt = new Date(); + // profiles.push(_profile); + // }) + // ); + // await this.profileRepo.save(profiles); + // return new HttpSuccess(); + // } + + // @Patch("retirement-employee") + // public async updateStatusRetirementEmp( + // @Body() + // body: { + // data: { + // profileId: string; + // }[]; + // }, + // ) { + // let profiles: ProfileEmployee[] = []; + // let _null: any = null; + // await Promise.all( + // body.data.map(async (item) => { + // const _profile = await this.profileEmpRepo.findOneBy({ id: item.profileId }); + // if (!_profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + // _profile.isRetirement = true; + // _profile.isLeave = true; + // _profile.leaveType = "RETIRE"; + // _profile.leaveDate = new Date(); + // _profile.dateLeave = new Date(); + // _profile.lastUpdatedAt = new Date(); + // profiles.push(_profile); + // }) + // ); + // await this.profileEmpRepo.save(profiles); + // return new HttpSuccess(); + // } } diff --git a/src/controllers/PosMasterActController.ts b/src/controllers/PosMasterActController.ts index 6f2b7cc5..e658d122 100644 --- a/src/controllers/PosMasterActController.ts +++ b/src/controllers/PosMasterActController.ts @@ -300,7 +300,7 @@ export class PosMasterActController extends Controller { ]; const _organization = organization .filter((part) => part !== undefined && part !== null) - .join("/"); + .join(" "); const organizationNew = [ posMasterAct.posMaster?.current_holder?.position ?? null, @@ -312,7 +312,7 @@ export class PosMasterActController extends Controller { ]; const _organizationNew = organizationNew .filter((part) => part !== undefined && part !== null) - .join("/"); + .join(" "); return new HttpSuccess({ prefix: posMasterAct.posMasterChild?.current_holder?.prefix ?? null, firstName: posMasterAct.posMasterChild?.current_holder?.firstName ?? null, diff --git a/src/controllers/ProfileAbilityController.ts b/src/controllers/ProfileAbilityController.ts index 41409586..dc641c1a 100644 --- a/src/controllers/ProfileAbilityController.ts +++ b/src/controllers/ProfileAbilityController.ts @@ -134,7 +134,7 @@ export class ProfileAbilityController extends Controller { history.profileAbilityId = data.id; await this.profileAbilityHistoryRepo.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{abilityId}") diff --git a/src/controllers/ProfileAbilityEmployeeController.ts b/src/controllers/ProfileAbilityEmployeeController.ts index b77f2ba1..eca0cd8c 100644 --- a/src/controllers/ProfileAbilityEmployeeController.ts +++ b/src/controllers/ProfileAbilityEmployeeController.ts @@ -139,7 +139,7 @@ export class ProfileAbilityEmployeeController extends Controller { await this.profileAbilityHistoryRepo.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{abilityId}") diff --git a/src/controllers/ProfileAbilityEmployeeTempController.ts b/src/controllers/ProfileAbilityEmployeeTempController.ts index 60c3d023..335ac04c 100644 --- a/src/controllers/ProfileAbilityEmployeeTempController.ts +++ b/src/controllers/ProfileAbilityEmployeeTempController.ts @@ -133,7 +133,7 @@ export class ProfileAbilityEmployeeTempController extends Controller { await this.profileAbilityHistoryRepo.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{abilityId}") diff --git a/src/controllers/ProfileActpositionController.ts b/src/controllers/ProfileActpositionController.ts new file mode 100644 index 00000000..0033af36 --- /dev/null +++ b/src/controllers/ProfileActpositionController.ts @@ -0,0 +1,204 @@ +import { + Body, + Controller, + Delete, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { Profile } from "../entities/Profile"; +import { + CreateProfileActposition, + ProfileActposition, + UpdateProfileActposition, +} from "../entities/ProfileActposition"; +import { ProfileActpositionHistory } from "../entities/ProfileActpositionHistory"; +import { RequestWithUser } from "../middlewares/user"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import HttpSuccess from "../interfaces/http-success"; +import permission from "../interfaces/permission"; +import { setLogDataDiff } from "../interfaces/utils"; +@Route("api/v1/org/profile/actposition") +@Tags("ProfileActposition") +@Security("bearerAuth") +export class ProfileActpositionController extends Controller { + private profileRepo = AppDataSource.getRepository(Profile); + private profileActpositionRepo = AppDataSource.getRepository(ProfileActposition); + private profileActpositionHistoryRepo = AppDataSource.getRepository(ProfileActpositionHistory); + + @Get("user") + public async detailProfileActpositionUser(@Request() request: { user: Record }) { + const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileActpositionId = await this.profileActpositionRepo.find({ + where: { profileId: profile.id }, + order: { createdAt: "ASC" }, + }); + if (!getProfileActpositionId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileActpositionId); + } + + @Get("{profileId}") + public async detailProfileActposition( + @Path() profileId: string, + @Request() req: RequestWithUser, + ) { + let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER"); + if (_workflow == false) + await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId); + const getProfileActpositionId = await this.profileActpositionRepo.find({ + where: { profileId: profileId }, + order: { createdAt: "ASC" }, + }); + if (!getProfileActpositionId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileActpositionId); + } + + @Get("admin/history/{actpositionId}") + public async getProfileActpositionAdminHistory( + @Path() actpositionId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (_record) { + let _workflow = await new permission().Workflow(req, actpositionId, "SYS_REGISTRY_OFFICER"); + if (_workflow == false) + await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", _record.profileId); + } + + const record = await this.profileActpositionHistoryRepo.find({ + where: { profileActpositionId: actpositionId }, + order: { createdAt: "DESC" }, + }); + + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Get("history/{actpositionId}") + public async getProfileActpositionHistory(@Path() actpositionId: string) { + const record = await this.profileActpositionHistoryRepo.find({ + where: { profileActpositionId: actpositionId }, + order: { createdAt: "DESC" }, + }); + + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Post() + public async newProfileActposition( + @Request() req: RequestWithUser, + @Body() body: CreateProfileActposition, + ) { + if (!body.profileId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); + } + + const profile = await this.profileRepo.findOneBy({ id: body.profileId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profile.id); + const before = null; + const data = new ProfileActposition(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + createdAt: new Date(), + lastUpdatedAt: new Date(), + }; + + Object.assign(data, { ...body, ...meta }); + const history = new ProfileActpositionHistory(); + Object.assign(history, { ...data, id: undefined }); + + await this.profileActpositionRepo.save(data, { data: req }); + setLogDataDiff(req, { before, after: data }); + history.profileActpositionId = data.id; + await this.profileActpositionHistoryRepo.save(history, { data: req }); + //setLogDataDiff(req, { before, after: history }); + return new HttpSuccess(data.id); + } + + @Patch("{actpositionId}") + public async editProfileActposition( + @Body() body: UpdateProfileActposition, + @Request() req: RequestWithUser, + @Path() actpositionId: string, + ) { + const record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", record.profileId); + + const history = new ProfileActpositionHistory(); + const before = structuredClone(record); + // const before_null = null; + Object.assign(record, body); + Object.assign(history, { ...record, id: undefined }); + + history.profileActpositionId = actpositionId; + record.lastUpdateUserId = req.user.sub; + record.lastUpdateFullName = req.user.name; + record.lastUpdatedAt = new Date(); + history.lastUpdateUserId = req.user.sub; + history.lastUpdateFullName = req.user.name; + history.createdUserId = req.user.sub; + history.createdFullName = req.user.name; + history.createdAt = new Date(); + history.lastUpdatedAt = new Date(); + + await Promise.all([ + this.profileActpositionRepo.save(record, { data: req }), + setLogDataDiff(req, { before, after: record }), + this.profileActpositionHistoryRepo.save(history, { data: req }), + // setLogDataDiff(req, { before: before_null, after: history }), + ]); + + return new HttpSuccess(); + } + + @Delete("{actpositionId}") + public async deleteProfileActposition( + @Path() actpositionId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (_record) { + await new permission().PermissionOrgUserDelete( + req, + "SYS_REGISTRY_OFFICER", + _record.profileId, + ); + } + await this.profileActpositionHistoryRepo.delete({ + profileActpositionId: actpositionId, + }); + + const result = await this.profileActpositionRepo.delete({ id: actpositionId }); + + if (result.affected == undefined || result.affected <= 0) + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileActpositionEmployeeController.ts b/src/controllers/ProfileActpositionEmployeeController.ts new file mode 100644 index 00000000..2ada7dd3 --- /dev/null +++ b/src/controllers/ProfileActpositionEmployeeController.ts @@ -0,0 +1,211 @@ +import { + Body, + Controller, + Delete, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileActpositionEmployee, + ProfileActposition, + UpdateProfileActposition, +} from "../entities/ProfileActposition"; +import { ProfileActpositionHistory } from "../entities/ProfileActpositionHistory"; +import { RequestWithUser } from "../middlewares/user"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import HttpSuccess from "../interfaces/http-success"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +import { setLogDataDiff } from "../interfaces/utils"; +@Route("api/v1/org/profile-employee/actposition") +@Tags("ProfileActpositionEmployee") +@Security("bearerAuth") +export class ProfileActpositionEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private profileActpositionRepo = AppDataSource.getRepository(ProfileActposition); + private profileActpositionHistoryRepo = AppDataSource.getRepository(ProfileActpositionHistory); + + @Get("user") + public async detailProfileActpositionUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileActpositionId = await this.profileActpositionRepo.find({ + where: { profileEmployeeId: profile.id }, + order: { createdAt: "ASC" }, + }); + if (!getProfileActpositionId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileActpositionId); + } + + @Get("{profileEmployeeId}") + public async detailProfileActposition( + @Path() profileEmployeeId: string, + @Request() req: RequestWithUser, + ) { + let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP"); + if (_workflow == false) + await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId); + const getProfileActpositionId = await this.profileActpositionRepo.find({ + where: { profileEmployeeId: profileEmployeeId }, + order: { createdAt: "ASC" }, + }); + if (!getProfileActpositionId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileActpositionId); + } + + @Get("admin/history/{actpositionId}") + public async getProfileAdminActpositionHistory( + @Path() actpositionId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (_record) { + let _workflow = await new permission().Workflow(req, actpositionId, "SYS_REGISTRY_EMP"); + if (_workflow == false) + await new permission().PermissionOrgUserGet( + req, + "SYS_REGISTRY_EMP", + _record.profileEmployeeId, + ); + } + const record = await this.profileActpositionHistoryRepo.find({ + where: { profileActpositionId: actpositionId }, + order: { createdAt: "DESC" }, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Get("history/{actpositionId}") + public async getProfileActpositionHistory(@Path() actpositionId: string) { + const record = await this.profileActpositionHistoryRepo.find({ + where: { profileActpositionId: actpositionId }, + order: { createdAt: "DESC" }, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Post() + public async newProfileActposition( + @Request() req: RequestWithUser, + @Body() body: CreateProfileActpositionEmployee, + ) { + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_EMP", profile.id); + const before = null; + const data = new ProfileActposition(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + createdAt: new Date(), + lastUpdatedAt: new Date(), + }; + + Object.assign(data, { ...body, ...meta }); + const history = new ProfileActpositionHistory(); + Object.assign(history, { ...data, id: undefined }); + + await this.profileActpositionRepo.save(data, { data: req }); + setLogDataDiff(req, { before, after: data }); + history.profileActpositionId = data.id; + await this.profileActpositionHistoryRepo.save(history, { data: req }); + //setLogDataDiff(req, { before, after: history }); + + return new HttpSuccess(data.id); + } + + @Patch("{actpositionId}") + public async editProfileActposition( + @Body() body: UpdateProfileActposition, + @Request() req: RequestWithUser, + @Path() actpositionId: string, + ) { + const record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + await new permission().PermissionOrgUserUpdate( + req, + "SYS_REGISTRY_EMP", + record.profileEmployeeId, + ); + const before = structuredClone(record); + // const before_null = null; + const history = new ProfileActpositionHistory(); + + Object.assign(record, body); + Object.assign(history, { ...record, id: undefined }); + + history.profileActpositionId = actpositionId; + record.lastUpdateUserId = req.user.sub; + record.lastUpdateFullName = req.user.name; + record.lastUpdatedAt = new Date(); + history.lastUpdateUserId = req.user.sub; + history.lastUpdateFullName = req.user.name; + history.createdUserId = req.user.sub; + history.createdFullName = req.user.name; + history.createdAt = new Date(); + history.lastUpdatedAt = new Date(); + + await Promise.all([ + this.profileActpositionRepo.save(record, { data: req }), + setLogDataDiff(req, { before, after: record }), + this.profileActpositionHistoryRepo.save(history, { data: req }), + // setLogDataDiff(req, { before: before_null, after: history }), + ]); + + return new HttpSuccess(); + } + + @Delete("{actpositionId}") + public async deleteProfileActposition( + @Path() actpositionId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (_record) { + await new permission().PermissionOrgUserDelete( + req, + "SYS_REGISTRY_EMP", + _record.profileEmployeeId, + ); + } + await this.profileActpositionHistoryRepo.delete({ + profileActpositionId: actpositionId, + }); + + const result = await this.profileActpositionRepo.delete({ id: actpositionId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileActpositionEmployeeTempController.ts b/src/controllers/ProfileActpositionEmployeeTempController.ts new file mode 100644 index 00000000..630cb785 --- /dev/null +++ b/src/controllers/ProfileActpositionEmployeeTempController.ts @@ -0,0 +1,198 @@ +import { + Body, + Controller, + Delete, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileActpositionEmployee, + ProfileActposition, + UpdateProfileActposition, +} from "../entities/ProfileActposition"; +import { ProfileActpositionHistory } from "../entities/ProfileActpositionHistory"; +import { RequestWithUser } from "../middlewares/user"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import HttpSuccess from "../interfaces/http-success"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +import { setLogDataDiff } from "../interfaces/utils"; +@Route("api/v1/org/profile-temp/actposition") +@Tags("ProfileActpositionEmployee") +@Security("bearerAuth") +export class ProfileActpositionEmployeeTempController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private profileActpositionRepo = AppDataSource.getRepository(ProfileActposition); + private profileActpositionHistoryRepo = AppDataSource.getRepository(ProfileActpositionHistory); + + @Get("user") + public async detailProfileActpositionUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileActpositionId = await this.profileActpositionRepo.find({ + where: { profileEmployeeId: profile.id }, + order: { createdAt: "ASC" }, + }); + if (!getProfileActpositionId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileActpositionId); + } + + @Get("{profileEmployeeId}") + public async detailProfileActposition( + @Path() profileEmployeeId: string, + @Request() req: RequestWithUser, + ) { + let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_TEMP"); + if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_TEMP"); + const getProfileActpositionId = await this.profileActpositionRepo.find({ + where: { profileEmployeeId: profileEmployeeId }, + order: { createdAt: "ASC" }, + }); + if (!getProfileActpositionId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileActpositionId); + } + + @Get("admin/history/{actpositionId}") + public async getProfileAdminActpositionHistory( + @Path() actpositionId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (_record) { + let _workflow = await new permission().Workflow(req, actpositionId, "SYS_REGISTRY_TEMP"); + if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_TEMP"); + } + const record = await this.profileActpositionHistoryRepo.find({ + where: { profileActpositionId: actpositionId }, + order: { createdAt: "DESC" }, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Get("history/{actpositionId}") + public async getProfileActpositionHistory(@Path() actpositionId: string) { + const record = await this.profileActpositionHistoryRepo.find({ + where: { profileActpositionId: actpositionId }, + order: { createdAt: "DESC" }, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Post() + public async newProfileActposition( + @Request() req: RequestWithUser, + @Body() body: CreateProfileActpositionEmployee, + ) { + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const before = null; + const data = new ProfileActposition(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + createdAt: new Date(), + lastUpdatedAt: new Date(), + }; + + Object.assign(data, { ...body, ...meta }); + const history = new ProfileActpositionHistory(); + Object.assign(history, { ...data, id: undefined }); + + await this.profileActpositionRepo.save(data, { data: req }); + setLogDataDiff(req, { before, after: data }); + history.profileActpositionId = data.id; + await this.profileActpositionHistoryRepo.save(history, { data: req }); + //setLogDataDiff(req, { before, after: history }); + + return new HttpSuccess(data.id); + } + + @Patch("{actpositionId}") + public async editProfileActposition( + @Body() body: UpdateProfileActposition, + @Request() req: RequestWithUser, + @Path() actpositionId: string, + ) { + const record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const before = structuredClone(record); + // const before_null = null; + const history = new ProfileActpositionHistory(); + + Object.assign(record, body); + Object.assign(history, { ...record, id: undefined }); + + history.profileActpositionId = actpositionId; + record.lastUpdateUserId = req.user.sub; + record.lastUpdateFullName = req.user.name; + record.lastUpdatedAt = new Date(); + history.lastUpdateUserId = req.user.sub; + history.lastUpdateFullName = req.user.name; + history.createdUserId = req.user.sub; + history.createdFullName = req.user.name; + history.createdAt = new Date(); + history.lastUpdatedAt = new Date(); + + await Promise.all([ + this.profileActpositionRepo.save(record, { data: req }), + setLogDataDiff(req, { before, after: record }), + this.profileActpositionHistoryRepo.save(history, { data: req }), + // setLogDataDiff(req, { before: before_null, after: history }), + ]); + + return new HttpSuccess(); + } + + @Delete("{actpositionId}") + public async deleteProfileActposition( + @Path() actpositionId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileActpositionRepo.findOneBy({ id: actpositionId }); + if (_record) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + } + + await this.profileActpositionHistoryRepo.delete({ + profileActpositionId: actpositionId, + }); + + const result = await this.profileActpositionRepo.delete({ id: actpositionId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileAssessmentsController.ts b/src/controllers/ProfileAssessmentsController.ts index ca81cb53..f8ca30e0 100644 --- a/src/controllers/ProfileAssessmentsController.ts +++ b/src/controllers/ProfileAssessmentsController.ts @@ -146,7 +146,7 @@ export class ProfileAssessmentsController extends Controller { await this.profileAssessmentsHistoryRepository.save(history, { data: req }); setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{assessmentId}") diff --git a/src/controllers/ProfileAssessmentsEmployeeController.ts b/src/controllers/ProfileAssessmentsEmployeeController.ts index 034218f4..26127f3e 100644 --- a/src/controllers/ProfileAssessmentsEmployeeController.ts +++ b/src/controllers/ProfileAssessmentsEmployeeController.ts @@ -147,7 +147,7 @@ export class ProfileAssessmentsEmployeeController extends Controller { await this.profileAssessmentsHistoryRepository.save(history, { data: req }); setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{assessmentId}") diff --git a/src/controllers/ProfileAssessmentsEmployeeTempController.ts b/src/controllers/ProfileAssessmentsEmployeeTempController.ts index d9e2b47a..2aa62ff7 100644 --- a/src/controllers/ProfileAssessmentsEmployeeTempController.ts +++ b/src/controllers/ProfileAssessmentsEmployeeTempController.ts @@ -140,7 +140,7 @@ export class ProfileAssessmentsEmployeeTempController extends Controller { await this.profileAssessmentsHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{assessmentId}") diff --git a/src/controllers/ProfileAssistanceController.ts b/src/controllers/ProfileAssistanceController.ts new file mode 100644 index 00000000..5db71276 --- /dev/null +++ b/src/controllers/ProfileAssistanceController.ts @@ -0,0 +1,201 @@ +import { + Body, + Controller, + Delete, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { Profile } from "../entities/Profile"; +import { + CreateProfileAssistance, + ProfileAssistance, + UpdateProfileAssistance, +} from "../entities/ProfileAssistance"; +import { ProfileAssistanceHistory } from "../entities/ProfileAssistanceHistory"; +import { RequestWithUser } from "../middlewares/user"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import HttpSuccess from "../interfaces/http-success"; +import permission from "../interfaces/permission"; +import { setLogDataDiff } from "../interfaces/utils"; +@Route("api/v1/org/profile/assistance") +@Tags("ProfileAssistance") +@Security("bearerAuth") +export class ProfileAssistanceController extends Controller { + private profileRepo = AppDataSource.getRepository(Profile); + private profileAssistanceRepo = AppDataSource.getRepository(ProfileAssistance); + private profileAssistanceHistoryRepo = AppDataSource.getRepository(ProfileAssistanceHistory); + + @Get("user") + public async detailProfileAssistanceUser(@Request() request: { user: Record }) { + const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileAssistanceId = await this.profileAssistanceRepo.find({ + where: { profileId: profile.id }, + order: { createdAt: "ASC" }, + }); + if (!getProfileAssistanceId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAssistanceId); + } + + @Get("{profileId}") + public async detailProfileAssistance(@Path() profileId: string, @Request() req: RequestWithUser) { + let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER"); + if (_workflow == false) + await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId); + const getProfileAssistanceId = await this.profileAssistanceRepo.find({ + where: { profileId: profileId }, + order: { createdAt: "ASC" }, + }); + if (!getProfileAssistanceId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAssistanceId); + } + + @Get("admin/history/{assistanceId}") + public async getProfileAssistanceAdminHistory( + @Path() assistanceId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (_record) { + let _workflow = await new permission().Workflow(req, assistanceId, "SYS_REGISTRY_OFFICER"); + if (_workflow == false) + await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", _record.profileId); + } + + const record = await this.profileAssistanceHistoryRepo.find({ + where: { profileAssistanceId: assistanceId }, + order: { createdAt: "DESC" }, + }); + + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Get("history/{assistanceId}") + public async getProfileAssistanceHistory(@Path() assistanceId: string) { + const record = await this.profileAssistanceHistoryRepo.find({ + where: { profileAssistanceId: assistanceId }, + order: { createdAt: "DESC" }, + }); + + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Post() + public async newProfileAssistance( + @Request() req: RequestWithUser, + @Body() body: CreateProfileAssistance, + ) { + if (!body.profileId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); + } + + const profile = await this.profileRepo.findOneBy({ id: body.profileId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profile.id); + const before = null; + const data = new ProfileAssistance(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + createdAt: new Date(), + lastUpdatedAt: new Date(), + }; + + Object.assign(data, { ...body, ...meta }); + const history = new ProfileAssistanceHistory(); + Object.assign(history, { ...data, id: undefined }); + + await this.profileAssistanceRepo.save(data, { data: req }); + setLogDataDiff(req, { before, after: data }); + history.profileAssistanceId = data.id; + await this.profileAssistanceHistoryRepo.save(history, { data: req }); + //setLogDataDiff(req, { before, after: history }); + return new HttpSuccess(data.id); + } + + @Patch("{assistanceId}") + public async editProfileAssistance( + @Body() body: UpdateProfileAssistance, + @Request() req: RequestWithUser, + @Path() assistanceId: string, + ) { + const record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", record.profileId); + + const history = new ProfileAssistanceHistory(); + const before = structuredClone(record); + // const before_null = null; + Object.assign(record, body); + Object.assign(history, { ...record, id: undefined }); + + history.profileAssistanceId = assistanceId; + record.lastUpdateUserId = req.user.sub; + record.lastUpdateFullName = req.user.name; + record.lastUpdatedAt = new Date(); + history.lastUpdateUserId = req.user.sub; + history.lastUpdateFullName = req.user.name; + history.createdUserId = req.user.sub; + history.createdFullName = req.user.name; + history.createdAt = new Date(); + history.lastUpdatedAt = new Date(); + + await Promise.all([ + this.profileAssistanceRepo.save(record, { data: req }), + setLogDataDiff(req, { before, after: record }), + this.profileAssistanceHistoryRepo.save(history, { data: req }), + // setLogDataDiff(req, { before: before_null, after: history }), + ]); + + return new HttpSuccess(); + } + + @Delete("{assistanceId}") + public async deleteProfileAssistance( + @Path() assistanceId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (_record) { + await new permission().PermissionOrgUserDelete( + req, + "SYS_REGISTRY_OFFICER", + _record.profileId, + ); + } + await this.profileAssistanceHistoryRepo.delete({ + profileAssistanceId: assistanceId, + }); + + const result = await this.profileAssistanceRepo.delete({ id: assistanceId }); + + if (result.affected == undefined || result.affected <= 0) + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileAssistanceEmployeeController.ts b/src/controllers/ProfileAssistanceEmployeeController.ts new file mode 100644 index 00000000..7a74675f --- /dev/null +++ b/src/controllers/ProfileAssistanceEmployeeController.ts @@ -0,0 +1,211 @@ +import { + Body, + Controller, + Delete, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileAssistanceEmployee, + ProfileAssistance, + UpdateProfileAssistance, +} from "../entities/ProfileAssistance"; +import { ProfileAssistanceHistory } from "../entities/ProfileAssistanceHistory"; +import { RequestWithUser } from "../middlewares/user"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import HttpSuccess from "../interfaces/http-success"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +import { setLogDataDiff } from "../interfaces/utils"; +@Route("api/v1/org/profile-employee/assistance") +@Tags("ProfileAssistanceEmployee") +@Security("bearerAuth") +export class ProfileAssistanceEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private profileAssistanceRepo = AppDataSource.getRepository(ProfileAssistance); + private profileAssistanceHistoryRepo = AppDataSource.getRepository(ProfileAssistanceHistory); + + @Get("user") + public async detailProfileAssistanceUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileAssistanceId = await this.profileAssistanceRepo.find({ + where: { profileEmployeeId: profile.id }, + order: { createdAt: "ASC" }, + }); + if (!getProfileAssistanceId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAssistanceId); + } + + @Get("{profileEmployeeId}") + public async detailProfileAssistance( + @Path() profileEmployeeId: string, + @Request() req: RequestWithUser, + ) { + let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP"); + if (_workflow == false) + await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId); + const getProfileAssistanceId = await this.profileAssistanceRepo.find({ + where: { profileEmployeeId: profileEmployeeId }, + order: { createdAt: "ASC" }, + }); + if (!getProfileAssistanceId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAssistanceId); + } + + @Get("admin/history/{assistanceId}") + public async getProfileAdminAssistanceHistory( + @Path() assistanceId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (_record) { + let _workflow = await new permission().Workflow(req, assistanceId, "SYS_REGISTRY_EMP"); + if (_workflow == false) + await new permission().PermissionOrgUserGet( + req, + "SYS_REGISTRY_EMP", + _record.profileEmployeeId, + ); + } + const record = await this.profileAssistanceHistoryRepo.find({ + where: { profileAssistanceId: assistanceId }, + order: { createdAt: "DESC" }, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Get("history/{assistanceId}") + public async getProfileAssistanceHistory(@Path() assistanceId: string) { + const record = await this.profileAssistanceHistoryRepo.find({ + where: { profileAssistanceId: assistanceId }, + order: { createdAt: "DESC" }, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Post() + public async newProfileAssistance( + @Request() req: RequestWithUser, + @Body() body: CreateProfileAssistanceEmployee, + ) { + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_EMP", profile.id); + const before = null; + const data = new ProfileAssistance(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + createdAt: new Date(), + lastUpdatedAt: new Date(), + }; + + Object.assign(data, { ...body, ...meta }); + const history = new ProfileAssistanceHistory(); + Object.assign(history, { ...data, id: undefined }); + + await this.profileAssistanceRepo.save(data, { data: req }); + setLogDataDiff(req, { before, after: data }); + history.profileAssistanceId = data.id; + await this.profileAssistanceHistoryRepo.save(history, { data: req }); + //setLogDataDiff(req, { before, after: history }); + + return new HttpSuccess(data.id); + } + + @Patch("{assistanceId}") + public async editProfileAssistance( + @Body() body: UpdateProfileAssistance, + @Request() req: RequestWithUser, + @Path() assistanceId: string, + ) { + const record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + await new permission().PermissionOrgUserUpdate( + req, + "SYS_REGISTRY_EMP", + record.profileEmployeeId, + ); + const before = structuredClone(record); + // const before_null = null; + const history = new ProfileAssistanceHistory(); + + Object.assign(record, body); + Object.assign(history, { ...record, id: undefined }); + + history.profileAssistanceId = assistanceId; + record.lastUpdateUserId = req.user.sub; + record.lastUpdateFullName = req.user.name; + record.lastUpdatedAt = new Date(); + history.lastUpdateUserId = req.user.sub; + history.lastUpdateFullName = req.user.name; + history.createdUserId = req.user.sub; + history.createdFullName = req.user.name; + history.createdAt = new Date(); + history.lastUpdatedAt = new Date(); + + await Promise.all([ + this.profileAssistanceRepo.save(record, { data: req }), + setLogDataDiff(req, { before, after: record }), + this.profileAssistanceHistoryRepo.save(history, { data: req }), + // setLogDataDiff(req, { before: before_null, after: history }), + ]); + + return new HttpSuccess(); + } + + @Delete("{assistanceId}") + public async deleteProfileAssistance( + @Path() assistanceId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (_record) { + await new permission().PermissionOrgUserDelete( + req, + "SYS_REGISTRY_EMP", + _record.profileEmployeeId, + ); + } + await this.profileAssistanceHistoryRepo.delete({ + profileAssistanceId: assistanceId, + }); + + const result = await this.profileAssistanceRepo.delete({ id: assistanceId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileAssistanceEmployeeTempController.ts b/src/controllers/ProfileAssistanceEmployeeTempController.ts new file mode 100644 index 00000000..546e8f88 --- /dev/null +++ b/src/controllers/ProfileAssistanceEmployeeTempController.ts @@ -0,0 +1,198 @@ +import { + Body, + Controller, + Delete, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileAssistanceEmployee, + ProfileAssistance, + UpdateProfileAssistance, +} from "../entities/ProfileAssistance"; +import { ProfileAssistanceHistory } from "../entities/ProfileAssistanceHistory"; +import { RequestWithUser } from "../middlewares/user"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import HttpSuccess from "../interfaces/http-success"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +import { setLogDataDiff } from "../interfaces/utils"; +@Route("api/v1/org/profile-temp/assistance") +@Tags("ProfileAssistanceEmployee") +@Security("bearerAuth") +export class ProfileAssistanceEmployeeTempController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private profileAssistanceRepo = AppDataSource.getRepository(ProfileAssistance); + private profileAssistanceHistoryRepo = AppDataSource.getRepository(ProfileAssistanceHistory); + + @Get("user") + public async detailProfileAssistanceUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileAssistanceId = await this.profileAssistanceRepo.find({ + where: { profileEmployeeId: profile.id }, + order: { createdAt: "ASC" }, + }); + if (!getProfileAssistanceId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAssistanceId); + } + + @Get("{profileEmployeeId}") + public async detailProfileAssistance( + @Path() profileEmployeeId: string, + @Request() req: RequestWithUser, + ) { + let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_TEMP"); + if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_TEMP"); + const getProfileAssistanceId = await this.profileAssistanceRepo.find({ + where: { profileEmployeeId: profileEmployeeId }, + order: { createdAt: "ASC" }, + }); + if (!getProfileAssistanceId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAssistanceId); + } + + @Get("admin/history/{assistanceId}") + public async getProfileAdminAssistanceHistory( + @Path() assistanceId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (_record) { + let _workflow = await new permission().Workflow(req, assistanceId, "SYS_REGISTRY_TEMP"); + if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_TEMP"); + } + const record = await this.profileAssistanceHistoryRepo.find({ + where: { profileAssistanceId: assistanceId }, + order: { createdAt: "DESC" }, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Get("history/{assistanceId}") + public async getProfileAssistanceHistory(@Path() assistanceId: string) { + const record = await this.profileAssistanceHistoryRepo.find({ + where: { profileAssistanceId: assistanceId }, + order: { createdAt: "DESC" }, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Post() + public async newProfileAssistance( + @Request() req: RequestWithUser, + @Body() body: CreateProfileAssistanceEmployee, + ) { + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const before = null; + const data = new ProfileAssistance(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + createdAt: new Date(), + lastUpdatedAt: new Date(), + }; + + Object.assign(data, { ...body, ...meta }); + const history = new ProfileAssistanceHistory(); + Object.assign(history, { ...data, id: undefined }); + + await this.profileAssistanceRepo.save(data, { data: req }); + setLogDataDiff(req, { before, after: data }); + history.profileAssistanceId = data.id; + await this.profileAssistanceHistoryRepo.save(history, { data: req }); + //setLogDataDiff(req, { before, after: history }); + + return new HttpSuccess(data.id); + } + + @Patch("{assistanceId}") + public async editProfileAssistance( + @Body() body: UpdateProfileAssistance, + @Request() req: RequestWithUser, + @Path() assistanceId: string, + ) { + const record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const before = structuredClone(record); + // const before_null = null; + const history = new ProfileAssistanceHistory(); + + Object.assign(record, body); + Object.assign(history, { ...record, id: undefined }); + + history.profileAssistanceId = assistanceId; + record.lastUpdateUserId = req.user.sub; + record.lastUpdateFullName = req.user.name; + record.lastUpdatedAt = new Date(); + history.lastUpdateUserId = req.user.sub; + history.lastUpdateFullName = req.user.name; + history.createdUserId = req.user.sub; + history.createdFullName = req.user.name; + history.createdAt = new Date(); + history.lastUpdatedAt = new Date(); + + await Promise.all([ + this.profileAssistanceRepo.save(record, { data: req }), + setLogDataDiff(req, { before, after: record }), + this.profileAssistanceHistoryRepo.save(history, { data: req }), + // setLogDataDiff(req, { before: before_null, after: history }), + ]); + + return new HttpSuccess(); + } + + @Delete("{assistanceId}") + public async deleteProfileAssistance( + @Path() assistanceId: string, + @Request() req: RequestWithUser, + ) { + const _record = await this.profileAssistanceRepo.findOneBy({ id: assistanceId }); + if (_record) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + } + + await this.profileAssistanceHistoryRepo.delete({ + profileAssistanceId: assistanceId, + }); + + const result = await this.profileAssistanceRepo.delete({ id: assistanceId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileCertificateController.ts b/src/controllers/ProfileCertificateController.ts index 4cdcf024..9ad35786 100644 --- a/src/controllers/ProfileCertificateController.ts +++ b/src/controllers/ProfileCertificateController.ts @@ -126,7 +126,7 @@ export class ProfileCertificateController extends Controller { await this.certificateHistoryRepo.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{certificateId}") diff --git a/src/controllers/ProfileCertificateEmployeeController.ts b/src/controllers/ProfileCertificateEmployeeController.ts index db2e9dde..33d00bfa 100644 --- a/src/controllers/ProfileCertificateEmployeeController.ts +++ b/src/controllers/ProfileCertificateEmployeeController.ts @@ -130,7 +130,7 @@ export class ProfileCertificateEmployeeController extends Controller { await this.certificateHistoryRepo.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{certificateId}") diff --git a/src/controllers/ProfileCertificateEmployeeTempController.ts b/src/controllers/ProfileCertificateEmployeeTempController.ts index 66f9d3cc..f0eec89c 100644 --- a/src/controllers/ProfileCertificateEmployeeTempController.ts +++ b/src/controllers/ProfileCertificateEmployeeTempController.ts @@ -121,7 +121,7 @@ export class ProfileCertificateEmployeeTempController extends Controller { await this.certificateHistoryRepo.save(history, { data: req }); setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{certificateId}") diff --git a/src/controllers/ProfileChildrenController.ts b/src/controllers/ProfileChildrenController.ts index 205352d1..27075758 100644 --- a/src/controllers/ProfileChildrenController.ts +++ b/src/controllers/ProfileChildrenController.ts @@ -104,7 +104,7 @@ export class ProfileChildrenController extends Controller { await this.childrenHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{childrenId}") diff --git a/src/controllers/ProfileChildrenEmployeeController.ts b/src/controllers/ProfileChildrenEmployeeController.ts index 1d4f46d6..a8792e7b 100644 --- a/src/controllers/ProfileChildrenEmployeeController.ts +++ b/src/controllers/ProfileChildrenEmployeeController.ts @@ -111,7 +111,8 @@ export class ProfileChildrenEmployeeController extends Controller { history.profileChildrenId = data.id; await this.childrenHistoryRepository.save(history, { data: req }); setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + + return new HttpSuccess(data.id); } @Patch("{childrenId}") diff --git a/src/controllers/ProfileChildrenEmployeeTempController.ts b/src/controllers/ProfileChildrenEmployeeTempController.ts index 874af63c..4ee31e5f 100644 --- a/src/controllers/ProfileChildrenEmployeeTempController.ts +++ b/src/controllers/ProfileChildrenEmployeeTempController.ts @@ -103,7 +103,7 @@ export class ProfileChildrenEmployeeTempController extends Controller { await this.childrenHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{childrenId}") diff --git a/src/controllers/ProfileController.ts b/src/controllers/ProfileController.ts index f9164a43..576d15cd 100644 --- a/src/controllers/ProfileController.ts +++ b/src/controllers/ProfileController.ts @@ -70,6 +70,7 @@ import { ProfileFamilyCoupleHistory } from "../entities/ProfileFamilyCoupleHisto import { viewDirector } from "../entities/view/viewDirector"; import { viewDirectorActing } from "../entities/view/viewDirectorActing"; import CallAPI from "../interfaces/call-api"; +import { OrgRoot } from "../entities/OrgRoot"; @Route("api/v1/org/profile") @Tags("Profile") @Security("bearerAuth") @@ -80,6 +81,7 @@ import CallAPI from "../interfaces/call-api"; @SuccessResponse(HttpStatus.OK, "สำเร็จ") export class ProfileController extends Controller { private orgRevisionRepo = AppDataSource.getRepository(OrgRevision); + private orgRootRepo = AppDataSource.getRepository(OrgRoot); private posMasterRepo = AppDataSource.getRepository(PosMaster); private profileRepo = AppDataSource.getRepository(Profile); private profileEmpRepo = AppDataSource.getRepository(ProfileEmployee); @@ -1654,6 +1656,204 @@ export class ProfileController extends Controller { return new HttpSuccess({ data: lists, total }); } } + /** + * + * + */ + @Post("commander-director-position") + async getProfileCommanderDirectorPosition( + @Request() request: RequestWithUser, + @Body() + body: { + isAct: boolean; + isDirector: boolean; + keyword: string; + page: number; + pageSize: number; + profileId: string; + }, + ) { + let posMaster = await this.posMasterRepo.findOne({ + where: { + current_holderId: body.profileId, + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + }, + relations: ["current_holder", "current_holder.posLevel"], + }); + if (!posMaster) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลการครองตำแหน่ง"); + if ((posMaster?.current_holder?.posLevel?.posLevelAuthority ?? null) == "DEPUTY") { + posMaster = await this.posMasterRepo.findOne({ + where: { + orgRoot: { isDeputy: true }, + orgChild1Id: IsNull(), + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + }, + }); + return new HttpSuccess({ data: [], total: 0 }); + } else if ((posMaster?.current_holder?.posLevel?.posLevelAuthority ?? null) == "GOVERNOR") { + return new HttpSuccess({ data: [], total: 0 }); + } + let condition: any = { + orgRootId: posMaster.orgRootId, + id: Not(posMaster.current_holderId || ""), + }; + let conditionNow: any = { + orgRootId: posMaster.orgRootId ?? IsNull(), + orgChild1Id: posMaster.orgChild1Id ?? IsNull(), + orgChild2Id: posMaster.orgChild2Id ?? IsNull(), + orgChild3Id: posMaster.orgChild3Id ?? IsNull(), + orgChild4Id: posMaster.orgChild4Id ?? IsNull(), + id: Not(posMaster.current_holderId), + }; + if ( + posMaster.orgRootId == null || + posMaster.orgChild1Id == null || + posMaster.orgChild2Id == null + ) { + condition.orgChild1Id = IsNull(); + } else if (posMaster.orgChild3Id == null) { + condition.orgChild2Id = IsNull(); + } else if (posMaster.orgChild4Id == null) { + condition.orgChild3Id = IsNull(); + } else if (posMaster.orgChild4Id != null) { + condition.orgChild4Id = IsNull(); + } + if (body.isDirector == true) { + condition.isDirector = true; + conditionNow.isDirector = true; + } + console.log(condition); + console.log(conditionNow); + if (body.isAct == true) { + const [lists, total] = await AppDataSource.getRepository(viewDirectorActing) + .createQueryBuilder("viewDirectorActing") + .andWhere( + new Brackets((qb) => { + qb.orWhere(condition).orWhere(conditionNow); + }), + ) + .andWhere( + new Brackets((qb) => { + qb.orWhere( + body.keyword != null && body.keyword != "" + ? "CONCAT(viewDirectorActing.prefix,viewDirectorActing.firstName,' ',viewDirectorActing.lastName) LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "viewDirectorActing.position LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "viewDirectorActing.actFullName LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "CONCAT(viewDirectorActing.posType, ' (', viewDirectorActing.posLevel, ')') LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "viewDirectorActing.posNo LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "viewDirectorActing.citizenId LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ); + }), + ) + .skip((body.page - 1) * body.pageSize) + .take(body.pageSize) + .getManyAndCount(); + return new HttpSuccess({ data: lists, total }); + } else { + const [lists, total] = await AppDataSource.getRepository(viewDirector) + .createQueryBuilder("viewDirector") + .andWhere( + new Brackets((qb) => { + qb.orWhere(condition).orWhere(conditionNow); + }), + ) + .andWhere( + new Brackets((qb) => { + qb.orWhere( + body.keyword != null && body.keyword != "" + ? "CONCAT(viewDirector.prefix,viewDirector.firstName,' ',viewDirector.lastName) LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "viewDirector.position LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "viewDirector.actFullName LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "CONCAT(viewDirector.posType, ' (', viewDirector.posLevel, ')') LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "viewDirector.posNo LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "viewDirector.citizenId LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ); + }), + ) + .skip((body.page - 1) * body.pageSize) + .take(body.pageSize) + .getManyAndCount(); + return new HttpSuccess({ data: lists, total }); + } + } /** * API เลือกผู้ประเมินสำหรับ User (ADMIN) @@ -4036,9 +4236,7 @@ export class ProfileController extends Controller { @Query() yearLeave?: number, @Query() isProbation?: boolean, @Query() isRetire?: boolean, - @Query() node?: number, @Query() nodeId?: string, - @Query() isAll?: boolean, ) { let queryLike = "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword"; @@ -4057,30 +4255,32 @@ export class ProfileController extends Controller { END LIKE :keyword `; } - let nodeCondition = "1=1"; - let nodeAll = ""; - if (node === 0 && nodeId) { - nodeCondition = "current_holders.orgRootId = :nodeId"; - if (isAll == false) nodeAll = " AND current_holders.orgChild1Id IS NULL"; - } else if (node === 1 && nodeId) { - nodeCondition = "current_holders.orgChild1Id = :nodeId"; - if (isAll == false) nodeAll = " AND current_holders.orgChild2Id IS NULL"; - } else if (node === 2 && nodeId) { - nodeCondition = "current_holders.orgChild2Id = :nodeId"; - if (isAll == false) nodeAll = " AND current_holders.orgChild3Id IS NULL"; - } else if (node === 3 && nodeId) { - nodeCondition = "current_holders.orgChild3Id = :nodeId"; - if (isAll == false) nodeAll = " AND current_holders.orgChild4Id IS NULL"; - } else if (node === 4 && nodeId) { - nodeCondition = "current_holders.orgChild4Id = :nodeId"; - } - nodeCondition = nodeCondition + nodeAll; - const findRevision = await this.orgRevisionRepo.findOne({ - where: { orgRevisionIsCurrent: true }, + let posMaster = await this.posMasterRepo.findOne({ + where: { + current_holder: { keycloak: request.user.sub }, + orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, + }, }); - if (!findRevision) { - throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + let revisionId = ""; + if (nodeId == null) { + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + if (!findRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + } + revisionId = findRevision.id; + if (posMaster != null) nodeId = posMaster.orgRootId ?? ""; + } else { + const findRoot = await this.orgRootRepo.findOne({ + where: { id: nodeId }, + }); + if (!findRoot) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบสำนักงานนี้ในระบบ"); + } + revisionId = findRoot.orgRevisionId; } + let nodeCondition = "current_holders.orgRootId = :nodeId"; const [record, total] = await this.profileRepo .createQueryBuilder("profile") .leftJoinAndSelect("profile.posLevel", "posLevel") @@ -4094,7 +4294,7 @@ export class ProfileController extends Controller { .leftJoinAndSelect("current_holders.orgChild2", "orgChild2") .leftJoinAndSelect("current_holders.orgChild3", "orgChild3") .leftJoinAndSelect("current_holders.orgChild4", "orgChild4") - .where("current_holders.orgRevisionId = :orgRevisionId", { orgRevisionId: findRevision.id }) + .where("current_holders.orgRevisionId = :orgRevisionId", { orgRevisionId: revisionId }) .andWhere( posType != undefined && posType != null && posType != "" ? "posType.posTypeName LIKE :keyword1" @@ -4135,7 +4335,7 @@ export class ProfileController extends Controller { nodeId: nodeId, }) // .andWhere(`current_holders.orgRevisionId LIKE :orgRevisionId`, { - // orgRevisionId: findRevision.id, + // orgRevisionId: revisionId, // }) .orderBy("current_holders.posMasterNo", "ASC") .skip((page - 1) * pageSize) @@ -4146,80 +4346,77 @@ export class ProfileController extends Controller { record.map((_data) => { const posExecutive = _data.current_holders.length == 0 || - _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null || - _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions.length == - 0 || + _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.positions.length == 0 || _data.current_holders - .find((x) => x.orgRevisionId == findRevision.id) + .find((x) => x.orgRevisionId == revisionId) ?.positions.find((x: any) => x.positionIsSelected == true) == null || _data.current_holders - .find((x) => x.orgRevisionId == findRevision.id) + .find((x) => x.orgRevisionId == revisionId) ?.positions.find((x: any) => x.positionIsSelected == true)?.posExecutive == null ? null : _data.current_holders - .find((x) => x.orgRevisionId == findRevision.id) + .find((x) => x.orgRevisionId == revisionId) ?.positions.find((x: any) => x.positionIsSelected == true)?.posExecutive ?.posExecutiveName; 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}` + : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null && + _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 != null + ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4.orgChild4ShortName}${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}` + : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null && + _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 != + null + ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3.orgChild3ShortName}${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}` + : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null && + _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 != + null + ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2.orgChild2ShortName}${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}` + : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null && + _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 != + null + ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1.orgChild1ShortName}${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}` + : _data.current_holders.find((x) => x.orgRevisionId == revisionId) != null && + _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot != + null + ? `${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot.orgRootShortName}${_data.current_holders.find((x) => x.orgRevisionId == revisionId)?.posMasterNo}` : null; 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) + (_data.current_holders.find((x) => x.orgRevisionId == revisionId) != null && + _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null) ? null - : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot; + : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot; const child1 = _data.current_holders == null || _data.current_holders.length == 0 || - _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null + _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null ? null - : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1; + : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1; const child2 = _data.current_holders == null || _data.current_holders.length == 0 || - _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null + _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null ? null - : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2; + : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2; const child3 = _data.current_holders == null || _data.current_holders.length == 0 || - _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null + _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null ? null - : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3; + : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3; const child4 = _data.current_holders == null || _data.current_holders.length == 0 || - _data.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null + _data.current_holders.find((x) => x.orgRevisionId == revisionId) == null ? null - : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4; + : _data.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4; let _child1 = child1 == null ? "" : `${child1.orgChild1Name}/`; let _child2 = child2 == null ? "" : `${child2.orgChild2Name}/`; @@ -4649,10 +4846,10 @@ export class ProfileController extends Controller { ? null : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4; - let _child1 = child1 == null ? "" : `${child1.orgChild1Name}/`; - let _child2 = child2 == null ? "" : `${child2.orgChild2Name}/`; - let _child3 = child3 == null ? "" : `${child3.orgChild3Name}/`; - let _child4 = child4 == null ? "" : `${child4.orgChild4Name}/`; + let _child1 = child1 == null ? "" : `${child1.orgChild1Name} `; + let _child2 = child2 == null ? "" : `${child2.orgChild2Name} `; + let _child3 = child3 == null ? "" : `${child3.orgChild3Name} `; + let _child4 = child4 == null ? "" : `${child4.orgChild4Name} `; return { id: _data.id, @@ -4928,7 +5125,7 @@ export class ProfileController extends Controller { requestBody.position != null && requestBody.position !== "" ? "positions.positionName LIKE :positionName" : "1=1", - { positionName: `${requestBody.position}` }, + { positionName: `%${requestBody.position}%` }, ) .getMany(); @@ -5125,18 +5322,23 @@ export class ProfileController extends Controller { posExecutiveId: position == null || position.posExecutive == null ? null : position.posExecutive.id, rootId: root == null ? null : root.id, + rootDnaId: root == null ? null : root.ancestorDNA, root: root == null ? null : root.orgRootName, rootShortName: root == null ? null : root.orgRootShortName, child1Id: child1 == null ? null : child1.id, + child1DnaId: child1 == null ? null : child1.ancestorDNA, child1: child1 == null ? null : child1.orgChild1Name, child1ShortName: child1 == null ? null : child1.orgChild1ShortName, child2Id: child2 == null ? null : child2.id, + child2DnaId: child2 == null ? null : child2.ancestorDNA, child2: child2 == null ? null : child2.orgChild2Name, child2ShortName: child2 == null ? null : child2.orgChild2ShortName, child3Id: child3 == null ? null : child3.id, + child3DnaId: child3 == null ? null : child3.ancestorDNA, child3: child3 == null ? null : child3.orgChild3Name, child3ShortName: child3 == null ? null : child3.orgChild3ShortName, child4Id: child4 == null ? null : child4.id, + child4DnaId: child4 == null ? null : child4.ancestorDNA, child4: child4 == null ? null : child4.orgChild4Name, child4ShortName: child4 == null ? null : child4.orgChild4ShortName, node: null, @@ -5271,18 +5473,23 @@ export class ProfileController extends Controller { posExecutiveId: position == null || position.posExecutive == null ? null : position.posExecutive.id, rootId: root == null ? null : root.id, + rootDnaId: root == null ? null : root.ancestorDNA, root: root == null ? null : root.orgRootName, rootShortName: root == null ? null : root.orgRootShortName, child1Id: child1 == null ? null : child1.id, + child1DnaId: child1 == null ? null : child1.ancestorDNA, child1: child1 == null ? null : child1.orgChild1Name, child1ShortName: child1 == null ? null : child1.orgChild1ShortName, child2Id: child2 == null ? null : child2.id, + child2DnaId: child2 == null ? null : child2.ancestorDNA, child2: child2 == null ? null : child2.orgChild2Name, child2ShortName: child2 == null ? null : child2.orgChild2ShortName, child3Id: child3 == null ? null : child3.id, + child3DnaId: child3 == null ? null : child3.ancestorDNA, child3: child3 == null ? null : child3.orgChild3Name, child3ShortName: child3 == null ? null : child3.orgChild3ShortName, child4Id: child4 == null ? null : child4.id, + child4DnaId: child4 == null ? null : child4.ancestorDNA, child4: child4 == null ? null : child4.orgChild4Name, child4ShortName: child4 == null ? null : child4.orgChild4ShortName, node: null, @@ -5502,7 +5709,7 @@ export class ProfileController extends Controller { : posMaster_.orgChild1.orgChild1Name, posMaster_ == null || posMaster_.orgRoot == null ? null : posMaster_.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); //find commander(ผู้บังคับบัญชา) let node = 4; @@ -5707,7 +5914,7 @@ export class ProfileController extends Controller { ]; commanderOrg_ = commanderFullNameParts .filter((part) => part !== undefined && part !== null) - .join("/"); + .join(" "); const commandAboveProfile = await this.profileRepo.findOne({ where: { id: String(commandAboveProfileId) }, @@ -5755,7 +5962,7 @@ export class ProfileController extends Controller { ]; commanderAboveOrg_ = commanderAboveFullNameParts .filter((part) => part !== undefined && part !== null) - .join("/"); + .join(" "); const _profile: any = { profileId: profile.id, @@ -7338,6 +7545,7 @@ export class ProfileController extends Controller { .orWhere(conditionFullName, { keyword: `%${body.keyword}%`, }) + .andWhere("profile.isLeave = false") .orderBy("profile.citizenId", "ASC") .skip((body.page - 1) * body.pageSize) .take(body.pageSize) @@ -7530,11 +7738,12 @@ export class ProfileController extends Controller { .where((qb) => { if (body.rootId) { qb.andWhere("posMaster.orgRootId = :rootId", { rootId: body.rootId }); + } else { + qb.andWhere("posMaster.orgRevisionId = :orgRevisionId", { + orgRevisionId: findRevision?.id, + }); } qb.andWhere("posMaster.current_holderId IS NOT NULL"); - qb.andWhere("posMaster.orgRevisionId = :orgRevisionId", { - orgRevisionId: findRevision?.id, - }); }) .andWhere( new Brackets((qb) => { @@ -8082,6 +8291,7 @@ export class ProfileController extends Controller { if (requestBody.isLeave == true) { await removeProfileInOrganize(profile.id, "OFFICER"); } + profile.leaveType = "RETIRE_DECEASED"; await this.profileRepo.save(profile, { data: request }); setLogDataDiff(request, { before, after: profile }); diff --git a/src/controllers/ProfileDevelopmentController.ts b/src/controllers/ProfileDevelopmentController.ts index 1d9149dd..754b8de1 100644 --- a/src/controllers/ProfileDevelopmentController.ts +++ b/src/controllers/ProfileDevelopmentController.ts @@ -127,23 +127,18 @@ export class ProfileDevelopmentController extends Controller { public async developmentDetail( @Path() developmentId: string, @Path() type: string, - @Request() req: RequestWithUser + @Request() req: RequestWithUser, ) { const data = await this.developmentRequestRepository.findOne({ where: { id: developmentId }, relations: ["developmentProjects"], }); - if (!data) - throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบรายการพัฒนารายบุคคลดังกล่าว"); + if (!data) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบรายการพัฒนารายบุคคลดังกล่าว"); if (type.trim().toLocaleUpperCase() == "OFFICER") { let _workflow = await new permission().Workflow(req, developmentId, "SYS_REGISTRY_OFFICER"); if (_workflow == false) - await new permission().PermissionOrgUserGet( - req, - "SYS_REGISTRY_OFFICER", - data.profileId, - ); + await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", data.profileId); } else if (type.trim().toLocaleUpperCase() == "EMPLOYEE") { let _workflow = await new permission().Workflow(req, developmentId, "SYS_REGISTRY_EMP"); if (_workflow == false) @@ -183,8 +178,8 @@ export class ProfileDevelopmentController extends Controller { reasonDevelopment10: data.reasonDevelopment10, selectType: null, selectTypeYear: null, - selectTypeId: null - } + selectTypeId: null, + }; const _data = { ..._mapData, developmentProjects: data.developmentProjects.map((x) => x.name), @@ -249,7 +244,7 @@ export class ProfileDevelopmentController extends Controller { ); } - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{developmentId}") diff --git a/src/controllers/ProfileDevelopmentEmployeeController.ts b/src/controllers/ProfileDevelopmentEmployeeController.ts index 025740e4..5843cee5 100644 --- a/src/controllers/ProfileDevelopmentEmployeeController.ts +++ b/src/controllers/ProfileDevelopmentEmployeeController.ts @@ -135,7 +135,7 @@ export class ProfileDevelopmentEmployeeController extends Controller { ); } - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{developmentId}") diff --git a/src/controllers/ProfileDevelopmentEmployeeTempController.ts b/src/controllers/ProfileDevelopmentEmployeeTempController.ts index 768fd87e..84cfa074 100644 --- a/src/controllers/ProfileDevelopmentEmployeeTempController.ts +++ b/src/controllers/ProfileDevelopmentEmployeeTempController.ts @@ -127,7 +127,7 @@ export class ProfileDevelopmentEmployeeTempController extends Controller { ); } - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{developmentId}") diff --git a/src/controllers/ProfileDisciplineController.ts b/src/controllers/ProfileDisciplineController.ts index e29af310..efcd6444 100644 --- a/src/controllers/ProfileDisciplineController.ts +++ b/src/controllers/ProfileDisciplineController.ts @@ -133,7 +133,7 @@ export class ProfileDisciplineController extends Controller { await this.disciplineHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{disciplineId}") diff --git a/src/controllers/ProfileDisciplineEmployeeController.ts b/src/controllers/ProfileDisciplineEmployeeController.ts index e934e668..d1c11906 100644 --- a/src/controllers/ProfileDisciplineEmployeeController.ts +++ b/src/controllers/ProfileDisciplineEmployeeController.ts @@ -135,7 +135,7 @@ export class ProfileDisciplineEmployeeController extends Controller { history.profileDisciplineId = data.id; await this.disciplineHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{disciplineId}") diff --git a/src/controllers/ProfileDisciplineEmployeeTempController.ts b/src/controllers/ProfileDisciplineEmployeeTempController.ts index b981d567..f6b19d3d 100644 --- a/src/controllers/ProfileDisciplineEmployeeTempController.ts +++ b/src/controllers/ProfileDisciplineEmployeeTempController.ts @@ -128,7 +128,7 @@ export class ProfileDisciplineEmployeeTempController extends Controller { await this.disciplineHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{disciplineId}") diff --git a/src/controllers/ProfileDutyController.ts b/src/controllers/ProfileDutyController.ts index a9b4865c..faed5e72 100644 --- a/src/controllers/ProfileDutyController.ts +++ b/src/controllers/ProfileDutyController.ts @@ -110,7 +110,7 @@ export class ProfileDutyController extends Controller { history.profileDutyId = data.id; await this.dutyHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{dutyId}") diff --git a/src/controllers/ProfileDutyEmployeeController.ts b/src/controllers/ProfileDutyEmployeeController.ts index 2093b375..9974fbc1 100644 --- a/src/controllers/ProfileDutyEmployeeController.ts +++ b/src/controllers/ProfileDutyEmployeeController.ts @@ -115,7 +115,7 @@ export class ProfileDutyEmployeeController extends Controller { await this.dutyHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{dutyId}") diff --git a/src/controllers/ProfileDutyEmployeeTempController.ts b/src/controllers/ProfileDutyEmployeeTempController.ts index 7b199560..3b5223d5 100644 --- a/src/controllers/ProfileDutyEmployeeTempController.ts +++ b/src/controllers/ProfileDutyEmployeeTempController.ts @@ -107,7 +107,7 @@ export class ProfileDutyEmployeeTempController extends Controller { await this.dutyHistoryRepository.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{dutyId}") diff --git a/src/controllers/ProfileEducationsController.ts b/src/controllers/ProfileEducationsController.ts index fe3bd49c..e01c7e30 100644 --- a/src/controllers/ProfileEducationsController.ts +++ b/src/controllers/ProfileEducationsController.ts @@ -145,7 +145,7 @@ export class ProfileEducationsController extends Controller { await this.profileEducationHistoryRepo.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{educationId}") diff --git a/src/controllers/ProfileEducationsEmployeeController.ts b/src/controllers/ProfileEducationsEmployeeController.ts index d152c6af..d181ae96 100644 --- a/src/controllers/ProfileEducationsEmployeeController.ts +++ b/src/controllers/ProfileEducationsEmployeeController.ts @@ -151,7 +151,7 @@ export class ProfileEducationsEmployeeController extends Controller { await this.profileEducationHistoryRepo.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{educationId}") diff --git a/src/controllers/ProfileEducationsEmployeeTempController.ts b/src/controllers/ProfileEducationsEmployeeTempController.ts index 6204e6e6..045e493d 100644 --- a/src/controllers/ProfileEducationsEmployeeTempController.ts +++ b/src/controllers/ProfileEducationsEmployeeTempController.ts @@ -141,7 +141,7 @@ export class ProfileEducationsEmployeeTempController extends Controller { await this.profileEducationHistoryRepo.save(history, { data: req }); //setLogDataDiff(req, { before, after: history }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{educationId}") diff --git a/src/controllers/ProfileEmployeeController.ts b/src/controllers/ProfileEmployeeController.ts index a8dac12d..a4f2121a 100644 --- a/src/controllers/ProfileEmployeeController.ts +++ b/src/controllers/ProfileEmployeeController.ts @@ -1714,10 +1714,10 @@ export class ProfileEmployeeController extends Controller { ? null : _data.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4; - let _child1 = child1 == null ? "" : `${child1.orgChild1Name}/`; - let _child2 = child2 == null ? "" : `${child2.orgChild2Name}/`; - let _child3 = child3 == null ? "" : `${child3.orgChild3Name}/`; - let _child4 = child4 == null ? "" : `${child4.orgChild4Name}/`; + let _child1 = child1 == null ? "" : `${child1.orgChild1Name} `; + let _child2 = child2 == null ? "" : `${child2.orgChild2Name} `; + let _child3 = child3 == null ? "" : `${child3.orgChild3Name} `; + let _child4 = child4 == null ? "" : `${child4.orgChild4Name} `; return { id: _data.id, prefix: _data.prefix, @@ -2069,7 +2069,7 @@ export class ProfileEmployeeController extends Controller { requestBody.position != null && requestBody.position !== "" ? "positions.positionName LIKE :positionName" : "1=1", - { positionName: `${requestBody.position}` }, + { positionName: `%${requestBody.position}%` }, ) .getMany(); @@ -3141,6 +3141,192 @@ export class ProfileEmployeeController extends Controller { return new HttpSuccess({ data: mapDataProfile, total }); } + /** + * API ค้นหาข้อมูลทะเบียนประวัติ เกษียณข้าราชการ + * + * @summary ค้นหาข้อมูลทะเบียนประวัติ เกษียณข้าราชการ (ADMIN) + * + */ + @Post("retire") + async getProfileBySearchKeywordRetire( + @Body() + body: { + page: number; + pageSize: number; + keyword?: string; + }, + ) { + let conditionFullName = + "CONCAT(profileEmployee.prefix, profileEmployee.firstName, ' ', profileEmployee.lastName) LIKE :keyword"; + const [findProfile, total] = await AppDataSource.getRepository(ProfileEmployee) + .createQueryBuilder("profileEmployee") + .leftJoinAndSelect("profileEmployee.posLevel", "posLevel") + .leftJoinAndSelect("profileEmployee.posType", "posType") + .leftJoinAndSelect("profileEmployee.current_holders", "current_holders") + .leftJoinAndSelect("current_holders.orgRevision", "orgRevision") + .leftJoinAndSelect("current_holders.orgRoot", "orgRoot") + .leftJoinAndSelect("current_holders.orgChild1", "orgChild1") + .leftJoinAndSelect("current_holders.orgChild2", "orgChild2") + .leftJoinAndSelect("current_holders.orgChild3", "orgChild3") + .leftJoinAndSelect("current_holders.orgChild4", "orgChild4") + .leftJoinAndSelect("current_holders.positions", "positions") + .where(`profileEmployee.position LIKE :keyword`, { + keyword: `%${body.keyword}%`, + }) + .orWhere(`profileEmployee.prefix LIKE :keyword`, { + keyword: `%${body.keyword}%`, + }) + .orWhere(`profileEmployee.firstName LIKE :keyword`, { + keyword: `%${body.keyword}%`, + }) + .orWhere(`profileEmployee.lastName LIKE :keyword`, { + keyword: `%${body.keyword}%`, + }) + .orWhere(`posLevel.posLevelName LIKE :keyword`, { + keyword: `%${body.keyword}%`, + }) + .orWhere(`posType.posTypeName LIKE :keyword`, { + keyword: `%${body.keyword}%`, + }) + .orWhere(conditionFullName, { + keyword: `%${body.keyword}%`, + }) + .andWhere("profileEmployee.isLeave = false") + .orderBy("profileEmployee.citizenId", "ASC") + .skip((body.page - 1) * body.pageSize) + .take(body.pageSize) + .getManyAndCount(); + + const orgRevisionActive = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }, + }); + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + if (!findRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + } + + const mapDataProfile = await Promise.all( + findProfile.map(async (item: ProfileEmployee) => { + const posMaster = + item.current_holders == null || + item.current_holders.length == 0 || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id); + const position = + posMaster == null || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions == null || + item.current_holders?.find((x) => x.orgRevisionId == findRevision.id)?.positions.length == + 0 || + item.current_holders + .find((x) => x.orgRevisionId == findRevision.id) + ?.positions?.find((position) => position.positionIsSelected == true) == null + ? null + : item.current_holders + .find((x) => x.orgRevisionId == findRevision.id) + ?.positions?.find((position) => position.positionIsSelected == true); + + const shortName = + item.current_holders.length == 0 + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 != + null + ? `${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 { + id: item.id, + prefix: item.prefix, + rank: item.rank, + firstName: item.firstName, + lastName: item.lastName, + position: item.position, + idcard: item.citizenId, + posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName, + posTypeName: item.posType == null ? null : item.posType.posTypeName, + posNo: `${posMaster == null ? null : posMaster.posMasterNo}${shortName}`, + // positionField: position == null ? null : position.positionField, + // positionArea: position == null ? null : position.positionArea, + // posExecutiveName: posExecutive, + // positionExecutiveField: position == null ? null : position.positionExecutiveField, + isProbation: item.isProbation, + orgRootName: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot + ?.orgRootName == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot + ?.orgRootName, + orgChild1Name: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1 == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1 + ?.orgChild1Name == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) + ?.orgChild1?.orgChild1Name, + orgChild2Name: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2 == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2 + ?.orgChild2Name == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) + ?.orgChild2?.orgChild2Name, + orgChild3Name: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3 == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3 + ?.orgChild3Name == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) + ?.orgChild3?.orgChild3Name, + orgChild4Name: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4 == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4 + ?.orgChild4Name == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) + ?.orgChild4?.orgChild4Name, + }; + }), + ); + + return new HttpSuccess({ data: mapDataProfile, total }); + } + /** * API รายชื่อราชการที่เลื่อนเงินเดือน * @@ -3182,11 +3368,12 @@ export class ProfileEmployeeController extends Controller { .where((qb) => { if (body.rootId) { qb.andWhere("employeePosMaster.orgRootId = :rootId", { rootId: body.rootId }); + } else { + qb.andWhere("employeePosMaster.orgRevisionId = :orgRevisionId", { + orgRevisionId: findRevision?.id, + }); } qb.andWhere("employeePosMaster.current_holderId IS NOT NULL"); - qb.andWhere("employeePosMaster.orgRevisionId = :orgRevisionId", { - orgRevisionId: findRevision?.id, - }); }) .andWhere( new Brackets((qb) => { @@ -3684,6 +3871,7 @@ export class ProfileEmployeeController extends Controller { if (requestBody.isLeave == true) { await removeProfileInOrganize(profile.id, "EMPLOYEE"); } + profile.leaveType = "RETIRE_DECEASED"; await this.profileRepo.save(profile); return new HttpSuccess(); diff --git a/src/controllers/ProfileEmployeeTempController.ts b/src/controllers/ProfileEmployeeTempController.ts index bc0e37b9..f4bc3cba 100644 --- a/src/controllers/ProfileEmployeeTempController.ts +++ b/src/controllers/ProfileEmployeeTempController.ts @@ -2686,11 +2686,12 @@ export class ProfileEmployeeTempController extends Controller { .where((qb) => { if (body.rootId) { qb.andWhere("employeePosMaster.orgRootId = :rootId", { rootId: body.rootId }); + } else { + qb.andWhere("employeePosMaster.orgRevisionId = :orgRevisionId", { + orgRevisionId: findRevision?.id, + }); } qb.andWhere("employeePosMaster.current_holderId IS NOT NULL"); - qb.andWhere("employeePosMaster.orgRevisionId = :orgRevisionId", { - orgRevisionId: findRevision?.id, - }); }) .andWhere( new Brackets((qb) => { diff --git a/src/controllers/ProfileGovernmentController.ts b/src/controllers/ProfileGovernmentController.ts index 10958196..b1abb860 100644 --- a/src/controllers/ProfileGovernmentController.ts +++ b/src/controllers/ProfileGovernmentController.ts @@ -8,7 +8,12 @@ import { Profile } from "../entities/Profile"; import { ProfileGovernment, UpdateProfileGovernment } from "../entities/ProfileGovernment"; import { Position } from "../entities/Position"; import { PosMaster } from "../entities/PosMaster"; -import { calculateAge, calculateGovAge, calculateRetireDate, setLogDataDiff } from "../interfaces/utils"; +import { + calculateAge, + calculateGovAge, + calculateRetireDate, + setLogDataDiff, +} from "../interfaces/utils"; import permission from "../interfaces/permission"; import { OrgRevision } from "../entities/OrgRevision"; @Route("api/v1/org/profile/government") @@ -89,7 +94,7 @@ export class ProfileGovernmentHistoryController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { @@ -120,7 +125,7 @@ export class ProfileGovernmentHistoryController extends Controller { dateLeave: record.birthDate == null ? null : calculateRetireDate(record.birthDate), dateRetireLaw: record.dateRetireLaw ?? null, // govAge: record.dateStart == null ? null : calculateAge(record.dateStart), - govAge: await calculateGovAge(profile.id,"OFFICER"), + govAge: await calculateGovAge(profile.id, "OFFICER"), dateAppoint: record.dateAppoint, dateStart: record.dateStart, govAgeAbsent: record.govAgeAbsent, @@ -200,7 +205,7 @@ export class ProfileGovernmentHistoryController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { @@ -231,7 +236,7 @@ export class ProfileGovernmentHistoryController extends Controller { dateLeave: record.birthDate == null ? null : calculateRetireDate(record.birthDate), dateRetireLaw: record.dateRetireLaw ?? null, // govAge: record.dateStart == null ? null : calculateAge(record.dateStart), - govAge: await calculateGovAge(profileId,"OFFICER"), + govAge: await calculateGovAge(profileId, "OFFICER"), dateAppoint: record.dateAppoint, dateStart: record.dateStart, govAgeAbsent: record.govAgeAbsent, @@ -294,7 +299,7 @@ export class ProfileGovernmentHistoryController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { @@ -325,7 +330,7 @@ export class ProfileGovernmentHistoryController extends Controller { dateLeave: record.birthDate == null ? null : calculateRetireDate(record.birthDate), dateRetireLaw: record.dateRetireLaw ?? null, // govAge: record.dateStart == null ? null : calculateAge(record.dateStart), - govAge: await calculateGovAge(profileId,"OFFICER"), + govAge: await calculateGovAge(profileId, "OFFICER"), dateAppoint: record.dateAppoint, dateStart: record.dateStart, govAgeAbsent: record.govAgeAbsent, diff --git a/src/controllers/ProfileGovernmentEmployeeController.ts b/src/controllers/ProfileGovernmentEmployeeController.ts index 626149f0..d8db83ed 100644 --- a/src/controllers/ProfileGovernmentEmployeeController.ts +++ b/src/controllers/ProfileGovernmentEmployeeController.ts @@ -90,7 +90,7 @@ export class ProfileGovernmentEmployeeController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { @@ -194,7 +194,7 @@ export class ProfileGovernmentEmployeeController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { @@ -281,7 +281,7 @@ export class ProfileGovernmentEmployeeController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { diff --git a/src/controllers/ProfileGovernmentEmployeeTempController.ts b/src/controllers/ProfileGovernmentEmployeeTempController.ts index 6facd5b0..7f72241a 100644 --- a/src/controllers/ProfileGovernmentEmployeeTempController.ts +++ b/src/controllers/ProfileGovernmentEmployeeTempController.ts @@ -85,7 +85,7 @@ export class ProfileGovernmentEmployeeTempController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { @@ -184,7 +184,7 @@ export class ProfileGovernmentEmployeeTempController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { @@ -271,7 +271,7 @@ export class ProfileGovernmentEmployeeTempController extends Controller { posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, ]; - const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join(" "); let orgShortName = ""; if (posMaster != null) { if (posMaster.orgChild1Id === null) { diff --git a/src/controllers/ProfileHonorController.ts b/src/controllers/ProfileHonorController.ts index 536161f9..82348c1c 100644 --- a/src/controllers/ProfileHonorController.ts +++ b/src/controllers/ProfileHonorController.ts @@ -137,7 +137,7 @@ export class ProfileHonorController extends Controller { history.profileHonorId = data.id; await this.honorHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{honorId}") diff --git a/src/controllers/ProfileHonorEmployeeController.ts b/src/controllers/ProfileHonorEmployeeController.ts index 1d6928ab..34bae5f0 100644 --- a/src/controllers/ProfileHonorEmployeeController.ts +++ b/src/controllers/ProfileHonorEmployeeController.ts @@ -145,7 +145,7 @@ export class ProfileHonorEmployeeController extends Controller { history.profileHonorId = data.id; await this.honorHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{honorId}") diff --git a/src/controllers/ProfileHonorEmployeeTempController.ts b/src/controllers/ProfileHonorEmployeeTempController.ts index fb14c035..deea0a2a 100644 --- a/src/controllers/ProfileHonorEmployeeTempController.ts +++ b/src/controllers/ProfileHonorEmployeeTempController.ts @@ -136,7 +136,7 @@ export class ProfileHonorEmployeeTempController extends Controller { history.profileHonorId = data.id; await this.honorHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{honorId}") diff --git a/src/controllers/ProfileInsigniaController.ts b/src/controllers/ProfileInsigniaController.ts index 852de8ec..131b5d52 100644 --- a/src/controllers/ProfileInsigniaController.ts +++ b/src/controllers/ProfileInsigniaController.ts @@ -150,7 +150,7 @@ export class ProfileInsigniaController extends Controller { history.profileInsigniaId = data.id; await this.insigniaHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{insigniaId}") diff --git a/src/controllers/ProfileInsigniaEmployeeController.ts b/src/controllers/ProfileInsigniaEmployeeController.ts index 6db83733..455e443d 100644 --- a/src/controllers/ProfileInsigniaEmployeeController.ts +++ b/src/controllers/ProfileInsigniaEmployeeController.ts @@ -157,7 +157,7 @@ export class ProfileInsigniaEmployeeController extends Controller { history.profileInsigniaId = data.id; await this.insigniaHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{insigniaId}") diff --git a/src/controllers/ProfileInsigniaEmployeeTempController.ts b/src/controllers/ProfileInsigniaEmployeeTempController.ts index 7c353273..d12ed3ab 100644 --- a/src/controllers/ProfileInsigniaEmployeeTempController.ts +++ b/src/controllers/ProfileInsigniaEmployeeTempController.ts @@ -149,7 +149,7 @@ export class ProfileInsigniaEmployeeTempController extends Controller { history.profileInsigniaId = data.id; await this.insigniaHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{insigniaId}") diff --git a/src/controllers/ProfileLeaveController.ts b/src/controllers/ProfileLeaveController.ts index 80fcef9f..ae7bcfe3 100644 --- a/src/controllers/ProfileLeaveController.ts +++ b/src/controllers/ProfileLeaveController.ts @@ -215,7 +215,7 @@ export class ProfileLeaveController extends Controller { history.profileLeaveId = data.id; await this.leaveHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{leaveId}") diff --git a/src/controllers/ProfileLeaveEmployeeController.ts b/src/controllers/ProfileLeaveEmployeeController.ts index f3c010de..feb6891e 100644 --- a/src/controllers/ProfileLeaveEmployeeController.ts +++ b/src/controllers/ProfileLeaveEmployeeController.ts @@ -143,7 +143,7 @@ export class ProfileLeaveEmployeeController extends Controller { history.profileLeaveId = data.id; await this.leaveHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{leaveId}") diff --git a/src/controllers/ProfileLeaveEmployeeTempController.ts b/src/controllers/ProfileLeaveEmployeeTempController.ts index 28d6a621..39506d32 100644 --- a/src/controllers/ProfileLeaveEmployeeTempController.ts +++ b/src/controllers/ProfileLeaveEmployeeTempController.ts @@ -133,7 +133,7 @@ export class ProfileLeaveEmployeeTempController extends Controller { history.profileLeaveId = data.id; await this.leaveHistoryRepo.save(history); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{leaveId}") diff --git a/src/controllers/ProfileNopaidController.ts b/src/controllers/ProfileNopaidController.ts index ecd4fc9d..6bc26043 100644 --- a/src/controllers/ProfileNopaidController.ts +++ b/src/controllers/ProfileNopaidController.ts @@ -101,7 +101,7 @@ export class ProfileNopaidController extends Controller { history.profileNopaidId = data.id; await this.nopaidHistoryRepository.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{nopaidId}") diff --git a/src/controllers/ProfileNopaidEmployeeController.ts b/src/controllers/ProfileNopaidEmployeeController.ts index 7f5eb3af..f7d506b4 100644 --- a/src/controllers/ProfileNopaidEmployeeController.ts +++ b/src/controllers/ProfileNopaidEmployeeController.ts @@ -103,7 +103,7 @@ export class ProfileNopaidEmployeeController extends Controller { history.profileNopaidId = data.id; await this.nopaidHistoryRepository.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{nopaidId}") diff --git a/src/controllers/ProfileNopaidEmployeeTempController.ts b/src/controllers/ProfileNopaidEmployeeTempController.ts index fca6b1c7..8ff058ec 100644 --- a/src/controllers/ProfileNopaidEmployeeTempController.ts +++ b/src/controllers/ProfileNopaidEmployeeTempController.ts @@ -104,7 +104,7 @@ export class ProfileNopaidEmployeeTempController extends Controller { history.profileNopaidId = data.id; await this.nopaidHistoryRepository.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{nopaidId}") diff --git a/src/controllers/ProfileOtherController.ts b/src/controllers/ProfileOtherController.ts index cf988fd6..79ae8c8f 100644 --- a/src/controllers/ProfileOtherController.ts +++ b/src/controllers/ProfileOtherController.ts @@ -111,7 +111,7 @@ export class ProfileOtherController extends Controller { history.profileOtherId = data.id; await this.otherHistoryRepository.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{otherId}") diff --git a/src/controllers/ProfileOtherEmployeeController.ts b/src/controllers/ProfileOtherEmployeeController.ts index a17ec51a..0a6622b6 100644 --- a/src/controllers/ProfileOtherEmployeeController.ts +++ b/src/controllers/ProfileOtherEmployeeController.ts @@ -118,7 +118,7 @@ export class ProfileOtherEmployeeController extends Controller { history.profileOtherId = data.id; await this.otherHistoryRepository.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{otherId}") diff --git a/src/controllers/ProfileOtherEmployeeTempController.ts b/src/controllers/ProfileOtherEmployeeTempController.ts index f56287e6..38962384 100644 --- a/src/controllers/ProfileOtherEmployeeTempController.ts +++ b/src/controllers/ProfileOtherEmployeeTempController.ts @@ -110,7 +110,7 @@ export class ProfileOtherEmployeeTempController extends Controller { history.profileOtherId = data.id; await this.otherHistoryRepository.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{otherId}") diff --git a/src/controllers/ProfileTrainingController.ts b/src/controllers/ProfileTrainingController.ts index 0e67a061..c331fdb9 100644 --- a/src/controllers/ProfileTrainingController.ts +++ b/src/controllers/ProfileTrainingController.ts @@ -118,7 +118,7 @@ export class ProfileTrainingController extends Controller { history.profileTrainingId = data.id; await this.trainingHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{trainingId}") diff --git a/src/controllers/ProfileTrainingEmployeeController.ts b/src/controllers/ProfileTrainingEmployeeController.ts index 66f5ebb8..60f1c2ac 100644 --- a/src/controllers/ProfileTrainingEmployeeController.ts +++ b/src/controllers/ProfileTrainingEmployeeController.ts @@ -126,7 +126,7 @@ export class ProfileTrainingEmployeeController extends Controller { history.profileTrainingId = data.id; await this.trainingHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{trainingId}") diff --git a/src/controllers/ProfileTrainingEmployeeTempController.ts b/src/controllers/ProfileTrainingEmployeeTempController.ts index 10894d4a..64e6fdcd 100644 --- a/src/controllers/ProfileTrainingEmployeeTempController.ts +++ b/src/controllers/ProfileTrainingEmployeeTempController.ts @@ -117,7 +117,7 @@ export class ProfileTrainingEmployeeTempController extends Controller { history.profileTrainingId = data.id; await this.trainingHistoryRepo.save(history, { data: req }); - return new HttpSuccess(); + return new HttpSuccess(data.id); } @Patch("{trainingId}") diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index 0a3dd02d..cba039c9 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -30,6 +30,7 @@ import { getRoleMappings, getUserCount, enableStatus, + getUserByUsername, } from "../keycloak"; import { AppDataSource } from "../database/data-source"; import { Profile } from "../entities/Profile"; @@ -96,15 +97,21 @@ export class KeycloakController extends Controller { profileId?: string; }, ) { - const userId = await createUser(body.username, body.password, { - firstName: body.firstName, - lastName: body.lastName, - // email: body.email, - }); - - if (typeof userId !== "string") { - throw new Error(userId.errorMessage); + const checkUser = await getUserByUsername(body.username); + let userId: any = ""; + if (checkUser.length == 0) { + userId = await createUser(body.username, body.password, { + firstName: body.firstName, + lastName: body.lastName, + // email: body.email, + }); + 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 result = await addUserRoles( @@ -647,6 +654,78 @@ export class KeycloakController extends Controller { } } + @Post("user/emp") + @Security("bearerAuth", ["system", "admin"]) + async createUserEmp( + @Request() request: { user: { sub: string; preferred_username: string } }, + @Body() + body: { + username: string; + password: string; + firstName?: string; + lastName?: string; + email?: string; + roles: string[]; + profileId?: string; + }, + ) { + const checkUser = await getUserByUsername(body.username); + let userId: any = ""; + if (checkUser.length == 0) { + userId = await createUser(body.username, body.password, { + firstName: body.firstName, + lastName: body.lastName, + // email: body.email, + }); + 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 result = await addUserRoles( + userId, + list.filter((v) => body.roles.includes(v.id)), + ); + + if (!result) { + throw new Error("Failed. Cannot set user's role."); + } + const profile = await this.profileEmpRepo.findOne({ + where: { + id: body.profileId, + }, + }); + + if (profile) { + let _null: any = null; + if (typeof userId === "string") { + profile.keycloak = userId; + } + profile.email = body.email == null ? _null : body.email; + await this.profileEmpRepo.save(profile); + if (body.roles != null && body.roles.length > 0) { + const roleKeycloak = await this.roleKeycloakRepo.find({ + where: { id: In(body.roles) }, + }); + const _profile = await this.profileEmpRepo.findOne({ + where: { keycloak: userId }, + relations: ["roleKeycloaks"], + }); + if (_profile) { + _profile.roleKeycloaks = Array.from( + new Set([..._profile.roleKeycloaks, ...roleKeycloak]), + ); + this.profileEmpRepo.save(_profile); + } + } + } + return userId; + } + @Delete("group/{groupId}") async deleteGroup(@Path() groupId: string) { const result = await deleteGroup(groupId); @@ -693,6 +772,24 @@ export class KeycloakController extends Controller { return profile.roleKeycloaks; } + @Get("user/username/{citizenId}") + async getUserByUsername(@Path("citizenId") citizenId: string) { + const userData = await getUserByUsername(citizenId); + if (!userData || userData.length == 0) { + throw new Error("User not found"); + } + const rolesData = await getRoleMappings(userData[0].id); + if (!rolesData) { + throw new Error("Role mappings not found"); + } + const userDataWithRoles = { + ...userData, + roles: rolesData, + }; + + return userDataWithRoles; + } + @Put("user/{userId}/enableStatus/{status}") //#log? async changeEnableStatus(@Path() userId: string, @Path() status: boolean) { const profile = await this.profileRepo.findOne({ diff --git a/src/controllers/WorkflowController.ts b/src/controllers/WorkflowController.ts index a26cf3e5..48cf63b5 100644 --- a/src/controllers/WorkflowController.ts +++ b/src/controllers/WorkflowController.ts @@ -815,6 +815,13 @@ export class WorkflowController extends Controller { let condition: any = { isDirector: true, orgRootId: posMasterUser.orgRootId, + orgRevisionId: posMasterUser.orgRevisionId, + }; + + let conditionOfficer: any = { + isDirector: true, + isOfficer: true, + orgRevisionId: posMasterUser.orgRevisionId, }; if (type.trim().toUpperCase() == "OPERATE") { @@ -832,6 +839,7 @@ export class WorkflowController extends Controller { condition = { isDirector: true, orgRootId: posMasterUser.orgRootId, + orgRevisionId: posMasterUser.orgRevisionId, orgChild1Id: IsNull(), orgChild2Id: IsNull(), orgChild3Id: IsNull(), @@ -848,6 +856,7 @@ export class WorkflowController extends Controller { condition = { isDirector: true, isDeputy: true, + orgRevisionId: posMasterUser.orgRevisionId, orgChild1Id: IsNull(), orgChild2Id: IsNull(), orgChild3Id: IsNull(), @@ -860,7 +869,11 @@ export class WorkflowController extends Controller { if (body.isAct == true) { const [lists, total] = await AppDataSource.getRepository(viewDirectorActing) .createQueryBuilder("viewDirectorActing") - .andWhere(condition) + .andWhere( + new Brackets((qb) => { + qb.orWhere(condition).orWhere(conditionOfficer); + }), + ) .andWhere( new Brackets((qb) => { qb.orWhere( @@ -936,7 +949,11 @@ export class WorkflowController extends Controller { } else { const [lists, total] = await AppDataSource.getRepository(viewDirector) .createQueryBuilder("viewDirector") - .andWhere(condition) + .andWhere( + new Brackets((qb) => { + qb.orWhere(condition).orWhere(conditionOfficer); + }), + ) .andWhere( new Brackets((qb) => { qb.orWhere( diff --git a/src/entities/CommandRecive.ts b/src/entities/CommandRecive.ts index 2ed7d823..ef638fe5 100644 --- a/src/entities/CommandRecive.ts +++ b/src/entities/CommandRecive.ts @@ -36,6 +36,30 @@ export class CommandRecive extends EntityBase { }) lastName: string; + @Column({ + nullable: true, + comment: "ตำแหน่ง", + length: 255, + default: null, + }) + position: string; + + @Column({ + nullable: true, + comment: "ประเภท", + length: 255, + default: null, + }) + posType: string; + + @Column({ + nullable: true, + comment: "ระดับ", + length: 255, + default: null, + }) + posLevel: string; + @Column({ nullable: true, comment: "ลำดับแสดงผล", diff --git a/src/entities/Profile.ts b/src/entities/Profile.ts index 24d9f8ba..41f9375f 100644 --- a/src/entities/Profile.ts +++ b/src/entities/Profile.ts @@ -45,6 +45,8 @@ import { StateOperatorUser } from "./StateOperatorUser"; import { StateUserComment } from "./StateUserComment"; import { CommandSign } from "./CommandSign"; import { RoleKeycloak } from "./RoleKeycloak"; +import { ProfileActposition } from "./ProfileActposition"; +import { ProfileAssistance } from "./ProfileAssistance"; @Entity("profile") export class Profile extends EntityBase { @@ -187,11 +189,17 @@ export class Profile extends EntityBase { isProbation: boolean; @Column({ - comment: "เกษียณ", + comment: "พ้นราชการ", default: false, }) isLeave: boolean; + @Column({ + comment: "เกษียณ", + default: false, + }) + isRetirement: boolean; + @Column({ comment: "สถานะการใช้งาน", default: true, @@ -363,6 +371,46 @@ export class Profile extends EntityBase { }) mouthSalaryAmount: Double; + @Column({ + nullable: true, + length: 40, + comment: "ไอดีคำสั่งพ้นจากราชการ", + default: null, + }) + leaveCommandId: string; + + @Column({ + nullable: true, + length: 255, + comment: "เลขที่คำสั่งพ้นจากราชการ", + default: null, + }) + leaveCommandNo: string; + + @Column({ + nullable: true, + comment: "หมายเหตุแนวตั้งคำสั่งพ้นจากราชการ", + type: "text", + default: null, + }) + leaveRemark: string; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันที่ลงนามคำสั่งพ้นจากราชการ", + default: null, + }) + leaveDate: Date | null; + + @Column({ + nullable: true, + type: "text", + comment: "ประเภทพ้นคำสั่งพ้นจากราชการ", + default: null, + }) + leaveType: string; + @OneToMany(() => PosMaster, (posMaster) => posMaster.current_holder) current_holders: PosMaster[]; @@ -393,6 +441,12 @@ export class Profile extends EntityBase { @OneToMany(() => ProfileAssessment, (profileAssessment) => profileAssessment.profile) profileAssessments: ProfileAssessment[]; + @OneToMany(() => ProfileActposition, (profileActposition) => profileActposition.profile) + profileActpositions: ProfileActposition[]; + + @OneToMany(() => ProfileAssistance, (profileAssistance) => profileAssistance.profile) + profileAssistances: ProfileAssistance[]; + @OneToMany(() => ProfileLeave, (profileLeave) => profileLeave.profile) profileLeaves: ProfileLeave[]; diff --git a/src/entities/ProfileAbility.ts b/src/entities/ProfileAbility.ts index e2cef051..6b5767f1 100644 --- a/src/entities/ProfileAbility.ts +++ b/src/entities/ProfileAbility.ts @@ -62,6 +62,12 @@ export class ProfileAbility extends EntityBase { }) field: string; + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + @Column({ nullable: true, length: 40, @@ -112,4 +118,5 @@ export type UpdateProfileAbility = { dateStart?: Date | null; dateEnd?: Date | null; field?: string | null; + isUpload?: boolean | null; }; diff --git a/src/entities/ProfileAbilityHistory.ts b/src/entities/ProfileAbilityHistory.ts index f3b4d7ab..16b0de99 100644 --- a/src/entities/ProfileAbilityHistory.ts +++ b/src/entities/ProfileAbilityHistory.ts @@ -52,6 +52,12 @@ export class ProfileAbilityHistory extends EntityBase { }) field: string; + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + @Column({ nullable: true, length: 40, diff --git a/src/entities/ProfileActposition.ts b/src/entities/ProfileActposition.ts new file mode 100644 index 00000000..dd95a458 --- /dev/null +++ b/src/entities/ProfileActposition.ts @@ -0,0 +1,100 @@ +import { Entity, Column, ManyToOne, JoinColumn, OneToMany } from "typeorm"; +import { EntityBase } from "./base/Base"; +import { Profile } from "./Profile"; +import { ProfileActpositionHistory } from "./ProfileActpositionHistory"; +import { ProfileEmployee } from "./ProfileEmployee"; + +@Entity("profileActposition") +export class ProfileActposition extends EntityBase { + @Column({ + nullable: true, + length: 40, + comment: "คีย์นอก(FK)ของตาราง Profile", + default: null, + }) + profileId: string; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันที่เริ่มต้น", + default: null, + }) + dateStart: Date; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันที่สิ้นสุด", + default: null, + }) + dateEnd: Date; + + @Column({ + nullable: true, + comment: "ตำแหน่งเลขที่", + default: null, + }) + posNo: string; + + @Column({ + nullable: true, + comment: "ตำแหน่ง", + default: null, + }) + position: string; + + @Column({ + comment: "สถานะ", + default: false, + }) + status: boolean; + + @Column({ + nullable: true, + length: 40, + comment: "คีย์นอก(FK)ของตาราง ProfileEmployee", + default: null, + }) + profileEmployeeId: string; + + @OneToMany( + () => ProfileActpositionHistory, + (profileActpositionHistory) => profileActpositionHistory.histories, + ) + profileActpositionHistorys: ProfileActpositionHistory[]; + + @ManyToOne(() => Profile, (profile) => profile.profileAbilities) + @JoinColumn({ name: "profileId" }) + profile: Profile; + + @ManyToOne(() => ProfileEmployee, (ProfileEmployee) => ProfileEmployee.profileAbilities) + @JoinColumn({ name: "profileEmployeeId" }) + profileEmployee: ProfileEmployee; +} + +export class CreateProfileActposition { + profileId: string | null; + dateStart: Date | null; + dateEnd: Date | null; + posNo: string | null; + position: string | null; + status: boolean; +} + +export class CreateProfileActpositionEmployee { + profileEmployeeId: string | null; + dateStart: Date | null; + dateEnd: Date | null; + posNo: string | null; + position: string | null; + status: boolean; +} + +export type UpdateProfileActposition = { + dateStart?: Date | null; + dateEnd?: Date | null; + posNo?: string | null; + position?: string | null; + status: boolean; +}; diff --git a/src/entities/ProfileActpositionHistory.ts b/src/entities/ProfileActpositionHistory.ts new file mode 100644 index 00000000..bb2034e7 --- /dev/null +++ b/src/entities/ProfileActpositionHistory.ts @@ -0,0 +1,57 @@ +import { Entity, Column, ManyToOne, JoinColumn } from "typeorm"; +import { EntityBase } from "./base/Base"; +import { ProfileActposition } from "./ProfileActposition"; + +@Entity("profileActpositionHistory") +export class ProfileActpositionHistory extends EntityBase { + @Column({ + nullable: true, + type: "datetime", + comment: "วันที่เริ่มต้น", + default: null, + }) + dateStart: Date; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันที่สิ้นสุด", + default: null, + }) + dateEnd: Date; + + @Column({ + nullable: true, + comment: "ตำแหน่งเลขที่", + default: null, + }) + posNo: string; + + @Column({ + nullable: true, + comment: "ตำแหน่ง", + default: null, + }) + position: string; + + @Column({ + comment: "สถานะ", + default: false, + }) + status: boolean; + + @Column({ + nullable: true, + length: 40, + comment: "คีย์นอก(FK)ของตาราง ProfileActposition", + default: null, + }) + profileActpositionId: string; + + @ManyToOne( + () => ProfileActposition, + (profileActposition) => profileActposition.profileActpositionHistorys, + ) + @JoinColumn({ name: "profileActpositionId" }) + histories: ProfileActposition; +} diff --git a/src/entities/ProfileAssistance.ts b/src/entities/ProfileAssistance.ts new file mode 100644 index 00000000..de1f0f3e --- /dev/null +++ b/src/entities/ProfileAssistance.ts @@ -0,0 +1,108 @@ +import { Entity, Column, ManyToOne, JoinColumn, OneToMany } from "typeorm"; +import { EntityBase } from "./base/Base"; +import { Profile } from "./Profile"; +import { ProfileAssistanceHistory } from "./ProfileAssistanceHistory"; +import { ProfileEmployee } from "./ProfileEmployee"; + +@Entity("profileAssistance") +export class ProfileAssistance extends EntityBase { + @Column({ + nullable: true, + length: 40, + comment: "คีย์นอก(FK)ของตาราง Profile", + default: null, + }) + profileId: string; + + @Column({ + nullable: true, + comment: "หน่วยงานที่ให้ช่วยราชการ", + default: null, + }) + agency: string; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันเริ่มช่วยราชการ", + default: null, + }) + dateStart: Date; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันสิ้นสุดการช่วยราชการ", + default: null, + }) + dateEnd: Date; + + @Column({ + nullable: true, + comment: "เลขที่คำสั่ง", + default: null, + }) + commandNo: string; + + @Column({ + nullable: true, + comment: "เอกสารอ้างอิง", + default: null, + }) + document: string; + + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + + @Column({ + nullable: true, + length: 40, + comment: "คีย์นอก(FK)ของตาราง ProfileEmployee", + default: null, + }) + profileEmployeeId: string; + + @OneToMany( + () => ProfileAssistanceHistory, + (profileAssistanceHistory) => profileAssistanceHistory.histories, + ) + profileAssistanceHistorys: ProfileAssistanceHistory[]; + + @ManyToOne(() => Profile, (profile) => profile.profileAbilities) + @JoinColumn({ name: "profileId" }) + profile: Profile; + + @ManyToOne(() => ProfileEmployee, (ProfileEmployee) => ProfileEmployee.profileAbilities) + @JoinColumn({ name: "profileEmployeeId" }) + profileEmployee: ProfileEmployee; +} + +export class CreateProfileAssistance { + profileId: string | null; + agency: string | null; + dateStart: Date | null; + dateEnd: Date | null; + commandNo: string | null; + document: string | null; +} + +export class CreateProfileAssistanceEmployee { + profileEmployeeId: string | null; + agency: string | null; + dateStart: Date | null; + dateEnd: Date | null; + commandNo: string | null; + document: string | null; +} + +export type UpdateProfileAssistance = { + agency?: string | null; + dateStart?: Date | null; + dateEnd?: Date | null; + commandNo?: string | null; + document?: string | null; + isUpload?: boolean | null; +}; diff --git a/src/entities/ProfileAssistanceHistory.ts b/src/entities/ProfileAssistanceHistory.ts new file mode 100644 index 00000000..3acea1a5 --- /dev/null +++ b/src/entities/ProfileAssistanceHistory.ts @@ -0,0 +1,64 @@ +import { Entity, Column, ManyToOne, JoinColumn } from "typeorm"; +import { EntityBase } from "./base/Base"; +import { ProfileAssistance } from "./ProfileAssistance"; + +@Entity("profileAssistanceHistory") +export class ProfileAssistanceHistory extends EntityBase { + @Column({ + nullable: true, + comment: "หน่วยงานที่ให้ช่วยราชการ", + default: null, + }) + agency: string; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันเริ่มช่วยราชการ", + default: null, + }) + dateStart: Date; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันสิ้นสุดการช่วยราชการ", + default: null, + }) + dateEnd: Date; + + @Column({ + nullable: true, + comment: "เลขที่คำสั่ง", + default: null, + }) + commandNo: string; + + @Column({ + nullable: true, + comment: "เอกสารอ้างอิง", + default: null, + }) + document: string; + + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + + @Column({ + nullable: true, + length: 40, + comment: "คีย์นอก(FK)ของตาราง ProfileAssistance", + default: null, + }) + profileAssistanceId: string; + + @ManyToOne( + () => ProfileAssistance, + (profileAssistance) => profileAssistance.profileAssistanceHistorys, + ) + @JoinColumn({ name: "profileAssistanceId" }) + histories: ProfileAssistance; +} diff --git a/src/entities/ProfileDuty.ts b/src/entities/ProfileDuty.ts index 455ae4ce..0454b6fb 100644 --- a/src/entities/ProfileDuty.ts +++ b/src/entities/ProfileDuty.ts @@ -70,6 +70,12 @@ export class ProfileDuty extends EntityBase { }) refCommandNo: string; + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + @OneToMany(() => ProfileDutyHistory, (profileDutyHistory) => profileDutyHistory.histories) profileDutyHistories: ProfileDutyHistory[]; @@ -109,4 +115,5 @@ export type UpdateProfileDuty = { reference?: string | null; refCommandDate?: Date | null; refCommandNo?: string | null; + isUpload?: boolean | null; }; diff --git a/src/entities/ProfileDutyHistory.ts b/src/entities/ProfileDutyHistory.ts index 31b1a01e..e00f4d5f 100644 --- a/src/entities/ProfileDutyHistory.ts +++ b/src/entities/ProfileDutyHistory.ts @@ -52,6 +52,12 @@ export class ProfileDutyHistory extends EntityBase { }) refCommandNo: string; + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + @Column({ nullable: true, length: 40, diff --git a/src/entities/ProfileEmployee.ts b/src/entities/ProfileEmployee.ts index 16841f8f..c6ee449a 100644 --- a/src/entities/ProfileEmployee.ts +++ b/src/entities/ProfileEmployee.ts @@ -197,11 +197,17 @@ export class ProfileEmployee extends EntityBase { isProbation: boolean; @Column({ - comment: "เกษียณ", + comment: "พ้นราชการ", default: false, }) isLeave: boolean; + @Column({ + comment: "เกษียณ", + default: false, + }) + isRetirement: boolean; + @Column({ comment: "สถานะการใช้งาน", default: true, @@ -616,6 +622,46 @@ export class ProfileEmployee extends EntityBase { }) mouthSalaryAmount: Double; + @Column({ + nullable: true, + length: 40, + comment: "ไอดีคำสั่งพ้นจากราชการ", + default: null, + }) + leaveCommandId: string; + + @Column({ + nullable: true, + length: 255, + comment: "เลขที่คำสั่งพ้นจากราชการ", + default: null, + }) + leaveCommandNo: string; + + @Column({ + nullable: true, + comment: "หมายเหตุแนวตั้งคำสั่งพ้นจากราชการ", + type: "text", + default: null, + }) + leaveRemark: string; + + @Column({ + nullable: true, + type: "datetime", + comment: "วันที่ลงนามคำสั่งพ้นจากราชการ", + default: null, + }) + leaveDate: Date | null; + + @Column({ + nullable: true, + type: "text", + comment: "ประเภทพ้นคำสั่งพ้นจากราชการ", + default: null, + }) + leaveType: string; + @OneToMany(() => ProfileEmployeeInformationHistory, (v) => v.profileEmployeeInformation) information_histories: ProfileEmployeeInformationHistory[]; diff --git a/src/entities/ProfileHonor.ts b/src/entities/ProfileHonor.ts index cba41733..1e73f676 100644 --- a/src/entities/ProfileHonor.ts +++ b/src/entities/ProfileHonor.ts @@ -46,6 +46,14 @@ export class ProfileHonor extends EntityBase { }) issuer: string; + @Column({ + nullable: true, + length: 200, + comment: "ประเภท", + default: null, + }) + type: string; + @Column({ nullable: true, type: "datetime", @@ -69,6 +77,12 @@ export class ProfileHonor extends EntityBase { }) isDate: boolean; + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + @OneToMany(() => ProfileHonorHistory, (profileHonorHistory) => profileHonorHistory.histories) profileHonorHistories: ProfileHonorHistory[]; @@ -88,6 +102,7 @@ export class CreateProfileHonor { issuer: string | null; refCommandDate: Date | null; refCommandNo: string | null; + type: string | null; isDate: boolean | null; } @@ -98,6 +113,7 @@ export class CreateProfileEmployeeHonor { issuer: string | null; refCommandDate: Date | null; refCommandNo: string | null; + type: string | null; isDate: boolean | null; } @@ -107,5 +123,7 @@ export type UpdateProfileHonor = { issuer?: string | null; refCommandDate?: Date | null; refCommandNo?: string | null; + type?: string | null; isDate: boolean | null; + isUpload?: boolean | null; }; diff --git a/src/entities/ProfileHonorHistory.ts b/src/entities/ProfileHonorHistory.ts index c2a45581..59338365 100644 --- a/src/entities/ProfileHonorHistory.ts +++ b/src/entities/ProfileHonorHistory.ts @@ -28,6 +28,14 @@ export class ProfileHonorHistory extends EntityBase { }) issuer: string; + @Column({ + nullable: true, + length: 200, + comment: "ประเภท", + default: null, + }) + type: string; + @Column({ nullable: true, type: "datetime", @@ -59,6 +67,12 @@ export class ProfileHonorHistory extends EntityBase { }) isDate: boolean; + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + @ManyToOne(() => ProfileHonor, (profileHonor) => profileHonor.profileHonorHistories) @JoinColumn({ name: "profileHonorId" }) histories: ProfileHonor; diff --git a/src/entities/ProfileInsignia.ts b/src/entities/ProfileInsignia.ts index 078b7355..d195b701 100644 --- a/src/entities/ProfileInsignia.ts +++ b/src/entities/ProfileInsignia.ts @@ -115,6 +115,12 @@ export class ProfileInsignia extends EntityBase { }) note: string; + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + @Column({ nullable: true, length: 40, @@ -190,4 +196,5 @@ export type UpdateProfileInsignia = { refCommandDate?: Date | null; refCommandNo?: string | null; note?: string | null; + isUpload?: boolean | null; }; diff --git a/src/entities/ProfileInsigniaHistory.ts b/src/entities/ProfileInsigniaHistory.ts index 8dfde589..954a3bca 100644 --- a/src/entities/ProfileInsigniaHistory.ts +++ b/src/entities/ProfileInsigniaHistory.ts @@ -47,6 +47,12 @@ export class ProfileInsigniaHistory extends EntityBase { @Column({ nullable: true, comment: "หมายเหตุ", default: null }) note: string; + @Column({ + comment: "แนบไฟล์เอกสาร", + default: false, + }) + isUpload: boolean; + @Column({ nullable: true, length: 40, diff --git a/src/entities/view/viewDirector.ts b/src/entities/view/viewDirector.ts index 82a8d10e..f6c1ae9a 100644 --- a/src/entities/view/viewDirector.ts +++ b/src/entities/view/viewDirector.ts @@ -21,6 +21,8 @@ import { ViewColumn, ViewEntity } from "typeorm"; \`posType\`.\`posTypeName\` AS \`posType\`, \`posExecutive\`.\`posExecutiveName\` AS \`posExecutiveName\`, \`orgRoot\`.\`isDeputy\` AS \`isDeputy\`, + \`orgChild1\`.\`isOfficer\` AS \`isOfficer\`, + \`posMaster\`.\`orgRevisionId\` AS \`orgRevisionId\`, \`posMaster\`.\`orgRootId\` AS \`orgRootId\`, \`posMaster\`.\`orgChild1Id\` AS \`orgChild1Id\`, \`posMaster\`.\`orgChild2Id\` AS \`orgChild2Id\`, @@ -113,6 +115,10 @@ export class viewDirector { @ViewColumn() isDeputy: boolean; @ViewColumn() + isOfficer: boolean; + @ViewColumn() + orgRevisionId: string; + @ViewColumn() orgRootId: string; @ViewColumn() orgChild1Id: string; diff --git a/src/entities/view/viewDirectorActing.ts b/src/entities/view/viewDirectorActing.ts index 92de1c73..19ca4c10 100644 --- a/src/entities/view/viewDirectorActing.ts +++ b/src/entities/view/viewDirectorActing.ts @@ -22,6 +22,8 @@ import { ViewColumn, ViewEntity } from "typeorm"; \`posType\`.\`posTypeName\` AS \`posType\`, \`posExecutive\`.\`posExecutiveName\` AS \`posExecutiveName\`, \`orgRoot\`.\`isDeputy\` AS \`isDeputy\`, + \`orgChild1\`.\`isOfficer\` AS \`isOfficer\`, + \`posMaster\`.\`orgRevisionId\` AS \`orgRevisionId\`, \`posMaster\`.\`orgRootId\` AS \`orgRootId\`, \`posMaster\`.\`orgChild1Id\` AS \`orgChild1Id\`, \`posMaster\`.\`orgChild2Id\` AS \`orgChild2Id\`, @@ -34,7 +36,7 @@ import { ViewColumn, ViewEntity } from "typeorm"; ' ', \`profile\`.\`lastName\`) AS \`actFullName\` FROM - ((((((((((((((\`posMasterAct\` + (((((((((((((((\`posMasterAct\` JOIN \`posMaster\` \`posMasterChild\` ON ((\`posMasterAct\`.\`posMasterChildId\` = \`posMasterChild\`.\`id\`))) JOIN \`profile\` \`profileChild\` ON ((\`posMasterChild\`.\`current_holderId\` = \`profileChild\`.\`id\`))) LEFT JOIN \`orgRoot\` \`orgRootChild\` ON ((\`posMasterChild\`.\`orgRootId\` = \`orgRootChild\`.\`id\`))) @@ -46,6 +48,7 @@ import { ViewColumn, ViewEntity } from "typeorm"; JOIN \`posType\` ON ((\`profileChild\`.\`posTypeId\` = \`posType\`.\`id\`))) JOIN \`posMaster\` ON ((\`posMasterAct\`.\`posMasterId\` = \`posMaster\`.\`id\`))) LEFT JOIN \`orgRoot\` ON ((\`posMaster\`.\`orgRootId\` = \`orgRoot\`.\`id\`))) + LEFT JOIN \`orgChild1\` ON ((\`posMaster\`.\`orgChild1Id\` = \`orgChild1\`.\`id\`))) JOIN \`profile\` ON ((\`posMaster\`.\`current_holderId\` = \`profile\`.\`id\`))) LEFT JOIN \`position\` ON ((\`posMasterChild\`.\`id\` = \`position\`.\`posMasterId\`))) LEFT JOIN \`posExecutive\` ON ((\`position\`.\`posExecutiveId\` = \`posExecutive\`.\`id\`))) @@ -78,8 +81,12 @@ export class viewDirectorActing { @ViewColumn() isDeputy: boolean; @ViewColumn() + isOfficer: boolean; + @ViewColumn() isDirectorChild: boolean; @ViewColumn() + orgRevisionId: string; + @ViewColumn() orgRootId: string; @ViewColumn() orgChild1Id: string; diff --git a/src/interfaces/utils.ts b/src/interfaces/utils.ts index 1fbcfb14..4c9116b1 100644 --- a/src/interfaces/utils.ts +++ b/src/interfaces/utils.ts @@ -10,6 +10,7 @@ import { Command } from "../entities/Command"; import { ProfileSalary } from "../entities/ProfileSalary"; import { Profile } from "../entities/Profile"; import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { CommandRecive } from "../entities/CommandRecive"; export function calculateAge(start: Date, end = new Date()) { if (start.getTime() > end.getTime()) return null; @@ -333,6 +334,7 @@ export async function checkReturnCommandType(commandId: string) { export async function checkExceptCommandType(commandId: string) { const commandRepository = AppDataSource.getRepository(Command); + const commandReciveRepository = AppDataSource.getRepository(CommandRecive) const _type = await commandRepository.findOne({ where: { id: commandId, @@ -340,27 +342,87 @@ export async function checkExceptCommandType(commandId: string) { relations: ["commandType"], }); if (!["C-PM-25", "C-PM-26"].includes(String(_type?.commandType.code))) { - return false; + return { status: false, LeaveType: null, leaveRemark: null}; } - return true; + const _commandRecive = await commandReciveRepository.findOne({ + where: { commandId: commandId } + }); + + let _leaveType: string ="" + switch(String(_type?.commandType.code)){ + case "C-PM-25" : { + _leaveType = "DISCIPLINE_SUSPEND"; //คำสั่งพักจากราชการ + break; + } + case "C-PM-26" : { + _leaveType = "DISCIPLINE_SUSPEND"; //คำสั่งให้ออกจากราชการไว้ก่อน + break; + } + default: { + _leaveType = "" + } + } + return { status: true, LeaveType: _leaveType, leaveRemark: _commandRecive ? _commandRecive.remarkVertical : null }; } export async function checkCommandType(commandId: string) { const commandRepository = AppDataSource.getRepository(Command); + const commandReciveRepository = AppDataSource.getRepository(CommandRecive) const _type = await commandRepository.findOne({ where: { id: commandId, }, - relations: ["commandType"], + relations: ["commandType", "commandRecives"], }); + if ( !["C-PM-12", "C-PM-13", "C-PM-17", "C-PM-18", "C-PM-23", "C-PM-19", "C-PM-20"].includes( String(_type?.commandType.code), ) ) { - return false; + // return false; + return { status: false, LeaveType: null, leaveRemark: null}; } - return true; + // return true; + const _commandRecive = await commandReciveRepository.findOne({ + where: { commandId: commandId } + }); + + let _leaveType: string ="" + switch(String(_type?.commandType.code)){ + case "C-PM-12" : { + _leaveType = "PROBATION_REPORT"; + break; + } + case "C-PM-13" : { + _leaveType = "PLACEMENT_TRANSFER"; + break; + } + case "C-PM-17" : { + _leaveType = "RETIRE_RESIGN"; + break; + } + case "C-PM-18" : { + _leaveType = "RETIRE_OUT"; + break; + } + case "C-PM-19" : { + _leaveType = "DISCIPLINE_RESULT_REMOVE"; + break; + } + case "C-PM-20" : { + _leaveType = "DISCIPLINE_RESULT_DISMISS"; + break; + } + case "C-PM-23" : { + _leaveType = "RETIRE_RESIGN_EMP"; + break; + } + default: { + _leaveType = "" + } + } + return { status: true, LeaveType: _leaveType, leaveRemark: _commandRecive ? _commandRecive.remarkVertical : null }; } //logs diff --git a/src/keycloak/index.ts b/src/keycloak/index.ts index 16081ee3..d4f5f8a6 100644 --- a/src/keycloak/index.ts +++ b/src/keycloak/index.ts @@ -114,6 +114,28 @@ export async function getUser(userId: string) { return await res.json(); } +/** + * Get keycloak user by Username (citizenId) + * + * Client must have permission to manage realm's user + * + * @returns user if success, false otherwise. + */ +export async function getUserByUsername(citizenId: string) { + const res = await fetch(`${KC_URL}/admin/realms/${KC_REALMS}/users?username=${citizenId}`, { + // prettier-ignore + headers: { + "authorization": `Bearer ${await getToken()}`, + "content-type": `application/json`, + }, + }).catch((e) => console.log("Keycloak Error: ", e)); + if (!res) return false; + if (!res.ok) { + return Boolean(console.error("Keycloak Error Response: ", await res.json())); + } + return await res.json(); +} + /** * Get keycloak user list * @@ -205,14 +227,7 @@ export async function getUserListOrg(first = "", max = "", search = "", userIds: } export async function getUserCountOrg(first = "", max = "", search = "", userIds: string[] = []) { - console.log(userIds); const userIdsParam = userIds.join(","); - console.log(userIdsParam); - console.log("xxxxxxxxxxxxxxxxx"); - console.log( - `${KC_URL}/admin/realms/${KC_REALMS}/users/count?first=${first || "0"}&max=${max || "-1"}${search ? `&search=${search}` : ""}${userIdsParam && userIdsParam != "" ? `&id=${userIdsParam}` : ""}`, - ); - console.log("aaaaaaaaaaaaaaaaaa"); const res = await fetch( `${KC_URL}/admin/realms/${KC_REALMS}/users/count?first=${first || "0"}&max=${max || "-1"}${search ? `&search=${search}` : ""}${userIdsParam && userIdsParam != "" ? `&id=${userIdsParam}` : ""}`, { diff --git a/src/migration/1737535442324-UpdateviewAddOfficer.ts b/src/migration/1737535442324-UpdateviewAddOfficer.ts new file mode 100644 index 00000000..74125a2e --- /dev/null +++ b/src/migration/1737535442324-UpdateviewAddOfficer.ts @@ -0,0 +1,156 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateviewAddOfficer1737535442324 implements MigrationInterface { + name = 'UpdateviewAddOfficer1737535442324' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`CREATE VIEW \`view_director_acting\` AS SELECT + \`profileChild\`.\`id\` AS \`Id\`, + \`profileChild\`.\`prefix\` AS \`prefix\`, + \`profileChild\`.\`firstName\` AS \`firstName\`, + \`profileChild\`.\`lastName\` AS \`lastName\`, + \`profileChild\`.\`citizenId\` AS \`citizenId\`, + \`profileChild\`.\`position\` AS \`position\`, + CONCAT((CASE + WHEN (\`posMaster\`.\`orgChild1Id\` IS NULL) THEN \`orgRootChild\`.\`orgRootShortName\` + WHEN (\`posMaster\`.\`orgChild2Id\` IS NULL) THEN \`orgChild1Child\`.\`orgChild1ShortName\` + WHEN (\`posMaster\`.\`orgChild3Id\` IS NULL) THEN \`orgChild2Child\`.\`orgChild2ShortName\` + WHEN (\`posMaster\`.\`orgChild4Id\` IS NULL) THEN \`orgChild3Child\`.\`orgChild3ShortName\` + ELSE \`orgChild4Child\`.\`orgChild4ShortName\` + END), + \`posMaster\`.\`posMasterNo\`) AS \`posNo\`, + \`posMasterChild\`.\`isDirector\` AS \`isDirectorChild\`, + \`posMaster\`.\`isDirector\` AS \`isDirector\`, + \`posLevel\`.\`posLevelName\` AS \`posLevel\`, + \`posType\`.\`posTypeName\` AS \`posType\`, + \`posExecutive\`.\`posExecutiveName\` AS \`posExecutiveName\`, + \`orgRoot\`.\`isDeputy\` AS \`isDeputy\`, + \`orgChild1\`.\`isOfficer\` AS \`isOfficer\`, + \`posMaster\`.\`orgRootId\` AS \`orgRootId\`, + \`posMaster\`.\`orgChild1Id\` AS \`orgChild1Id\`, + \`posMaster\`.\`orgChild2Id\` AS \`orgChild2Id\`, + \`posMaster\`.\`orgChild3Id\` AS \`orgChild3Id\`, + \`posMaster\`.\`orgChild4Id\` AS \`orgChild4Id\`, + CONCAT(\`posMaster\`.\`id\`, \`profileChild\`.\`id\`) AS \`key\`, + \`profile\`.\`id\` AS \`actFullNameId\`, + CONCAT(\`profile\`.\`prefix\`, + \`profile\`.\`firstName\`, + ' ', + \`profile\`.\`lastName\`) AS \`actFullName\` + FROM + (((((((((((((((\`posMasterAct\` + JOIN \`posMaster\` \`posMasterChild\` ON ((\`posMasterAct\`.\`posMasterChildId\` = \`posMasterChild\`.\`id\`))) + JOIN \`profile\` \`profileChild\` ON ((\`posMasterChild\`.\`current_holderId\` = \`profileChild\`.\`id\`))) + LEFT JOIN \`orgRoot\` \`orgRootChild\` ON ((\`posMasterChild\`.\`orgRootId\` = \`orgRootChild\`.\`id\`))) + LEFT JOIN \`orgChild1\` \`orgChild1Child\` ON ((\`posMasterChild\`.\`orgChild1Id\` = \`orgChild1Child\`.\`id\`))) + LEFT JOIN \`orgChild2\` \`orgChild2Child\` ON ((\`posMasterChild\`.\`orgChild2Id\` = \`orgChild2Child\`.\`id\`))) + LEFT JOIN \`orgChild3\` \`orgChild3Child\` ON ((\`posMasterChild\`.\`orgChild3Id\` = \`orgChild3Child\`.\`id\`))) + LEFT JOIN \`orgChild4\` \`orgChild4Child\` ON ((\`posMasterChild\`.\`orgChild4Id\` = \`orgChild4Child\`.\`id\`))) + JOIN \`posLevel\` ON ((\`profileChild\`.\`posLevelId\` = \`posLevel\`.\`id\`))) + JOIN \`posType\` ON ((\`profileChild\`.\`posTypeId\` = \`posType\`.\`id\`))) + JOIN \`posMaster\` ON ((\`posMasterAct\`.\`posMasterId\` = \`posMaster\`.\`id\`))) + LEFT JOIN \`orgRoot\` ON ((\`posMaster\`.\`orgRootId\` = \`orgRoot\`.\`id\`))) + LEFT JOIN \`orgChild1\` ON ((\`posMaster\`.\`orgChild1Id\` = \`orgChild1\`.\`id\`))) + JOIN \`profile\` ON ((\`posMaster\`.\`current_holderId\` = \`profile\`.\`id\`))) + LEFT JOIN \`position\` ON ((\`posMasterChild\`.\`id\` = \`position\`.\`posMasterId\`))) + LEFT JOIN \`posExecutive\` ON ((\`position\`.\`posExecutiveId\` = \`posExecutive\`.\`id\`))) + WHERE + (\`position\`.\`positionIsSelected\` = TRUE)`); + await queryRunner.query(`INSERT INTO \`bma_ehr_organization_demo\`.\`typeorm_metadata\`(\`database\`, \`schema\`, \`table\`, \`type\`, \`name\`, \`value\`) VALUES (DEFAULT, ?, DEFAULT, ?, ?, ?)`, ["bma_ehr_organization_demo","VIEW","view_director_acting","SELECT \n `profileChild`.`id` AS `Id`,\n `profileChild`.`prefix` AS `prefix`,\n `profileChild`.`firstName` AS `firstName`,\n `profileChild`.`lastName` AS `lastName`,\n `profileChild`.`citizenId` AS `citizenId`,\n `profileChild`.`position` AS `position`,\n CONCAT((CASE\n WHEN (`posMaster`.`orgChild1Id` IS NULL) THEN `orgRootChild`.`orgRootShortName`\n WHEN (`posMaster`.`orgChild2Id` IS NULL) THEN `orgChild1Child`.`orgChild1ShortName`\n WHEN (`posMaster`.`orgChild3Id` IS NULL) THEN `orgChild2Child`.`orgChild2ShortName`\n WHEN (`posMaster`.`orgChild4Id` IS NULL) THEN `orgChild3Child`.`orgChild3ShortName`\n ELSE `orgChild4Child`.`orgChild4ShortName`\n END),\n `posMaster`.`posMasterNo`) AS `posNo`,\n `posMasterChild`.`isDirector` AS `isDirectorChild`,\n `posMaster`.`isDirector` AS `isDirector`,\n `posLevel`.`posLevelName` AS `posLevel`,\n `posType`.`posTypeName` AS `posType`,\n `posExecutive`.`posExecutiveName` AS `posExecutiveName`,\n `orgRoot`.`isDeputy` AS `isDeputy`,\n `orgChild1`.`isOfficer` AS `isOfficer`,\n `posMaster`.`orgRootId` AS `orgRootId`,\n `posMaster`.`orgChild1Id` AS `orgChild1Id`,\n `posMaster`.`orgChild2Id` AS `orgChild2Id`,\n `posMaster`.`orgChild3Id` AS `orgChild3Id`,\n `posMaster`.`orgChild4Id` AS `orgChild4Id`,\n CONCAT(`posMaster`.`id`, `profileChild`.`id`) AS `key`,\n `profile`.`id` AS `actFullNameId`,\n CONCAT(`profile`.`prefix`,\n `profile`.`firstName`,\n ' ',\n `profile`.`lastName`) AS `actFullName`\n FROM\n (((((((((((((((`posMasterAct`\n JOIN `posMaster` `posMasterChild` ON ((`posMasterAct`.`posMasterChildId` = `posMasterChild`.`id`)))\n JOIN `profile` `profileChild` ON ((`posMasterChild`.`current_holderId` = `profileChild`.`id`)))\n LEFT JOIN `orgRoot` `orgRootChild` ON ((`posMasterChild`.`orgRootId` = `orgRootChild`.`id`)))\n LEFT JOIN `orgChild1` `orgChild1Child` ON ((`posMasterChild`.`orgChild1Id` = `orgChild1Child`.`id`)))\n LEFT JOIN `orgChild2` `orgChild2Child` ON ((`posMasterChild`.`orgChild2Id` = `orgChild2Child`.`id`)))\n LEFT JOIN `orgChild3` `orgChild3Child` ON ((`posMasterChild`.`orgChild3Id` = `orgChild3Child`.`id`)))\n LEFT JOIN `orgChild4` `orgChild4Child` ON ((`posMasterChild`.`orgChild4Id` = `orgChild4Child`.`id`)))\n JOIN `posLevel` ON ((`profileChild`.`posLevelId` = `posLevel`.`id`)))\n JOIN `posType` ON ((`profileChild`.`posTypeId` = `posType`.`id`)))\n JOIN `posMaster` ON ((`posMasterAct`.`posMasterId` = `posMaster`.`id`)))\n LEFT JOIN `orgRoot` ON ((`posMaster`.`orgRootId` = `orgRoot`.`id`)))\n LEFT JOIN `orgChild1` ON ((`posMaster`.`orgChild1Id` = `orgChild1`.`id`)))\n JOIN `profile` ON ((`posMaster`.`current_holderId` = `profile`.`id`)))\n LEFT JOIN `position` ON ((`posMasterChild`.`id` = `position`.`posMasterId`)))\n LEFT JOIN `posExecutive` ON ((`position`.`posExecutiveId` = `posExecutive`.`id`)))\n WHERE\n (`position`.`positionIsSelected` = TRUE)"]); + await queryRunner.query(`CREATE VIEW \`view_director\` AS SELECT + \`profile\`.\`id\` AS \`Id\`, + \`profile\`.\`prefix\` AS \`prefix\`, + \`profile\`.\`firstName\` AS \`firstName\`, + \`profile\`.\`lastName\` AS \`lastName\`, + \`profile\`.\`citizenId\` AS \`citizenId\`, + \`profile\`.\`position\` AS \`position\`, + CONCAT((CASE + WHEN (\`posMaster\`.\`orgChild1Id\` IS NULL) THEN \`orgRoot\`.\`orgRootShortName\` + WHEN (\`posMaster\`.\`orgChild2Id\` IS NULL) THEN \`orgChild1\`.\`orgChild1ShortName\` + WHEN (\`posMaster\`.\`orgChild3Id\` IS NULL) THEN \`orgChild2\`.\`orgChild2ShortName\` + WHEN (\`posMaster\`.\`orgChild4Id\` IS NULL) THEN \`orgChild3\`.\`orgChild3ShortName\` + ELSE \`orgChild4\`.\`orgChild4ShortName\` + END), + \`posMaster\`.\`posMasterNo\`) AS \`posNo\`, + \`posMaster\`.\`isDirector\` AS \`isDirector\`, + \`posLevel\`.\`posLevelName\` AS \`posLevel\`, + \`posType\`.\`posTypeName\` AS \`posType\`, + \`posExecutive\`.\`posExecutiveName\` AS \`posExecutiveName\`, + \`orgRoot\`.\`isDeputy\` AS \`isDeputy\`, + \`orgChild1\`.\`isOfficer\` AS \`isOfficer\`, + \`posMaster\`.\`orgRootId\` AS \`orgRootId\`, + \`posMaster\`.\`orgChild1Id\` AS \`orgChild1Id\`, + \`posMaster\`.\`orgChild2Id\` AS \`orgChild2Id\`, + \`posMaster\`.\`orgChild3Id\` AS \`orgChild3Id\`, + \`posMaster\`.\`orgChild4Id\` AS \`orgChild4Id\`, + CONCAT(\`posMaster\`.\`id\`, \`profile\`.\`id\`) AS \`key\`, + ( + SELECT \`actFullNameId\` + FROM \`view_director_acting\` AS \`acting\` + WHERE \`acting\`.\`Id\` = \`posMaster\`.\`current_holderId\` + AND \`acting\`.\`orgRootId\` = \`posMaster\`.\`orgRootId\` + AND ( + (\`acting\`.\`orgChild1Id\` IS NULL AND \`posMaster\`.\`orgChild1Id\` IS NULL) + OR (\`acting\`.\`orgChild1Id\` = \`posMaster\`.\`orgChild1Id\`) + ) + AND ( + (\`acting\`.\`orgChild2Id\` IS NULL AND \`posMaster\`.\`orgChild2Id\` IS NULL) + OR (\`acting\`.\`orgChild2Id\` = \`posMaster\`.\`orgChild2Id\`) + ) + AND ( + (\`acting\`.\`orgChild3Id\` IS NULL AND \`posMaster\`.\`orgChild3Id\` IS NULL) + OR (\`acting\`.\`orgChild3Id\` = \`posMaster\`.\`orgChild3Id\`) + ) + AND ( + (\`acting\`.\`orgChild4Id\` IS NULL AND \`posMaster\`.\`orgChild4Id\` IS NULL) + OR (\`acting\`.\`orgChild4Id\` = \`posMaster\`.\`orgChild4Id\`) + ) + ) AS \`actFullNameId\`, + ( + SELECT \`actFullName\` + FROM \`view_director_acting\` AS \`acting\` + WHERE \`acting\`.\`Id\` = \`posMaster\`.\`current_holderId\` + AND \`acting\`.\`orgRootId\` = \`posMaster\`.\`orgRootId\` + AND ( + (\`acting\`.\`orgChild1Id\` IS NULL AND \`posMaster\`.\`orgChild1Id\` IS NULL) + OR (\`acting\`.\`orgChild1Id\` = \`posMaster\`.\`orgChild1Id\`) + ) + AND ( + (\`acting\`.\`orgChild2Id\` IS NULL AND \`posMaster\`.\`orgChild2Id\` IS NULL) + OR (\`acting\`.\`orgChild2Id\` = \`posMaster\`.\`orgChild2Id\`) + ) + AND ( + (\`acting\`.\`orgChild3Id\` IS NULL AND \`posMaster\`.\`orgChild3Id\` IS NULL) + OR (\`acting\`.\`orgChild3Id\` = \`posMaster\`.\`orgChild3Id\`) + ) + AND ( + (\`acting\`.\`orgChild4Id\` IS NULL AND \`posMaster\`.\`orgChild4Id\` IS NULL) + OR (\`acting\`.\`orgChild4Id\` = \`posMaster\`.\`orgChild4Id\`) + ) + ) AS \`actFullName\` + + FROM + ((((((((((\`posMaster\` + JOIN \`profile\` ON ((\`posMaster\`.\`current_holderId\` = \`profile\`.\`id\`))) + LEFT JOIN \`orgRoot\` ON ((\`posMaster\`.\`orgRootId\` = \`orgRoot\`.\`id\`))) + LEFT JOIN \`orgChild1\` ON ((\`posMaster\`.\`orgChild1Id\` = \`orgChild1\`.\`id\`))) + LEFT JOIN \`orgChild2\` ON ((\`posMaster\`.\`orgChild2Id\` = \`orgChild2\`.\`id\`))) + LEFT JOIN \`orgChild3\` ON ((\`posMaster\`.\`orgChild3Id\` = \`orgChild3\`.\`id\`))) + LEFT JOIN \`orgChild4\` ON ((\`posMaster\`.\`orgChild4Id\` = \`orgChild4\`.\`id\`))) + JOIN \`posLevel\` ON ((\`profile\`.\`posLevelId\` = \`posLevel\`.\`id\`))) + JOIN \`posType\` ON ((\`profile\`.\`posTypeId\` = \`posType\`.\`id\`))) + LEFT JOIN \`position\` ON ((\`posMaster\`.\`id\` = \`position\`.\`posMasterId\`))) + LEFT JOIN \`posExecutive\` ON ((\`position\`.\`posExecutiveId\` = \`posExecutive\`.\`id\`))) + WHERE + (\`position\`.\`positionIsSelected\` = TRUE)`); + await queryRunner.query(`INSERT INTO \`bma_ehr_organization_demo\`.\`typeorm_metadata\`(\`database\`, \`schema\`, \`table\`, \`type\`, \`name\`, \`value\`) VALUES (DEFAULT, ?, DEFAULT, ?, ?, ?)`, ["bma_ehr_organization_demo","VIEW","view_director","SELECT \n `profile`.`id` AS `Id`,\n `profile`.`prefix` AS `prefix`,\n `profile`.`firstName` AS `firstName`,\n `profile`.`lastName` AS `lastName`,\n `profile`.`citizenId` AS `citizenId`,\n `profile`.`position` AS `position`,\n CONCAT((CASE\n WHEN (`posMaster`.`orgChild1Id` IS NULL) THEN `orgRoot`.`orgRootShortName`\n WHEN (`posMaster`.`orgChild2Id` IS NULL) THEN `orgChild1`.`orgChild1ShortName`\n WHEN (`posMaster`.`orgChild3Id` IS NULL) THEN `orgChild2`.`orgChild2ShortName`\n WHEN (`posMaster`.`orgChild4Id` IS NULL) THEN `orgChild3`.`orgChild3ShortName`\n ELSE `orgChild4`.`orgChild4ShortName`\n END),\n `posMaster`.`posMasterNo`) AS `posNo`,\n `posMaster`.`isDirector` AS `isDirector`,\n `posLevel`.`posLevelName` AS `posLevel`,\n `posType`.`posTypeName` AS `posType`,\n `posExecutive`.`posExecutiveName` AS `posExecutiveName`,\n `orgRoot`.`isDeputy` AS `isDeputy`,\n `orgChild1`.`isOfficer` AS `isOfficer`,\n `posMaster`.`orgRootId` AS `orgRootId`,\n `posMaster`.`orgChild1Id` AS `orgChild1Id`,\n `posMaster`.`orgChild2Id` AS `orgChild2Id`,\n `posMaster`.`orgChild3Id` AS `orgChild3Id`,\n `posMaster`.`orgChild4Id` AS `orgChild4Id`,\n CONCAT(`posMaster`.`id`, `profile`.`id`) AS `key`,\n (\n SELECT `actFullNameId` \n FROM `view_director_acting` AS `acting`\n WHERE `acting`.`Id` = `posMaster`.`current_holderId` \n AND `acting`.`orgRootId` = `posMaster`.`orgRootId` \n AND (\n (`acting`.`orgChild1Id` IS NULL AND `posMaster`.`orgChild1Id` IS NULL) \n OR (`acting`.`orgChild1Id` = `posMaster`.`orgChild1Id`)\n ) \n AND (\n (`acting`.`orgChild2Id` IS NULL AND `posMaster`.`orgChild2Id` IS NULL) \n OR (`acting`.`orgChild2Id` = `posMaster`.`orgChild2Id`)\n ) \n AND (\n (`acting`.`orgChild3Id` IS NULL AND `posMaster`.`orgChild3Id` IS NULL) \n OR (`acting`.`orgChild3Id` = `posMaster`.`orgChild3Id`)\n ) \n AND (\n (`acting`.`orgChild4Id` IS NULL AND `posMaster`.`orgChild4Id` IS NULL) \n OR (`acting`.`orgChild4Id` = `posMaster`.`orgChild4Id`)\n )\n ) AS `actFullNameId`,\n (\n SELECT `actFullName` \n FROM `view_director_acting` AS `acting`\n WHERE `acting`.`Id` = `posMaster`.`current_holderId` \n AND `acting`.`orgRootId` = `posMaster`.`orgRootId` \n AND (\n (`acting`.`orgChild1Id` IS NULL AND `posMaster`.`orgChild1Id` IS NULL) \n OR (`acting`.`orgChild1Id` = `posMaster`.`orgChild1Id`)\n ) \n AND (\n (`acting`.`orgChild2Id` IS NULL AND `posMaster`.`orgChild2Id` IS NULL) \n OR (`acting`.`orgChild2Id` = `posMaster`.`orgChild2Id`)\n ) \n AND (\n (`acting`.`orgChild3Id` IS NULL AND `posMaster`.`orgChild3Id` IS NULL) \n OR (`acting`.`orgChild3Id` = `posMaster`.`orgChild3Id`)\n ) \n AND (\n (`acting`.`orgChild4Id` IS NULL AND `posMaster`.`orgChild4Id` IS NULL) \n OR (`acting`.`orgChild4Id` = `posMaster`.`orgChild4Id`)\n )\n ) AS `actFullName`\n \n FROM\n ((((((((((`posMaster`\n JOIN `profile` ON ((`posMaster`.`current_holderId` = `profile`.`id`)))\n LEFT JOIN `orgRoot` ON ((`posMaster`.`orgRootId` = `orgRoot`.`id`)))\n LEFT JOIN `orgChild1` ON ((`posMaster`.`orgChild1Id` = `orgChild1`.`id`)))\n LEFT JOIN `orgChild2` ON ((`posMaster`.`orgChild2Id` = `orgChild2`.`id`)))\n LEFT JOIN `orgChild3` ON ((`posMaster`.`orgChild3Id` = `orgChild3`.`id`)))\n LEFT JOIN `orgChild4` ON ((`posMaster`.`orgChild4Id` = `orgChild4`.`id`)))\n JOIN `posLevel` ON ((`profile`.`posLevelId` = `posLevel`.`id`)))\n JOIN `posType` ON ((`profile`.`posTypeId` = `posType`.`id`)))\n LEFT JOIN `position` ON ((`posMaster`.`id` = `position`.`posMasterId`)))\n LEFT JOIN `posExecutive` ON ((`position`.`posExecutiveId` = `posExecutive`.`id`)))\n WHERE\n (`position`.`positionIsSelected` = TRUE)"]); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DELETE FROM \`bma_ehr_organization_demo\`.\`typeorm_metadata\` WHERE \`type\` = ? AND \`name\` = ? AND \`schema\` = ?`, ["VIEW","view_director","bma_ehr_organization_demo"]); + await queryRunner.query(`DROP VIEW \`view_director\``); + await queryRunner.query(`DELETE FROM \`bma_ehr_organization_demo\`.\`typeorm_metadata\` WHERE \`type\` = ? AND \`name\` = ? AND \`schema\` = ?`, ["VIEW","view_director_acting","bma_ehr_organization_demo"]); + await queryRunner.query(`DROP VIEW \`view_director_acting\``); + } + +} diff --git a/src/migration/1737536238830-UpdateviewAddOfficer2.ts b/src/migration/1737536238830-UpdateviewAddOfficer2.ts new file mode 100644 index 00000000..3816204e --- /dev/null +++ b/src/migration/1737536238830-UpdateviewAddOfficer2.ts @@ -0,0 +1,302 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateviewAddOfficer21737536238830 implements MigrationInterface { + name = 'UpdateviewAddOfficer21737536238830' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DELETE FROM \`bma_ehr_organization_demo\`.\`typeorm_metadata\` WHERE \`type\` = ? AND \`name\` = ? AND \`schema\` = ?`, ["VIEW","view_director","bma_ehr_organization_demo"]); + await queryRunner.query(`DROP VIEW \`view_director\``); + await queryRunner.query(`DELETE FROM \`bma_ehr_organization_demo\`.\`typeorm_metadata\` WHERE \`type\` = ? AND \`name\` = ? AND \`schema\` = ?`, ["VIEW","view_director_acting","bma_ehr_organization_demo"]); + await queryRunner.query(`DROP VIEW \`view_director_acting\``); + await queryRunner.query(`CREATE VIEW \`view_director_acting\` AS SELECT + \`profileChild\`.\`id\` AS \`Id\`, + \`profileChild\`.\`prefix\` AS \`prefix\`, + \`profileChild\`.\`firstName\` AS \`firstName\`, + \`profileChild\`.\`lastName\` AS \`lastName\`, + \`profileChild\`.\`citizenId\` AS \`citizenId\`, + \`profileChild\`.\`position\` AS \`position\`, + CONCAT((CASE + WHEN (\`posMaster\`.\`orgChild1Id\` IS NULL) THEN \`orgRootChild\`.\`orgRootShortName\` + WHEN (\`posMaster\`.\`orgChild2Id\` IS NULL) THEN \`orgChild1Child\`.\`orgChild1ShortName\` + WHEN (\`posMaster\`.\`orgChild3Id\` IS NULL) THEN \`orgChild2Child\`.\`orgChild2ShortName\` + WHEN (\`posMaster\`.\`orgChild4Id\` IS NULL) THEN \`orgChild3Child\`.\`orgChild3ShortName\` + ELSE \`orgChild4Child\`.\`orgChild4ShortName\` + END), + \`posMaster\`.\`posMasterNo\`) AS \`posNo\`, + \`posMasterChild\`.\`isDirector\` AS \`isDirectorChild\`, + \`posMaster\`.\`isDirector\` AS \`isDirector\`, + \`posLevel\`.\`posLevelName\` AS \`posLevel\`, + \`posType\`.\`posTypeName\` AS \`posType\`, + \`posExecutive\`.\`posExecutiveName\` AS \`posExecutiveName\`, + \`orgRoot\`.\`isDeputy\` AS \`isDeputy\`, + \`orgChild1\`.\`isOfficer\` AS \`isOfficer\`, + \`posMaster\`.\`orgRevisionId\` AS \`orgRevisionId\`, + \`posMaster\`.\`orgRootId\` AS \`orgRootId\`, + \`posMaster\`.\`orgChild1Id\` AS \`orgChild1Id\`, + \`posMaster\`.\`orgChild2Id\` AS \`orgChild2Id\`, + \`posMaster\`.\`orgChild3Id\` AS \`orgChild3Id\`, + \`posMaster\`.\`orgChild4Id\` AS \`orgChild4Id\`, + CONCAT(\`posMaster\`.\`id\`, \`profileChild\`.\`id\`) AS \`key\`, + \`profile\`.\`id\` AS \`actFullNameId\`, + CONCAT(\`profile\`.\`prefix\`, + \`profile\`.\`firstName\`, + ' ', + \`profile\`.\`lastName\`) AS \`actFullName\` + FROM + (((((((((((((((\`posMasterAct\` + JOIN \`posMaster\` \`posMasterChild\` ON ((\`posMasterAct\`.\`posMasterChildId\` = \`posMasterChild\`.\`id\`))) + JOIN \`profile\` \`profileChild\` ON ((\`posMasterChild\`.\`current_holderId\` = \`profileChild\`.\`id\`))) + LEFT JOIN \`orgRoot\` \`orgRootChild\` ON ((\`posMasterChild\`.\`orgRootId\` = \`orgRootChild\`.\`id\`))) + LEFT JOIN \`orgChild1\` \`orgChild1Child\` ON ((\`posMasterChild\`.\`orgChild1Id\` = \`orgChild1Child\`.\`id\`))) + LEFT JOIN \`orgChild2\` \`orgChild2Child\` ON ((\`posMasterChild\`.\`orgChild2Id\` = \`orgChild2Child\`.\`id\`))) + LEFT JOIN \`orgChild3\` \`orgChild3Child\` ON ((\`posMasterChild\`.\`orgChild3Id\` = \`orgChild3Child\`.\`id\`))) + LEFT JOIN \`orgChild4\` \`orgChild4Child\` ON ((\`posMasterChild\`.\`orgChild4Id\` = \`orgChild4Child\`.\`id\`))) + JOIN \`posLevel\` ON ((\`profileChild\`.\`posLevelId\` = \`posLevel\`.\`id\`))) + JOIN \`posType\` ON ((\`profileChild\`.\`posTypeId\` = \`posType\`.\`id\`))) + JOIN \`posMaster\` ON ((\`posMasterAct\`.\`posMasterId\` = \`posMaster\`.\`id\`))) + LEFT JOIN \`orgRoot\` ON ((\`posMaster\`.\`orgRootId\` = \`orgRoot\`.\`id\`))) + LEFT JOIN \`orgChild1\` ON ((\`posMaster\`.\`orgChild1Id\` = \`orgChild1\`.\`id\`))) + JOIN \`profile\` ON ((\`posMaster\`.\`current_holderId\` = \`profile\`.\`id\`))) + LEFT JOIN \`position\` ON ((\`posMasterChild\`.\`id\` = \`position\`.\`posMasterId\`))) + LEFT JOIN \`posExecutive\` ON ((\`position\`.\`posExecutiveId\` = \`posExecutive\`.\`id\`))) + WHERE + (\`position\`.\`positionIsSelected\` = TRUE)`); + await queryRunner.query(`INSERT INTO \`bma_ehr_organization_demo\`.\`typeorm_metadata\`(\`database\`, \`schema\`, \`table\`, \`type\`, \`name\`, \`value\`) VALUES (DEFAULT, ?, DEFAULT, ?, ?, ?)`, ["bma_ehr_organization_demo","VIEW","view_director_acting","SELECT \n `profileChild`.`id` AS `Id`,\n `profileChild`.`prefix` AS `prefix`,\n `profileChild`.`firstName` AS `firstName`,\n `profileChild`.`lastName` AS `lastName`,\n `profileChild`.`citizenId` AS `citizenId`,\n `profileChild`.`position` AS `position`,\n CONCAT((CASE\n WHEN (`posMaster`.`orgChild1Id` IS NULL) THEN `orgRootChild`.`orgRootShortName`\n WHEN (`posMaster`.`orgChild2Id` IS NULL) THEN `orgChild1Child`.`orgChild1ShortName`\n WHEN (`posMaster`.`orgChild3Id` IS NULL) THEN `orgChild2Child`.`orgChild2ShortName`\n WHEN (`posMaster`.`orgChild4Id` IS NULL) THEN `orgChild3Child`.`orgChild3ShortName`\n ELSE `orgChild4Child`.`orgChild4ShortName`\n END),\n `posMaster`.`posMasterNo`) AS `posNo`,\n `posMasterChild`.`isDirector` AS `isDirectorChild`,\n `posMaster`.`isDirector` AS `isDirector`,\n `posLevel`.`posLevelName` AS `posLevel`,\n `posType`.`posTypeName` AS `posType`,\n `posExecutive`.`posExecutiveName` AS `posExecutiveName`,\n `orgRoot`.`isDeputy` AS `isDeputy`,\n `orgChild1`.`isOfficer` AS `isOfficer`,\n `posMaster`.`orgRevisionId` AS `orgRevisionId`,\n `posMaster`.`orgRootId` AS `orgRootId`,\n `posMaster`.`orgChild1Id` AS `orgChild1Id`,\n `posMaster`.`orgChild2Id` AS `orgChild2Id`,\n `posMaster`.`orgChild3Id` AS `orgChild3Id`,\n `posMaster`.`orgChild4Id` AS `orgChild4Id`,\n CONCAT(`posMaster`.`id`, `profileChild`.`id`) AS `key`,\n `profile`.`id` AS `actFullNameId`,\n CONCAT(`profile`.`prefix`,\n `profile`.`firstName`,\n ' ',\n `profile`.`lastName`) AS `actFullName`\n FROM\n (((((((((((((((`posMasterAct`\n JOIN `posMaster` `posMasterChild` ON ((`posMasterAct`.`posMasterChildId` = `posMasterChild`.`id`)))\n JOIN `profile` `profileChild` ON ((`posMasterChild`.`current_holderId` = `profileChild`.`id`)))\n LEFT JOIN `orgRoot` `orgRootChild` ON ((`posMasterChild`.`orgRootId` = `orgRootChild`.`id`)))\n LEFT JOIN `orgChild1` `orgChild1Child` ON ((`posMasterChild`.`orgChild1Id` = `orgChild1Child`.`id`)))\n LEFT JOIN `orgChild2` `orgChild2Child` ON ((`posMasterChild`.`orgChild2Id` = `orgChild2Child`.`id`)))\n LEFT JOIN `orgChild3` `orgChild3Child` ON ((`posMasterChild`.`orgChild3Id` = `orgChild3Child`.`id`)))\n LEFT JOIN `orgChild4` `orgChild4Child` ON ((`posMasterChild`.`orgChild4Id` = `orgChild4Child`.`id`)))\n JOIN `posLevel` ON ((`profileChild`.`posLevelId` = `posLevel`.`id`)))\n JOIN `posType` ON ((`profileChild`.`posTypeId` = `posType`.`id`)))\n JOIN `posMaster` ON ((`posMasterAct`.`posMasterId` = `posMaster`.`id`)))\n LEFT JOIN `orgRoot` ON ((`posMaster`.`orgRootId` = `orgRoot`.`id`)))\n LEFT JOIN `orgChild1` ON ((`posMaster`.`orgChild1Id` = `orgChild1`.`id`)))\n JOIN `profile` ON ((`posMaster`.`current_holderId` = `profile`.`id`)))\n LEFT JOIN `position` ON ((`posMasterChild`.`id` = `position`.`posMasterId`)))\n LEFT JOIN `posExecutive` ON ((`position`.`posExecutiveId` = `posExecutive`.`id`)))\n WHERE\n (`position`.`positionIsSelected` = TRUE)"]); + await queryRunner.query(`CREATE VIEW \`view_director\` AS SELECT + \`profile\`.\`id\` AS \`Id\`, + \`profile\`.\`prefix\` AS \`prefix\`, + \`profile\`.\`firstName\` AS \`firstName\`, + \`profile\`.\`lastName\` AS \`lastName\`, + \`profile\`.\`citizenId\` AS \`citizenId\`, + \`profile\`.\`position\` AS \`position\`, + CONCAT((CASE + WHEN (\`posMaster\`.\`orgChild1Id\` IS NULL) THEN \`orgRoot\`.\`orgRootShortName\` + WHEN (\`posMaster\`.\`orgChild2Id\` IS NULL) THEN \`orgChild1\`.\`orgChild1ShortName\` + WHEN (\`posMaster\`.\`orgChild3Id\` IS NULL) THEN \`orgChild2\`.\`orgChild2ShortName\` + WHEN (\`posMaster\`.\`orgChild4Id\` IS NULL) THEN \`orgChild3\`.\`orgChild3ShortName\` + ELSE \`orgChild4\`.\`orgChild4ShortName\` + END), + \`posMaster\`.\`posMasterNo\`) AS \`posNo\`, + \`posMaster\`.\`isDirector\` AS \`isDirector\`, + \`posLevel\`.\`posLevelName\` AS \`posLevel\`, + \`posType\`.\`posTypeName\` AS \`posType\`, + \`posExecutive\`.\`posExecutiveName\` AS \`posExecutiveName\`, + \`orgRoot\`.\`isDeputy\` AS \`isDeputy\`, + \`orgChild1\`.\`isOfficer\` AS \`isOfficer\`, + \`posMaster\`.\`orgRevisionId\` AS \`orgRevisionId\`, + \`posMaster\`.\`orgRootId\` AS \`orgRootId\`, + \`posMaster\`.\`orgChild1Id\` AS \`orgChild1Id\`, + \`posMaster\`.\`orgChild2Id\` AS \`orgChild2Id\`, + \`posMaster\`.\`orgChild3Id\` AS \`orgChild3Id\`, + \`posMaster\`.\`orgChild4Id\` AS \`orgChild4Id\`, + CONCAT(\`posMaster\`.\`id\`, \`profile\`.\`id\`) AS \`key\`, + ( + SELECT \`actFullNameId\` + FROM \`view_director_acting\` AS \`acting\` + WHERE \`acting\`.\`Id\` = \`posMaster\`.\`current_holderId\` + AND \`acting\`.\`orgRootId\` = \`posMaster\`.\`orgRootId\` + AND ( + (\`acting\`.\`orgChild1Id\` IS NULL AND \`posMaster\`.\`orgChild1Id\` IS NULL) + OR (\`acting\`.\`orgChild1Id\` = \`posMaster\`.\`orgChild1Id\`) + ) + AND ( + (\`acting\`.\`orgChild2Id\` IS NULL AND \`posMaster\`.\`orgChild2Id\` IS NULL) + OR (\`acting\`.\`orgChild2Id\` = \`posMaster\`.\`orgChild2Id\`) + ) + AND ( + (\`acting\`.\`orgChild3Id\` IS NULL AND \`posMaster\`.\`orgChild3Id\` IS NULL) + OR (\`acting\`.\`orgChild3Id\` = \`posMaster\`.\`orgChild3Id\`) + ) + AND ( + (\`acting\`.\`orgChild4Id\` IS NULL AND \`posMaster\`.\`orgChild4Id\` IS NULL) + OR (\`acting\`.\`orgChild4Id\` = \`posMaster\`.\`orgChild4Id\`) + ) + ) AS \`actFullNameId\`, + ( + SELECT \`actFullName\` + FROM \`view_director_acting\` AS \`acting\` + WHERE \`acting\`.\`Id\` = \`posMaster\`.\`current_holderId\` + AND \`acting\`.\`orgRootId\` = \`posMaster\`.\`orgRootId\` + AND ( + (\`acting\`.\`orgChild1Id\` IS NULL AND \`posMaster\`.\`orgChild1Id\` IS NULL) + OR (\`acting\`.\`orgChild1Id\` = \`posMaster\`.\`orgChild1Id\`) + ) + AND ( + (\`acting\`.\`orgChild2Id\` IS NULL AND \`posMaster\`.\`orgChild2Id\` IS NULL) + OR (\`acting\`.\`orgChild2Id\` = \`posMaster\`.\`orgChild2Id\`) + ) + AND ( + (\`acting\`.\`orgChild3Id\` IS NULL AND \`posMaster\`.\`orgChild3Id\` IS NULL) + OR (\`acting\`.\`orgChild3Id\` = \`posMaster\`.\`orgChild3Id\`) + ) + AND ( + (\`acting\`.\`orgChild4Id\` IS NULL AND \`posMaster\`.\`orgChild4Id\` IS NULL) + OR (\`acting\`.\`orgChild4Id\` = \`posMaster\`.\`orgChild4Id\`) + ) + ) AS \`actFullName\` + + FROM + ((((((((((\`posMaster\` + JOIN \`profile\` ON ((\`posMaster\`.\`current_holderId\` = \`profile\`.\`id\`))) + LEFT JOIN \`orgRoot\` ON ((\`posMaster\`.\`orgRootId\` = \`orgRoot\`.\`id\`))) + LEFT JOIN \`orgChild1\` ON ((\`posMaster\`.\`orgChild1Id\` = \`orgChild1\`.\`id\`))) + LEFT JOIN \`orgChild2\` ON ((\`posMaster\`.\`orgChild2Id\` = \`orgChild2\`.\`id\`))) + LEFT JOIN \`orgChild3\` ON ((\`posMaster\`.\`orgChild3Id\` = \`orgChild3\`.\`id\`))) + LEFT JOIN \`orgChild4\` ON ((\`posMaster\`.\`orgChild4Id\` = \`orgChild4\`.\`id\`))) + JOIN \`posLevel\` ON ((\`profile\`.\`posLevelId\` = \`posLevel\`.\`id\`))) + JOIN \`posType\` ON ((\`profile\`.\`posTypeId\` = \`posType\`.\`id\`))) + LEFT JOIN \`position\` ON ((\`posMaster\`.\`id\` = \`position\`.\`posMasterId\`))) + LEFT JOIN \`posExecutive\` ON ((\`position\`.\`posExecutiveId\` = \`posExecutive\`.\`id\`))) + WHERE + (\`position\`.\`positionIsSelected\` = TRUE)`); + await queryRunner.query(`INSERT INTO \`bma_ehr_organization_demo\`.\`typeorm_metadata\`(\`database\`, \`schema\`, \`table\`, \`type\`, \`name\`, \`value\`) VALUES (DEFAULT, ?, DEFAULT, ?, ?, ?)`, ["bma_ehr_organization_demo","VIEW","view_director","SELECT \n `profile`.`id` AS `Id`,\n `profile`.`prefix` AS `prefix`,\n `profile`.`firstName` AS `firstName`,\n `profile`.`lastName` AS `lastName`,\n `profile`.`citizenId` AS `citizenId`,\n `profile`.`position` AS `position`,\n CONCAT((CASE\n WHEN (`posMaster`.`orgChild1Id` IS NULL) THEN `orgRoot`.`orgRootShortName`\n WHEN (`posMaster`.`orgChild2Id` IS NULL) THEN `orgChild1`.`orgChild1ShortName`\n WHEN (`posMaster`.`orgChild3Id` IS NULL) THEN `orgChild2`.`orgChild2ShortName`\n WHEN (`posMaster`.`orgChild4Id` IS NULL) THEN `orgChild3`.`orgChild3ShortName`\n ELSE `orgChild4`.`orgChild4ShortName`\n END),\n `posMaster`.`posMasterNo`) AS `posNo`,\n `posMaster`.`isDirector` AS `isDirector`,\n `posLevel`.`posLevelName` AS `posLevel`,\n `posType`.`posTypeName` AS `posType`,\n `posExecutive`.`posExecutiveName` AS `posExecutiveName`,\n `orgRoot`.`isDeputy` AS `isDeputy`,\n `orgChild1`.`isOfficer` AS `isOfficer`,\n `posMaster`.`orgRevisionId` AS `orgRevisionId`,\n `posMaster`.`orgRootId` AS `orgRootId`,\n `posMaster`.`orgChild1Id` AS `orgChild1Id`,\n `posMaster`.`orgChild2Id` AS `orgChild2Id`,\n `posMaster`.`orgChild3Id` AS `orgChild3Id`,\n `posMaster`.`orgChild4Id` AS `orgChild4Id`,\n CONCAT(`posMaster`.`id`, `profile`.`id`) AS `key`,\n (\n SELECT `actFullNameId` \n FROM `view_director_acting` AS `acting`\n WHERE `acting`.`Id` = `posMaster`.`current_holderId` \n AND `acting`.`orgRootId` = `posMaster`.`orgRootId` \n AND (\n (`acting`.`orgChild1Id` IS NULL AND `posMaster`.`orgChild1Id` IS NULL) \n OR (`acting`.`orgChild1Id` = `posMaster`.`orgChild1Id`)\n ) \n AND (\n (`acting`.`orgChild2Id` IS NULL AND `posMaster`.`orgChild2Id` IS NULL) \n OR (`acting`.`orgChild2Id` = `posMaster`.`orgChild2Id`)\n ) \n AND (\n (`acting`.`orgChild3Id` IS NULL AND `posMaster`.`orgChild3Id` IS NULL) \n OR (`acting`.`orgChild3Id` = `posMaster`.`orgChild3Id`)\n ) \n AND (\n (`acting`.`orgChild4Id` IS NULL AND `posMaster`.`orgChild4Id` IS NULL) \n OR (`acting`.`orgChild4Id` = `posMaster`.`orgChild4Id`)\n )\n ) AS `actFullNameId`,\n (\n SELECT `actFullName` \n FROM `view_director_acting` AS `acting`\n WHERE `acting`.`Id` = `posMaster`.`current_holderId` \n AND `acting`.`orgRootId` = `posMaster`.`orgRootId` \n AND (\n (`acting`.`orgChild1Id` IS NULL AND `posMaster`.`orgChild1Id` IS NULL) \n OR (`acting`.`orgChild1Id` = `posMaster`.`orgChild1Id`)\n ) \n AND (\n (`acting`.`orgChild2Id` IS NULL AND `posMaster`.`orgChild2Id` IS NULL) \n OR (`acting`.`orgChild2Id` = `posMaster`.`orgChild2Id`)\n ) \n AND (\n (`acting`.`orgChild3Id` IS NULL AND `posMaster`.`orgChild3Id` IS NULL) \n OR (`acting`.`orgChild3Id` = `posMaster`.`orgChild3Id`)\n ) \n AND (\n (`acting`.`orgChild4Id` IS NULL AND `posMaster`.`orgChild4Id` IS NULL) \n OR (`acting`.`orgChild4Id` = `posMaster`.`orgChild4Id`)\n )\n ) AS `actFullName`\n \n FROM\n ((((((((((`posMaster`\n JOIN `profile` ON ((`posMaster`.`current_holderId` = `profile`.`id`)))\n LEFT JOIN `orgRoot` ON ((`posMaster`.`orgRootId` = `orgRoot`.`id`)))\n LEFT JOIN `orgChild1` ON ((`posMaster`.`orgChild1Id` = `orgChild1`.`id`)))\n LEFT JOIN `orgChild2` ON ((`posMaster`.`orgChild2Id` = `orgChild2`.`id`)))\n LEFT JOIN `orgChild3` ON ((`posMaster`.`orgChild3Id` = `orgChild3`.`id`)))\n LEFT JOIN `orgChild4` ON ((`posMaster`.`orgChild4Id` = `orgChild4`.`id`)))\n JOIN `posLevel` ON ((`profile`.`posLevelId` = `posLevel`.`id`)))\n JOIN `posType` ON ((`profile`.`posTypeId` = `posType`.`id`)))\n LEFT JOIN `position` ON ((`posMaster`.`id` = `position`.`posMasterId`)))\n LEFT JOIN `posExecutive` ON ((`position`.`posExecutiveId` = `posExecutive`.`id`)))\n WHERE\n (`position`.`positionIsSelected` = TRUE)"]); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DELETE FROM \`bma_ehr_organization_demo\`.\`typeorm_metadata\` WHERE \`type\` = ? AND \`name\` = ? AND \`schema\` = ?`, ["VIEW","view_director","bma_ehr_organization_demo"]); + await queryRunner.query(`DROP VIEW \`view_director\``); + await queryRunner.query(`DELETE FROM \`bma_ehr_organization_demo\`.\`typeorm_metadata\` WHERE \`type\` = ? AND \`name\` = ? AND \`schema\` = ?`, ["VIEW","view_director_acting","bma_ehr_organization_demo"]); + await queryRunner.query(`DROP VIEW \`view_director_acting\``); + await queryRunner.query(`CREATE VIEW \`view_director_acting\` AS SELECT + \`profileChild\`.\`id\` AS \`Id\`, + \`profileChild\`.\`prefix\` AS \`prefix\`, + \`profileChild\`.\`firstName\` AS \`firstName\`, + \`profileChild\`.\`lastName\` AS \`lastName\`, + \`profileChild\`.\`citizenId\` AS \`citizenId\`, + \`profileChild\`.\`position\` AS \`position\`, + CONCAT((CASE + WHEN (\`posMaster\`.\`orgChild1Id\` IS NULL) THEN \`orgRootChild\`.\`orgRootShortName\` + WHEN (\`posMaster\`.\`orgChild2Id\` IS NULL) THEN \`orgChild1Child\`.\`orgChild1ShortName\` + WHEN (\`posMaster\`.\`orgChild3Id\` IS NULL) THEN \`orgChild2Child\`.\`orgChild2ShortName\` + WHEN (\`posMaster\`.\`orgChild4Id\` IS NULL) THEN \`orgChild3Child\`.\`orgChild3ShortName\` + ELSE \`orgChild4Child\`.\`orgChild4ShortName\` + END), + \`posMaster\`.\`posMasterNo\`) AS \`posNo\`, + \`posMasterChild\`.\`isDirector\` AS \`isDirectorChild\`, + \`posMaster\`.\`isDirector\` AS \`isDirector\`, + \`posLevel\`.\`posLevelName\` AS \`posLevel\`, + \`posType\`.\`posTypeName\` AS \`posType\`, + \`posExecutive\`.\`posExecutiveName\` AS \`posExecutiveName\`, + \`orgRoot\`.\`isDeputy\` AS \`isDeputy\`, + \`orgChild1\`.\`isOfficer\` AS \`isOfficer\`, + \`posMaster\`.\`orgRootId\` AS \`orgRootId\`, + \`posMaster\`.\`orgChild1Id\` AS \`orgChild1Id\`, + \`posMaster\`.\`orgChild2Id\` AS \`orgChild2Id\`, + \`posMaster\`.\`orgChild3Id\` AS \`orgChild3Id\`, + \`posMaster\`.\`orgChild4Id\` AS \`orgChild4Id\`, + CONCAT(\`posMaster\`.\`id\`, \`profileChild\`.\`id\`) AS \`key\`, + \`profile\`.\`id\` AS \`actFullNameId\`, + CONCAT(\`profile\`.\`prefix\`, + \`profile\`.\`firstName\`, + ' ', + \`profile\`.\`lastName\`) AS \`actFullName\` + FROM + (((((((((((((((\`posMasterAct\` + JOIN \`posMaster\` \`posMasterChild\` ON ((\`posMasterAct\`.\`posMasterChildId\` = \`posMasterChild\`.\`id\`))) + JOIN \`profile\` \`profileChild\` ON ((\`posMasterChild\`.\`current_holderId\` = \`profileChild\`.\`id\`))) + LEFT JOIN \`orgRoot\` \`orgRootChild\` ON ((\`posMasterChild\`.\`orgRootId\` = \`orgRootChild\`.\`id\`))) + LEFT JOIN \`orgChild1\` \`orgChild1Child\` ON ((\`posMasterChild\`.\`orgChild1Id\` = \`orgChild1Child\`.\`id\`))) + LEFT JOIN \`orgChild2\` \`orgChild2Child\` ON ((\`posMasterChild\`.\`orgChild2Id\` = \`orgChild2Child\`.\`id\`))) + LEFT JOIN \`orgChild3\` \`orgChild3Child\` ON ((\`posMasterChild\`.\`orgChild3Id\` = \`orgChild3Child\`.\`id\`))) + LEFT JOIN \`orgChild4\` \`orgChild4Child\` ON ((\`posMasterChild\`.\`orgChild4Id\` = \`orgChild4Child\`.\`id\`))) + JOIN \`posLevel\` ON ((\`profileChild\`.\`posLevelId\` = \`posLevel\`.\`id\`))) + JOIN \`posType\` ON ((\`profileChild\`.\`posTypeId\` = \`posType\`.\`id\`))) + JOIN \`posMaster\` ON ((\`posMasterAct\`.\`posMasterId\` = \`posMaster\`.\`id\`))) + LEFT JOIN \`orgRoot\` ON ((\`posMaster\`.\`orgRootId\` = \`orgRoot\`.\`id\`))) + LEFT JOIN \`orgChild1\` ON ((\`posMaster\`.\`orgChild1Id\` = \`orgChild1\`.\`id\`))) + JOIN \`profile\` ON ((\`posMaster\`.\`current_holderId\` = \`profile\`.\`id\`))) + LEFT JOIN \`position\` ON ((\`posMasterChild\`.\`id\` = \`position\`.\`posMasterId\`))) + LEFT JOIN \`posExecutive\` ON ((\`position\`.\`posExecutiveId\` = \`posExecutive\`.\`id\`))) + WHERE + (\`position\`.\`positionIsSelected\` = TRUE)`); + await queryRunner.query(`INSERT INTO \`bma_ehr_organization_demo\`.\`typeorm_metadata\`(\`database\`, \`schema\`, \`table\`, \`type\`, \`name\`, \`value\`) VALUES (DEFAULT, ?, DEFAULT, ?, ?, ?)`, ["bma_ehr_organization_demo","VIEW","view_director_acting","SELECT \n `profileChild`.`id` AS `Id`,\n `profileChild`.`prefix` AS `prefix`,\n `profileChild`.`firstName` AS `firstName`,\n `profileChild`.`lastName` AS `lastName`,\n `profileChild`.`citizenId` AS `citizenId`,\n `profileChild`.`position` AS `position`,\n CONCAT((CASE\n WHEN (`posMaster`.`orgChild1Id` IS NULL) THEN `orgRootChild`.`orgRootShortName`\n WHEN (`posMaster`.`orgChild2Id` IS NULL) THEN `orgChild1Child`.`orgChild1ShortName`\n WHEN (`posMaster`.`orgChild3Id` IS NULL) THEN `orgChild2Child`.`orgChild2ShortName`\n WHEN (`posMaster`.`orgChild4Id` IS NULL) THEN `orgChild3Child`.`orgChild3ShortName`\n ELSE `orgChild4Child`.`orgChild4ShortName`\n END),\n `posMaster`.`posMasterNo`) AS `posNo`,\n `posMasterChild`.`isDirector` AS `isDirectorChild`,\n `posMaster`.`isDirector` AS `isDirector`,\n `posLevel`.`posLevelName` AS `posLevel`,\n `posType`.`posTypeName` AS `posType`,\n `posExecutive`.`posExecutiveName` AS `posExecutiveName`,\n `orgRoot`.`isDeputy` AS `isDeputy`,\n `orgChild1`.`isOfficer` AS `isOfficer`,\n `posMaster`.`orgRootId` AS `orgRootId`,\n `posMaster`.`orgChild1Id` AS `orgChild1Id`,\n `posMaster`.`orgChild2Id` AS `orgChild2Id`,\n `posMaster`.`orgChild3Id` AS `orgChild3Id`,\n `posMaster`.`orgChild4Id` AS `orgChild4Id`,\n CONCAT(`posMaster`.`id`, `profileChild`.`id`) AS `key`,\n `profile`.`id` AS `actFullNameId`,\n CONCAT(`profile`.`prefix`,\n `profile`.`firstName`,\n ' ',\n `profile`.`lastName`) AS `actFullName`\n FROM\n (((((((((((((((`posMasterAct`\n JOIN `posMaster` `posMasterChild` ON ((`posMasterAct`.`posMasterChildId` = `posMasterChild`.`id`)))\n JOIN `profile` `profileChild` ON ((`posMasterChild`.`current_holderId` = `profileChild`.`id`)))\n LEFT JOIN `orgRoot` `orgRootChild` ON ((`posMasterChild`.`orgRootId` = `orgRootChild`.`id`)))\n LEFT JOIN `orgChild1` `orgChild1Child` ON ((`posMasterChild`.`orgChild1Id` = `orgChild1Child`.`id`)))\n LEFT JOIN `orgChild2` `orgChild2Child` ON ((`posMasterChild`.`orgChild2Id` = `orgChild2Child`.`id`)))\n LEFT JOIN `orgChild3` `orgChild3Child` ON ((`posMasterChild`.`orgChild3Id` = `orgChild3Child`.`id`)))\n LEFT JOIN `orgChild4` `orgChild4Child` ON ((`posMasterChild`.`orgChild4Id` = `orgChild4Child`.`id`)))\n JOIN `posLevel` ON ((`profileChild`.`posLevelId` = `posLevel`.`id`)))\n JOIN `posType` ON ((`profileChild`.`posTypeId` = `posType`.`id`)))\n JOIN `posMaster` ON ((`posMasterAct`.`posMasterId` = `posMaster`.`id`)))\n LEFT JOIN `orgRoot` ON ((`posMaster`.`orgRootId` = `orgRoot`.`id`)))\n LEFT JOIN `orgChild1` ON ((`posMaster`.`orgChild1Id` = `orgChild1`.`id`)))\n JOIN `profile` ON ((`posMaster`.`current_holderId` = `profile`.`id`)))\n LEFT JOIN `position` ON ((`posMasterChild`.`id` = `position`.`posMasterId`)))\n LEFT JOIN `posExecutive` ON ((`position`.`posExecutiveId` = `posExecutive`.`id`)))\n WHERE\n (`position`.`positionIsSelected` = TRUE)"]); + await queryRunner.query(`CREATE VIEW \`view_director\` AS SELECT + \`profile\`.\`id\` AS \`Id\`, + \`profile\`.\`prefix\` AS \`prefix\`, + \`profile\`.\`firstName\` AS \`firstName\`, + \`profile\`.\`lastName\` AS \`lastName\`, + \`profile\`.\`citizenId\` AS \`citizenId\`, + \`profile\`.\`position\` AS \`position\`, + CONCAT((CASE + WHEN (\`posMaster\`.\`orgChild1Id\` IS NULL) THEN \`orgRoot\`.\`orgRootShortName\` + WHEN (\`posMaster\`.\`orgChild2Id\` IS NULL) THEN \`orgChild1\`.\`orgChild1ShortName\` + WHEN (\`posMaster\`.\`orgChild3Id\` IS NULL) THEN \`orgChild2\`.\`orgChild2ShortName\` + WHEN (\`posMaster\`.\`orgChild4Id\` IS NULL) THEN \`orgChild3\`.\`orgChild3ShortName\` + ELSE \`orgChild4\`.\`orgChild4ShortName\` + END), + \`posMaster\`.\`posMasterNo\`) AS \`posNo\`, + \`posMaster\`.\`isDirector\` AS \`isDirector\`, + \`posLevel\`.\`posLevelName\` AS \`posLevel\`, + \`posType\`.\`posTypeName\` AS \`posType\`, + \`posExecutive\`.\`posExecutiveName\` AS \`posExecutiveName\`, + \`orgRoot\`.\`isDeputy\` AS \`isDeputy\`, + \`orgChild1\`.\`isOfficer\` AS \`isOfficer\`, + \`posMaster\`.\`orgRootId\` AS \`orgRootId\`, + \`posMaster\`.\`orgChild1Id\` AS \`orgChild1Id\`, + \`posMaster\`.\`orgChild2Id\` AS \`orgChild2Id\`, + \`posMaster\`.\`orgChild3Id\` AS \`orgChild3Id\`, + \`posMaster\`.\`orgChild4Id\` AS \`orgChild4Id\`, + CONCAT(\`posMaster\`.\`id\`, \`profile\`.\`id\`) AS \`key\`, + ( + SELECT \`actFullNameId\` + FROM \`view_director_acting\` AS \`acting\` + WHERE \`acting\`.\`Id\` = \`posMaster\`.\`current_holderId\` + AND \`acting\`.\`orgRootId\` = \`posMaster\`.\`orgRootId\` + AND ( + (\`acting\`.\`orgChild1Id\` IS NULL AND \`posMaster\`.\`orgChild1Id\` IS NULL) + OR (\`acting\`.\`orgChild1Id\` = \`posMaster\`.\`orgChild1Id\`) + ) + AND ( + (\`acting\`.\`orgChild2Id\` IS NULL AND \`posMaster\`.\`orgChild2Id\` IS NULL) + OR (\`acting\`.\`orgChild2Id\` = \`posMaster\`.\`orgChild2Id\`) + ) + AND ( + (\`acting\`.\`orgChild3Id\` IS NULL AND \`posMaster\`.\`orgChild3Id\` IS NULL) + OR (\`acting\`.\`orgChild3Id\` = \`posMaster\`.\`orgChild3Id\`) + ) + AND ( + (\`acting\`.\`orgChild4Id\` IS NULL AND \`posMaster\`.\`orgChild4Id\` IS NULL) + OR (\`acting\`.\`orgChild4Id\` = \`posMaster\`.\`orgChild4Id\`) + ) + ) AS \`actFullNameId\`, + ( + SELECT \`actFullName\` + FROM \`view_director_acting\` AS \`acting\` + WHERE \`acting\`.\`Id\` = \`posMaster\`.\`current_holderId\` + AND \`acting\`.\`orgRootId\` = \`posMaster\`.\`orgRootId\` + AND ( + (\`acting\`.\`orgChild1Id\` IS NULL AND \`posMaster\`.\`orgChild1Id\` IS NULL) + OR (\`acting\`.\`orgChild1Id\` = \`posMaster\`.\`orgChild1Id\`) + ) + AND ( + (\`acting\`.\`orgChild2Id\` IS NULL AND \`posMaster\`.\`orgChild2Id\` IS NULL) + OR (\`acting\`.\`orgChild2Id\` = \`posMaster\`.\`orgChild2Id\`) + ) + AND ( + (\`acting\`.\`orgChild3Id\` IS NULL AND \`posMaster\`.\`orgChild3Id\` IS NULL) + OR (\`acting\`.\`orgChild3Id\` = \`posMaster\`.\`orgChild3Id\`) + ) + AND ( + (\`acting\`.\`orgChild4Id\` IS NULL AND \`posMaster\`.\`orgChild4Id\` IS NULL) + OR (\`acting\`.\`orgChild4Id\` = \`posMaster\`.\`orgChild4Id\`) + ) + ) AS \`actFullName\` + + FROM + ((((((((((\`posMaster\` + JOIN \`profile\` ON ((\`posMaster\`.\`current_holderId\` = \`profile\`.\`id\`))) + LEFT JOIN \`orgRoot\` ON ((\`posMaster\`.\`orgRootId\` = \`orgRoot\`.\`id\`))) + LEFT JOIN \`orgChild1\` ON ((\`posMaster\`.\`orgChild1Id\` = \`orgChild1\`.\`id\`))) + LEFT JOIN \`orgChild2\` ON ((\`posMaster\`.\`orgChild2Id\` = \`orgChild2\`.\`id\`))) + LEFT JOIN \`orgChild3\` ON ((\`posMaster\`.\`orgChild3Id\` = \`orgChild3\`.\`id\`))) + LEFT JOIN \`orgChild4\` ON ((\`posMaster\`.\`orgChild4Id\` = \`orgChild4\`.\`id\`))) + JOIN \`posLevel\` ON ((\`profile\`.\`posLevelId\` = \`posLevel\`.\`id\`))) + JOIN \`posType\` ON ((\`profile\`.\`posTypeId\` = \`posType\`.\`id\`))) + LEFT JOIN \`position\` ON ((\`posMaster\`.\`id\` = \`position\`.\`posMasterId\`))) + LEFT JOIN \`posExecutive\` ON ((\`position\`.\`posExecutiveId\` = \`posExecutive\`.\`id\`))) + WHERE + (\`position\`.\`positionIsSelected\` = TRUE)`); + await queryRunner.query(`INSERT INTO \`bma_ehr_organization_demo\`.\`typeorm_metadata\`(\`database\`, \`schema\`, \`table\`, \`type\`, \`name\`, \`value\`) VALUES (DEFAULT, ?, DEFAULT, ?, ?, ?)`, ["bma_ehr_organization_demo","VIEW","view_director","SELECT \n `profile`.`id` AS `Id`,\n `profile`.`prefix` AS `prefix`,\n `profile`.`firstName` AS `firstName`,\n `profile`.`lastName` AS `lastName`,\n `profile`.`citizenId` AS `citizenId`,\n `profile`.`position` AS `position`,\n CONCAT((CASE\n WHEN (`posMaster`.`orgChild1Id` IS NULL) THEN `orgRoot`.`orgRootShortName`\n WHEN (`posMaster`.`orgChild2Id` IS NULL) THEN `orgChild1`.`orgChild1ShortName`\n WHEN (`posMaster`.`orgChild3Id` IS NULL) THEN `orgChild2`.`orgChild2ShortName`\n WHEN (`posMaster`.`orgChild4Id` IS NULL) THEN `orgChild3`.`orgChild3ShortName`\n ELSE `orgChild4`.`orgChild4ShortName`\n END),\n `posMaster`.`posMasterNo`) AS `posNo`,\n `posMaster`.`isDirector` AS `isDirector`,\n `posLevel`.`posLevelName` AS `posLevel`,\n `posType`.`posTypeName` AS `posType`,\n `posExecutive`.`posExecutiveName` AS `posExecutiveName`,\n `orgRoot`.`isDeputy` AS `isDeputy`,\n `orgChild1`.`isOfficer` AS `isOfficer`,\n `posMaster`.`orgRootId` AS `orgRootId`,\n `posMaster`.`orgChild1Id` AS `orgChild1Id`,\n `posMaster`.`orgChild2Id` AS `orgChild2Id`,\n `posMaster`.`orgChild3Id` AS `orgChild3Id`,\n `posMaster`.`orgChild4Id` AS `orgChild4Id`,\n CONCAT(`posMaster`.`id`, `profile`.`id`) AS `key`,\n (\n SELECT `actFullNameId` \n FROM `view_director_acting` AS `acting`\n WHERE `acting`.`Id` = `posMaster`.`current_holderId` \n AND `acting`.`orgRootId` = `posMaster`.`orgRootId` \n AND (\n (`acting`.`orgChild1Id` IS NULL AND `posMaster`.`orgChild1Id` IS NULL) \n OR (`acting`.`orgChild1Id` = `posMaster`.`orgChild1Id`)\n ) \n AND (\n (`acting`.`orgChild2Id` IS NULL AND `posMaster`.`orgChild2Id` IS NULL) \n OR (`acting`.`orgChild2Id` = `posMaster`.`orgChild2Id`)\n ) \n AND (\n (`acting`.`orgChild3Id` IS NULL AND `posMaster`.`orgChild3Id` IS NULL) \n OR (`acting`.`orgChild3Id` = `posMaster`.`orgChild3Id`)\n ) \n AND (\n (`acting`.`orgChild4Id` IS NULL AND `posMaster`.`orgChild4Id` IS NULL) \n OR (`acting`.`orgChild4Id` = `posMaster`.`orgChild4Id`)\n )\n ) AS `actFullNameId`,\n (\n SELECT `actFullName` \n FROM `view_director_acting` AS `acting`\n WHERE `acting`.`Id` = `posMaster`.`current_holderId` \n AND `acting`.`orgRootId` = `posMaster`.`orgRootId` \n AND (\n (`acting`.`orgChild1Id` IS NULL AND `posMaster`.`orgChild1Id` IS NULL) \n OR (`acting`.`orgChild1Id` = `posMaster`.`orgChild1Id`)\n ) \n AND (\n (`acting`.`orgChild2Id` IS NULL AND `posMaster`.`orgChild2Id` IS NULL) \n OR (`acting`.`orgChild2Id` = `posMaster`.`orgChild2Id`)\n ) \n AND (\n (`acting`.`orgChild3Id` IS NULL AND `posMaster`.`orgChild3Id` IS NULL) \n OR (`acting`.`orgChild3Id` = `posMaster`.`orgChild3Id`)\n ) \n AND (\n (`acting`.`orgChild4Id` IS NULL AND `posMaster`.`orgChild4Id` IS NULL) \n OR (`acting`.`orgChild4Id` = `posMaster`.`orgChild4Id`)\n )\n ) AS `actFullName`\n \n FROM\n ((((((((((`posMaster`\n JOIN `profile` ON ((`posMaster`.`current_holderId` = `profile`.`id`)))\n LEFT JOIN `orgRoot` ON ((`posMaster`.`orgRootId` = `orgRoot`.`id`)))\n LEFT JOIN `orgChild1` ON ((`posMaster`.`orgChild1Id` = `orgChild1`.`id`)))\n LEFT JOIN `orgChild2` ON ((`posMaster`.`orgChild2Id` = `orgChild2`.`id`)))\n LEFT JOIN `orgChild3` ON ((`posMaster`.`orgChild3Id` = `orgChild3`.`id`)))\n LEFT JOIN `orgChild4` ON ((`posMaster`.`orgChild4Id` = `orgChild4`.`id`)))\n JOIN `posLevel` ON ((`profile`.`posLevelId` = `posLevel`.`id`)))\n JOIN `posType` ON ((`profile`.`posTypeId` = `posType`.`id`)))\n LEFT JOIN `position` ON ((`posMaster`.`id` = `position`.`posMasterId`)))\n LEFT JOIN `posExecutive` ON ((`position`.`posExecutiveId` = `posExecutive`.`id`)))\n WHERE\n (`position`.`positionIsSelected` = TRUE)"]); + } + +} diff --git a/src/migration/1737715789621-UpdateCommandAddPosition.ts b/src/migration/1737715789621-UpdateCommandAddPosition.ts new file mode 100644 index 00000000..fa39b2ad --- /dev/null +++ b/src/migration/1737715789621-UpdateCommandAddPosition.ts @@ -0,0 +1,18 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateCommandAddPosition1737715789621 implements MigrationInterface { + name = 'UpdateCommandAddPosition1737715789621' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`commandRecive\` ADD \`position\` varchar(255) NULL COMMENT 'ตำแหน่ง'`); + await queryRunner.query(`ALTER TABLE \`commandRecive\` ADD \`posType\` varchar(255) NULL COMMENT 'ประเภท'`); + await queryRunner.query(`ALTER TABLE \`commandRecive\` ADD \`posLevel\` varchar(255) NULL COMMENT 'ระดับ'`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`commandRecive\` DROP COLUMN \`posLevel\``); + await queryRunner.query(`ALTER TABLE \`commandRecive\` DROP COLUMN \`posType\``); + await queryRunner.query(`ALTER TABLE \`commandRecive\` DROP COLUMN \`position\``); + } + +} diff --git a/src/migration/1737737577863-addtableprofileAssistance.ts b/src/migration/1737737577863-addtableprofileAssistance.ts new file mode 100644 index 00000000..5397c0e3 --- /dev/null +++ b/src/migration/1737737577863-addtableprofileAssistance.ts @@ -0,0 +1,32 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class AddtableprofileAssistance1737737577863 implements MigrationInterface { + name = 'AddtableprofileAssistance1737737577863' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`CREATE TABLE \`profileActpositionHistory\` (\`id\` varchar(36) NOT NULL, \`createdAt\` datetime(6) NOT NULL COMMENT 'สร้างข้อมูลเมื่อ' DEFAULT CURRENT_TIMESTAMP(6), \`createdUserId\` varchar(40) NOT NULL COMMENT 'User Id ที่สร้างข้อมูล' DEFAULT '00000000-0000-0000-0000-000000000000', \`lastUpdatedAt\` datetime(6) NOT NULL COMMENT 'แก้ไขข้อมูลล่าสุดเมื่อ' DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), \`lastUpdateUserId\` varchar(40) NOT NULL COMMENT 'User Id ที่แก้ไขข้อมูล' DEFAULT '00000000-0000-0000-0000-000000000000', \`createdFullName\` varchar(200) NOT NULL COMMENT 'ชื่อ User ที่สร้างข้อมูล' DEFAULT 'string', \`lastUpdateFullName\` varchar(200) NOT NULL COMMENT 'ชื่อ User ที่แก้ไขข้อมูลล่าสุด' DEFAULT 'string', \`dateStart\` datetime NULL COMMENT 'วันที่เริ่มต้น', \`dateEnd\` datetime NULL COMMENT 'วันที่สิ้นสุด', \`posNo\` varchar(255) NULL COMMENT 'ตำแหน่งเลขที่', \`position\` varchar(255) NULL COMMENT 'ตำแหน่ง', \`status\` varchar(255) NULL COMMENT 'สถานะ', \`profileActpositionId\` varchar(40) NULL COMMENT 'คีย์นอก(FK)ของตาราง ProfileActposition', PRIMARY KEY (\`id\`)) ENGINE=InnoDB`); + await queryRunner.query(`CREATE TABLE \`profileActposition\` (\`id\` varchar(36) NOT NULL, \`createdAt\` datetime(6) NOT NULL COMMENT 'สร้างข้อมูลเมื่อ' DEFAULT CURRENT_TIMESTAMP(6), \`createdUserId\` varchar(40) NOT NULL COMMENT 'User Id ที่สร้างข้อมูล' DEFAULT '00000000-0000-0000-0000-000000000000', \`lastUpdatedAt\` datetime(6) NOT NULL COMMENT 'แก้ไขข้อมูลล่าสุดเมื่อ' DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), \`lastUpdateUserId\` varchar(40) NOT NULL COMMENT 'User Id ที่แก้ไขข้อมูล' DEFAULT '00000000-0000-0000-0000-000000000000', \`createdFullName\` varchar(200) NOT NULL COMMENT 'ชื่อ User ที่สร้างข้อมูล' DEFAULT 'string', \`lastUpdateFullName\` varchar(200) NOT NULL COMMENT 'ชื่อ User ที่แก้ไขข้อมูลล่าสุด' DEFAULT 'string', \`profileId\` varchar(40) NULL COMMENT 'คีย์นอก(FK)ของตาราง Profile', \`dateStart\` datetime NULL COMMENT 'วันที่เริ่มต้น', \`dateEnd\` datetime NULL COMMENT 'วันที่สิ้นสุด', \`posNo\` varchar(255) NULL COMMENT 'ตำแหน่งเลขที่', \`position\` varchar(255) NULL COMMENT 'ตำแหน่ง', \`status\` varchar(255) NULL COMMENT 'สถานะ', \`profileEmployeeId\` varchar(40) NULL COMMENT 'คีย์นอก(FK)ของตาราง ProfileEmployee', PRIMARY KEY (\`id\`)) ENGINE=InnoDB`); + await queryRunner.query(`CREATE TABLE \`profileAssistanceHistory\` (\`id\` varchar(36) NOT NULL, \`createdAt\` datetime(6) NOT NULL COMMENT 'สร้างข้อมูลเมื่อ' DEFAULT CURRENT_TIMESTAMP(6), \`createdUserId\` varchar(40) NOT NULL COMMENT 'User Id ที่สร้างข้อมูล' DEFAULT '00000000-0000-0000-0000-000000000000', \`lastUpdatedAt\` datetime(6) NOT NULL COMMENT 'แก้ไขข้อมูลล่าสุดเมื่อ' DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), \`lastUpdateUserId\` varchar(40) NOT NULL COMMENT 'User Id ที่แก้ไขข้อมูล' DEFAULT '00000000-0000-0000-0000-000000000000', \`createdFullName\` varchar(200) NOT NULL COMMENT 'ชื่อ User ที่สร้างข้อมูล' DEFAULT 'string', \`lastUpdateFullName\` varchar(200) NOT NULL COMMENT 'ชื่อ User ที่แก้ไขข้อมูลล่าสุด' DEFAULT 'string', \`agency\` varchar(255) NULL COMMENT 'หน่วยงานที่ให้ช่วยราชการ', \`dateStart\` datetime NULL COMMENT 'วันเริ่มช่วยราชการ', \`dateEnd\` datetime NULL COMMENT 'วันสิ้นสุดการช่วยราชการ', \`commandNo\` varchar(255) NULL COMMENT 'เลขที่คำสั่ง', \`document\` varchar(255) NULL COMMENT 'เอกสารอ้างอิง', \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0, \`profileAssistanceId\` varchar(40) NULL COMMENT 'คีย์นอก(FK)ของตาราง ProfileAssistance', PRIMARY KEY (\`id\`)) ENGINE=InnoDB`); + await queryRunner.query(`CREATE TABLE \`profileAssistance\` (\`id\` varchar(36) NOT NULL, \`createdAt\` datetime(6) NOT NULL COMMENT 'สร้างข้อมูลเมื่อ' DEFAULT CURRENT_TIMESTAMP(6), \`createdUserId\` varchar(40) NOT NULL COMMENT 'User Id ที่สร้างข้อมูล' DEFAULT '00000000-0000-0000-0000-000000000000', \`lastUpdatedAt\` datetime(6) NOT NULL COMMENT 'แก้ไขข้อมูลล่าสุดเมื่อ' DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), \`lastUpdateUserId\` varchar(40) NOT NULL COMMENT 'User Id ที่แก้ไขข้อมูล' DEFAULT '00000000-0000-0000-0000-000000000000', \`createdFullName\` varchar(200) NOT NULL COMMENT 'ชื่อ User ที่สร้างข้อมูล' DEFAULT 'string', \`lastUpdateFullName\` varchar(200) NOT NULL COMMENT 'ชื่อ User ที่แก้ไขข้อมูลล่าสุด' DEFAULT 'string', \`profileId\` varchar(40) NULL COMMENT 'คีย์นอก(FK)ของตาราง Profile', \`agency\` varchar(255) NULL COMMENT 'หน่วยงานที่ให้ช่วยราชการ', \`dateStart\` datetime NULL COMMENT 'วันเริ่มช่วยราชการ', \`dateEnd\` datetime NULL COMMENT 'วันสิ้นสุดการช่วยราชการ', \`commandNo\` varchar(255) NULL COMMENT 'เลขที่คำสั่ง', \`document\` varchar(255) NULL COMMENT 'เอกสารอ้างอิง', \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0, \`profileEmployeeId\` varchar(40) NULL COMMENT 'คีย์นอก(FK)ของตาราง ProfileEmployee', PRIMARY KEY (\`id\`)) ENGINE=InnoDB`); + await queryRunner.query(`ALTER TABLE \`profileActpositionHistory\` ADD CONSTRAINT \`FK_3237d7abfbea9831a55541af88e\` FOREIGN KEY (\`profileActpositionId\`) REFERENCES \`profileActposition\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION`); + await queryRunner.query(`ALTER TABLE \`profileActposition\` ADD CONSTRAINT \`FK_23b27027d87eeb4434a0fd180b9\` FOREIGN KEY (\`profileId\`) REFERENCES \`profile\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION`); + await queryRunner.query(`ALTER TABLE \`profileActposition\` ADD CONSTRAINT \`FK_9a1370a44ec70ab52dacbfa59c7\` FOREIGN KEY (\`profileEmployeeId\`) REFERENCES \`profileEmployee\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION`); + await queryRunner.query(`ALTER TABLE \`profileAssistanceHistory\` ADD CONSTRAINT \`FK_800ad6a522e1d5570282421a254\` FOREIGN KEY (\`profileAssistanceId\`) REFERENCES \`profileAssistance\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION`); + await queryRunner.query(`ALTER TABLE \`profileAssistance\` ADD CONSTRAINT \`FK_40921096fc4283edf837ac7dd0d\` FOREIGN KEY (\`profileId\`) REFERENCES \`profile\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION`); + await queryRunner.query(`ALTER TABLE \`profileAssistance\` ADD CONSTRAINT \`FK_5d287abdf47e8fba3e700537ed8\` FOREIGN KEY (\`profileEmployeeId\`) REFERENCES \`profileEmployee\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileAssistance\` DROP FOREIGN KEY \`FK_5d287abdf47e8fba3e700537ed8\``); + await queryRunner.query(`ALTER TABLE \`profileAssistance\` DROP FOREIGN KEY \`FK_40921096fc4283edf837ac7dd0d\``); + await queryRunner.query(`ALTER TABLE \`profileAssistanceHistory\` DROP FOREIGN KEY \`FK_800ad6a522e1d5570282421a254\``); + await queryRunner.query(`ALTER TABLE \`profileActposition\` DROP FOREIGN KEY \`FK_9a1370a44ec70ab52dacbfa59c7\``); + await queryRunner.query(`ALTER TABLE \`profileActposition\` DROP FOREIGN KEY \`FK_23b27027d87eeb4434a0fd180b9\``); + await queryRunner.query(`ALTER TABLE \`profileActpositionHistory\` DROP FOREIGN KEY \`FK_3237d7abfbea9831a55541af88e\``); + await queryRunner.query(`DROP TABLE \`profileAssistance\``); + await queryRunner.query(`DROP TABLE \`profileAssistanceHistory\``); + await queryRunner.query(`DROP TABLE \`profileActposition\``); + await queryRunner.query(`DROP TABLE \`profileActpositionHistory\``); + } + +} diff --git a/src/migration/1737948097408-UpdateprofileActpositionaddstatus.ts b/src/migration/1737948097408-UpdateprofileActpositionaddstatus.ts new file mode 100644 index 00000000..e559ce25 --- /dev/null +++ b/src/migration/1737948097408-UpdateprofileActpositionaddstatus.ts @@ -0,0 +1,20 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateprofileActpositionaddstatus1737948097408 implements MigrationInterface { + name = 'UpdateprofileActpositionaddstatus1737948097408' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileActpositionHistory\` DROP COLUMN \`status\``); + await queryRunner.query(`ALTER TABLE \`profileActpositionHistory\` ADD \`status\` tinyint NOT NULL COMMENT 'สถานะ' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileActposition\` DROP COLUMN \`status\``); + await queryRunner.query(`ALTER TABLE \`profileActposition\` ADD \`status\` tinyint NOT NULL COMMENT 'สถานะ' DEFAULT 0`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileActposition\` DROP COLUMN \`status\``); + await queryRunner.query(`ALTER TABLE \`profileActposition\` ADD \`status\` varchar(255) NULL COMMENT 'สถานะ'`); + await queryRunner.query(`ALTER TABLE \`profileActpositionHistory\` DROP COLUMN \`status\``); + await queryRunner.query(`ALTER TABLE \`profileActpositionHistory\` ADD \`status\` varchar(255) NULL COMMENT 'สถานะ'`); + } + +} diff --git a/src/migration/1737951091780-update_table_profile_and_profileEmp.ts b/src/migration/1737951091780-update_table_profile_and_profileEmp.ts new file mode 100644 index 00000000..3206a0fb --- /dev/null +++ b/src/migration/1737951091780-update_table_profile_and_profileEmp.ts @@ -0,0 +1,44 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateTableProfileAndProfileEmp1737951091780 implements MigrationInterface { + name = 'UpdateTableProfileAndProfileEmp1737951091780' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileEmployee\` ADD \`leaveType\` text NULL COMMENT 'ประเภทพ้นคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` ADD \`leaveCommandId\` varchar(40) NULL COMMENT 'ไอดีคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` ADD \`leaveCommandNo\` varchar(255) NULL COMMENT 'เลขที่คำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` ADD \`leaveRemark\` text NULL COMMENT 'หมายเหตุแนวตั้งคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` ADD \`leaveDate\` datetime NULL COMMENT 'วันที่ลงนามคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` ADD \`leaveType\` text NULL COMMENT 'ประเภทพ้นคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profile\` ADD \`leaveCommandId\` varchar(40) NULL COMMENT 'ไอดีคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profile\` ADD \`leaveCommandNo\` varchar(255) NULL COMMENT 'เลขที่คำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profile\` ADD \`leaveRemark\` text NULL COMMENT 'หมายเหตุแนวตั้งคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profile\` ADD \`leaveDate\` datetime NULL COMMENT 'วันที่ลงนามคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profile\` ADD \`leaveType\` text NULL COMMENT 'ประเภทพ้นคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileHistory\` ADD \`leaveCommandId\` varchar(40) NULL COMMENT 'ไอดีคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileHistory\` ADD \`leaveCommandNo\` varchar(255) NULL COMMENT 'เลขที่คำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileHistory\` ADD \`leaveRemark\` text NULL COMMENT 'หมายเหตุแนวตั้งคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileHistory\` ADD \`leaveDate\` datetime NULL COMMENT 'วันที่ลงนามคำสั่งพ้นจากราชการ'`); + await queryRunner.query(`ALTER TABLE \`profileHistory\` ADD \`leaveType\` text NULL COMMENT 'ประเภทพ้นคำสั่งพ้นจากราชการ'`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileHistory\` DROP COLUMN \`leaveType\``); + await queryRunner.query(`ALTER TABLE \`profileHistory\` DROP COLUMN \`leaveDate\``); + await queryRunner.query(`ALTER TABLE \`profileHistory\` DROP COLUMN \`leaveRemark\``); + await queryRunner.query(`ALTER TABLE \`profileHistory\` DROP COLUMN \`leaveCommandNo\``); + await queryRunner.query(`ALTER TABLE \`profileHistory\` DROP COLUMN \`leaveCommandId\``); + await queryRunner.query(`ALTER TABLE \`profile\` DROP COLUMN \`leaveType\``); + await queryRunner.query(`ALTER TABLE \`profile\` DROP COLUMN \`leaveDate\``); + await queryRunner.query(`ALTER TABLE \`profile\` DROP COLUMN \`leaveRemark\``); + await queryRunner.query(`ALTER TABLE \`profile\` DROP COLUMN \`leaveCommandNo\``); + await queryRunner.query(`ALTER TABLE \`profile\` DROP COLUMN \`leaveCommandId\``); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` DROP COLUMN \`leaveType\``); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` DROP COLUMN \`leaveDate\``); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` DROP COLUMN \`leaveRemark\``); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` DROP COLUMN \`leaveCommandNo\``); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` DROP COLUMN \`leaveCommandId\``); + await queryRunner.query(`ALTER TABLE \`profileEmployee\` DROP COLUMN \`leaveType\``); + } + +} diff --git a/src/migration/1738037460278-UpdateprofileaddisRetirement.ts b/src/migration/1738037460278-UpdateprofileaddisRetirement.ts new file mode 100644 index 00000000..a7b95961 --- /dev/null +++ b/src/migration/1738037460278-UpdateprofileaddisRetirement.ts @@ -0,0 +1,20 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateprofileaddisRetirement1738037460278 implements MigrationInterface { + name = 'UpdateprofileaddisRetirement1738037460278' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profile\` ADD \`isRetirement\` tinyint NOT NULL COMMENT 'เกษียณ' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileHistory\` ADD \`isRetirement\` tinyint NOT NULL COMMENT 'เกษียณ' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profile\` CHANGE \`isLeave\` \`isLeave\` tinyint NOT NULL COMMENT 'พ้นราชการ' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileHistory\` CHANGE \`isLeave\` \`isLeave\` tinyint NOT NULL COMMENT 'พ้นราชการ' DEFAULT 0`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileHistory\` CHANGE \`isLeave\` \`isLeave\` tinyint NOT NULL COMMENT 'เกษียณ' DEFAULT '0'`); + await queryRunner.query(`ALTER TABLE \`profile\` CHANGE \`isLeave\` \`isLeave\` tinyint NOT NULL COMMENT 'เกษียณ' DEFAULT '0'`); + await queryRunner.query(`ALTER TABLE \`profileHistory\` DROP COLUMN \`isRetirement\``); + await queryRunner.query(`ALTER TABLE \`profile\` DROP COLUMN \`isRetirement\``); + } + +} diff --git a/src/migration/1738042376574-UpdateprofileHonoraddtype.ts b/src/migration/1738042376574-UpdateprofileHonoraddtype.ts new file mode 100644 index 00000000..798a0e41 --- /dev/null +++ b/src/migration/1738042376574-UpdateprofileHonoraddtype.ts @@ -0,0 +1,16 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateprofileHonoraddtype1738042376574 implements MigrationInterface { + name = 'UpdateprofileHonoraddtype1738042376574' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileHonorHistory\` ADD \`type\` varchar(200) NULL COMMENT 'ประเภท'`); + await queryRunner.query(`ALTER TABLE \`profileHonor\` ADD \`type\` varchar(200) NULL COMMENT 'ประเภท'`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileHonor\` DROP COLUMN \`type\``); + await queryRunner.query(`ALTER TABLE \`profileHonorHistory\` DROP COLUMN \`type\``); + } + +} diff --git a/src/migration/1738049529701-UpdateprofileHonoraddisUpload.ts b/src/migration/1738049529701-UpdateprofileHonoraddisUpload.ts new file mode 100644 index 00000000..250a423f --- /dev/null +++ b/src/migration/1738049529701-UpdateprofileHonoraddisUpload.ts @@ -0,0 +1,28 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateprofileHonoraddisUpload1738049529701 implements MigrationInterface { + name = 'UpdateprofileHonoraddisUpload1738049529701' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileInsigniaHistory\` ADD \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileInsignia\` ADD \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileHonorHistory\` ADD \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileHonor\` ADD \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileDutyHistory\` ADD \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileDuty\` ADD \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileAbilityHistory\` ADD \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileAbility\` ADD \`isUpload\` tinyint NOT NULL COMMENT 'แนบไฟล์เอกสาร' DEFAULT 0`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileAbility\` DROP COLUMN \`isUpload\``); + await queryRunner.query(`ALTER TABLE \`profileAbilityHistory\` DROP COLUMN \`isUpload\``); + await queryRunner.query(`ALTER TABLE \`profileDuty\` DROP COLUMN \`isUpload\``); + await queryRunner.query(`ALTER TABLE \`profileDutyHistory\` DROP COLUMN \`isUpload\``); + await queryRunner.query(`ALTER TABLE \`profileHonor\` DROP COLUMN \`isUpload\``); + await queryRunner.query(`ALTER TABLE \`profileHonorHistory\` DROP COLUMN \`isUpload\``); + await queryRunner.query(`ALTER TABLE \`profileInsignia\` DROP COLUMN \`isUpload\``); + await queryRunner.query(`ALTER TABLE \`profileInsigniaHistory\` DROP COLUMN \`isUpload\``); + } + +} diff --git a/src/migration/1738139755428-update_table_profileEmp.ts b/src/migration/1738139755428-update_table_profileEmp.ts new file mode 100644 index 00000000..bf6bbed4 --- /dev/null +++ b/src/migration/1738139755428-update_table_profileEmp.ts @@ -0,0 +1,20 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class UpdateTableProfileEmp1738139755428 implements MigrationInterface { + name = 'UpdateTableProfileEmp1738139755428' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileEmployee\` ADD \`isRetirement\` tinyint NOT NULL COMMENT 'เกษียณ' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` ADD \`isRetirement\` tinyint NOT NULL COMMENT 'เกษียณ' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileEmployee\` CHANGE \`isLeave\` \`isLeave\` tinyint NOT NULL COMMENT 'พ้นราชการ' DEFAULT 0`); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` CHANGE \`isLeave\` \`isLeave\` tinyint NOT NULL COMMENT 'พ้นราชการ' DEFAULT 0`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` CHANGE \`isLeave\` \`isLeave\` tinyint NOT NULL COMMENT 'เกษียณ' DEFAULT '0'`); + await queryRunner.query(`ALTER TABLE \`profileEmployee\` CHANGE \`isLeave\` \`isLeave\` tinyint NOT NULL COMMENT 'เกษียณ' DEFAULT '0'`); + await queryRunner.query(`ALTER TABLE \`profileEmployeeHistory\` DROP COLUMN \`isRetirement\``); + await queryRunner.query(`ALTER TABLE \`profileEmployee\` DROP COLUMN \`isRetirement\``); + } + +}