From ef279df4526d482a765ed87d563a95580c11bbb4 Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Fri, 1 May 2026 00:22:16 +0700 Subject: [PATCH] fix handler_org error use temporary table --- src/services/PositionService.ts | 71 +- src/services/rabbitmq.ts | 2666 ++++++++++++++++--------------- 2 files changed, 1378 insertions(+), 1359 deletions(-) diff --git a/src/services/PositionService.ts b/src/services/PositionService.ts index cd3a0aca..f60539fa 100644 --- a/src/services/PositionService.ts +++ b/src/services/PositionService.ts @@ -433,40 +433,53 @@ export async function BatchUpdatePosMasters( ): Promise { if (updates.length === 0) return; - const CHUNK_SIZE = 1000; + const CHUNK_SIZE = 5000; const chunks = chunkArray(updates, CHUNK_SIZE); for (const chunk of chunks) { - // Build single bulk UPDATE query using CASE WHEN - const caseStatements: string[] = []; - const params: any[] = []; + // Create a temporary table for this batch + const tempTableName = `temp_posmaster_update_${Date.now()}_${Math.random().toString(36).substring(7)}`; - for (const update of chunk) { - caseStatements.push(`WHEN ? THEN ?`); - params.push(update.id, update.current_holderId); + try { + // Create temporary table + await manager.query(` + CREATE TEMPORARY TABLE ${tempTableName} ( + id CHAR(36) PRIMARY KEY, + current_holderId CHAR(36) NULL, + lastUpdateUserId CHAR(36) NOT NULL, + lastUpdateFullName VARCHAR(255) NOT NULL, + lastUpdatedAt DATETIME NOT NULL + ) ENGINE=InnoDB + `); + + // Build insert query with proper parameter count + const insertParams: any[] = []; + const valuePlaceholders: string[] = []; + for (const u of chunk) { + valuePlaceholders.push('(?, ?, ?, ?, ?)'); + insertParams.push(u.id, u.current_holderId, u.lastUpdateUserId, u.lastUpdateFullName, u.lastUpdatedAt); + } + + // Bulk insert into temporary table + await manager.query(` + INSERT INTO ${tempTableName} (id, current_holderId, lastUpdateUserId, lastUpdateFullName, lastUpdatedAt) + VALUES ${valuePlaceholders.join(',')} + `, insertParams); + + // Update using JOIN with temporary table (very fast - single query per chunk) + await manager.query(` + UPDATE posMaster p + INNER JOIN ${tempTableName} t ON p.id = t.id + SET p.current_holderId = t.current_holderId, + p.next_holderId = NULL, + p.lastUpdateUserId = t.lastUpdateUserId, + p.lastUpdateFullName = t.lastUpdateFullName, + p.lastUpdatedAt = t.lastUpdatedAt + `); + } finally { + // Drop temporary table + await manager.query(`DROP TEMPORARY TABLE IF EXISTS ${tempTableName}`).catch(() => {}); } - - // Build IN clause placeholders - const idPlaceholders = chunk.map(() => '?').join(','); - const ids = chunk.map((u: any) => u.id); - - // Add common params at the end - params.push( - chunk[0].lastUpdateUserId, - chunk[0].lastUpdateFullName, - chunk[0].lastUpdatedAt, - ...ids - ); - - await manager.query(` - UPDATE posMaster - SET current_holderId = CASE id ${caseStatements.join(' ')} END, - next_holderId = NULL, - lastUpdateUserId = ?, - lastUpdateFullName = ?, - lastUpdatedAt = ? - WHERE id IN (${idPlaceholders}) - `, params); } } diff --git a/src/services/rabbitmq.ts b/src/services/rabbitmq.ts index 420b21e3..2f560531 100644 --- a/src/services/rabbitmq.ts +++ b/src/services/rabbitmq.ts @@ -24,7 +24,12 @@ import { In, Not } from "typeorm"; import { PosMasterAct } from "../entities/PosMasterAct"; import { PermissionOrg } from "../entities/PermissionOrg"; import { sendWebSocket } from "./webSocket"; -import { CreatePosMasterHistoryOfficer, BatchUpdatePosMasters, BatchCreatePosMasterHistoryOfficer, BatchHistoryOperation } from "./PositionService"; +import { + CreatePosMasterHistoryOfficer, + BatchUpdatePosMasters, + BatchCreatePosMasterHistoryOfficer, + BatchHistoryOperation, +} from "./PositionService"; import { PayloadSendNoti } from "../interfaces/utils"; import { PermissionProfile } from "../entities/PermissionProfile"; @@ -405,7 +410,7 @@ async function handler_command_noti(msg: amqp.ConsumeMessage): Promise try { let profilesNotiRequest: Promise | undefined; - if (!(["C-PM-10"].includes(command.commandType.code))) { + if (!["C-PM-10"].includes(command.commandType.code)) { profilesNotiRequest = new CallAPI() .PostData( { headers: { authorization: token } }, @@ -441,14 +446,14 @@ async function handler_command_noti(msg: amqp.ConsumeMessage): Promise let profilesSend = command && command.commandSends.length > 0 ? command.commandSends - .filter((x: any) => x.profileId != null) - .map((x: any) => ({ - receiverUserId: x.profileId, - notiLink: "", - isSendMail: x.commandSendCCs.map((x: any) => x.name == "EMAIL").length > 0, - isSendInbox: x.commandSendCCs.map((x: any) => x.name == "INBOX").length > 0, - isSendNotification: true, - })) + .filter((x: any) => x.profileId != null) + .map((x: any) => ({ + receiverUserId: x.profileId, + notiLink: "", + isSendMail: x.commandSendCCs.map((x: any) => x.name == "EMAIL").length > 0, + isSendInbox: x.commandSendCCs.map((x: any) => x.name == "INBOX").length > 0, + isSendNotification: true, + })) : []; const payloadStr = await PayloadSendNoti(command.id); const profilesSendRequest = new CallAPI() @@ -482,8 +487,7 @@ async function handler_command_noti(msg: amqp.ConsumeMessage): Promise /*เฉพาะคำสั่ง C-PM-10 ให้ตัด profilesNotiRequest ที่ส่ง noti ครั้งแรกออก*/ if (["C-PM-10"].includes(command.commandType.code)) { await Promise.all([profilesSendRequest]); - } - else { + } else { await Promise.all([profilesNotiRequest!, profilesSendRequest]); } @@ -497,7 +501,7 @@ async function handler_command_noti(msg: amqp.ConsumeMessage): Promise async function handler_org(msg: amqp.ConsumeMessage): Promise { //----> condition before process consume - console.time('[AMQ] handler_org_total'); + console.time("[AMQ] handler_org_total"); const startTime = Date.now(); console.log(`[AMQ] handler_org START at ${new Date(startTime).toISOString()}`); @@ -525,574 +529,580 @@ async function handler_org(msg: amqp.ConsumeMessage): Promise { console.log(`[AMQ] Received message - revisionId: ${id}, status: ${status}`); if (user) { - sendWebSocket( - "send-publish-org", - { - success: true, - message: `ระบบกำลังทำการเผยแพร่โครงสร้างหน่วยงาน`, - }, - { userId: user?.sub }, - ).catch(console.error); - } + sendWebSocket( + "send-publish-org", + { + success: true, + message: `ระบบกำลังทำการเผยแพร่โครงสร้างหน่วยงาน`, + }, + { userId: user?.sub }, + ).catch(console.error); + } - console.time('[AMQ] query_revisions'); - const orgRevisionPublish = await repoOrgRevision - .createQueryBuilder("orgRevision") - .where("orgRevision.orgRevisionIsDraft = false") - .andWhere("orgRevision.orgRevisionIsCurrent = true") - .getOne(); + console.time("[AMQ] query_revisions"); + const orgRevisionPublish = await repoOrgRevision + .createQueryBuilder("orgRevision") + .where("orgRevision.orgRevisionIsDraft = false") + .andWhere("orgRevision.orgRevisionIsCurrent = true") + .getOne(); - const orgRevisionDraft = await repoOrgRevision - .createQueryBuilder("orgRevision") - .where("orgRevision.orgRevisionIsDraft = true") - .andWhere("orgRevision.orgRevisionIsCurrent = false") - .getOne(); - console.timeEnd('[AMQ] query_revisions'); - console.log(`[AMQ] orgRevisionPublish found: ${orgRevisionPublish ? orgRevisionPublish.id : 'null'}`); - console.log(`[AMQ] orgRevisionDraft found: ${orgRevisionDraft ? orgRevisionDraft.id : 'null'}`); + const orgRevisionDraft = await repoOrgRevision + .createQueryBuilder("orgRevision") + .where("orgRevision.orgRevisionIsDraft = true") + .andWhere("orgRevision.orgRevisionIsCurrent = false") + .getOne(); + console.timeEnd("[AMQ] query_revisions"); + console.log( + `[AMQ] orgRevisionPublish found: ${orgRevisionPublish ? orgRevisionPublish.id : "null"}`, + ); + console.log( + `[AMQ] orgRevisionDraft found: ${orgRevisionDraft ? orgRevisionDraft.id : "null"}`, + ); - // Validate: ต้องมี orgRevisionPublish เสมอสำหรับการเผยแพร่ - if (!orgRevisionPublish) { - console.error('[AMQ] Cannot publish: No current org revision found (isDraft=false, isCurrent=true)'); - if (user) { - sendWebSocket( - "send-publish-org", - { - success: false, - message: `ไม่พบข้อมูลโครงสร้างหน่วยงานปัจจุบัน ไม่สามารถเผยแพร่ได้`, - }, - { userId: user?.sub }, - ).catch(console.error); - } - return false; - } + // Validate: ต้องมี orgRevisionPublish เสมอสำหรับการเผยแพร่ + if (!orgRevisionPublish) { + console.error( + "[AMQ] Cannot publish: No current org revision found (isDraft=false, isCurrent=true)", + ); + if (user) { + sendWebSocket( + "send-publish-org", + { + success: false, + message: `ไม่พบข้อมูลโครงสร้างหน่วยงานปัจจุบัน ไม่สามารถเผยแพร่ได้`, + }, + { userId: user?.sub }, + ).catch(console.error); + } + return false; + } - // Validate: ต้องมี orgRevisionDraft ที่จะเผยแพร่ - if (!orgRevisionDraft) { - console.error('[AMQ] Cannot publish: No draft org revision found (isDraft=true, isCurrent=false)'); - if (user) { - sendWebSocket( - "send-publish-org", - { - success: false, - message: `ไม่พบข้อมูลโครงสร้างหน่วยงานแบบร่าง ไม่สามารถเผยแพร่ได้`, - }, - { userId: user?.sub }, - ).catch(console.error); - } - return false; - } + // Validate: ต้องมี orgRevisionDraft ที่จะเผยแพร่ + if (!orgRevisionDraft) { + console.error( + "[AMQ] Cannot publish: No draft org revision found (isDraft=true, isCurrent=false)", + ); + if (user) { + sendWebSocket( + "send-publish-org", + { + success: false, + message: `ไม่พบข้อมูลโครงสร้างหน่วยงานแบบร่าง ไม่สามารถเผยแพร่ได้`, + }, + { userId: user?.sub }, + ).catch(console.error); + } + return false; + } - // NOTE: ย้ายการอัปเดตสถานะไปไว้หลังจากทำงานเสร็จทั้งหมด - // เพื่อป้องกันกรณี timeout/retry ทำให้สถานะเพี้ยน (ทุก row เป็น false,false) + // NOTE: ย้ายการอัปเดตสถานะไปไว้หลังจากทำงานเสร็จทั้งหมด + // เพื่อป้องกันกรณี timeout/retry ทำให้สถานะเพี้ยน (ทุก row เป็น false,false) - console.time('[AMQ] query_posMaster'); - const POS_MASTER_PAGE_SIZE = 2000; - let totalPosMastersProcessed = 0; - let hasMoreRecords = true; - let skip = 0; - const posMaster: PosMaster[] = []; + console.time("[AMQ] query_posMaster"); + const POS_MASTER_PAGE_SIZE = 2000; + let totalPosMastersProcessed = 0; + let hasMoreRecords = true; + let skip = 0; + const posMaster: PosMaster[] = []; - while (hasMoreRecords) { - const posMasterPage = await repoPosmaster.find({ - where: { orgRevisionId: id }, - relations: [ - "orgRoot", - "orgChild4", - "orgChild3", - "orgChild2", - "orgChild1", - "positions", - "positions.posLevel", - "positions.posType", - "positions.posExecutive", - ], - order: { id: 'ASC' }, - skip: skip, - take: POS_MASTER_PAGE_SIZE, - }); + while (hasMoreRecords) { + const posMasterPage = await repoPosmaster.find({ + where: { orgRevisionId: id }, + relations: [ + "orgRoot", + "orgChild4", + "orgChild3", + "orgChild2", + "orgChild1", + "positions", + "positions.posLevel", + "positions.posType", + "positions.posExecutive", + ], + order: { id: "ASC" }, + skip: skip, + take: POS_MASTER_PAGE_SIZE, + }); - posMaster.push(...posMasterPage); - totalPosMastersProcessed += posMasterPage.length; - hasMoreRecords = posMasterPage.length === POS_MASTER_PAGE_SIZE; - skip += POS_MASTER_PAGE_SIZE; + posMaster.push(...posMasterPage); + totalPosMastersProcessed += posMasterPage.length; + hasMoreRecords = posMasterPage.length === POS_MASTER_PAGE_SIZE; + skip += POS_MASTER_PAGE_SIZE; - console.log(`[AMQ] Loaded posMaster page: ${totalPosMastersProcessed} records`); - } - console.timeEnd('[AMQ] query_posMaster'); - console.log(`[AMQ] posMaster count: ${posMaster.length}`); + console.log(`[AMQ] Loaded posMaster page: ${totalPosMastersProcessed} records`); + } + console.timeEnd("[AMQ] query_posMaster"); + console.log(`[AMQ] posMaster count: ${posMaster.length}`); - console.time('[AMQ] query_old_data'); - const oldPosMasters = await repoPosmaster.find({ - where: { - orgRevisionId: orgRevisionPublish.id, - }, - select: ['id', 'current_holderId', 'ancestorDNA'] - }); - - // Task #2160 ดึง posMasterAssign ของ revision เดิม - const oldposMasterAssigns = await posMasterAssignRepository.find({ - relations: ["posMaster"], - where: { - posMaster: { + console.time("[AMQ] query_old_data"); + const oldPosMasters = await repoPosmaster.find({ + where: { orgRevisionId: orgRevisionPublish.id, }, - }, - }); - console.timeEnd('[AMQ] query_old_data'); - console.log(`[AMQ] oldPosMasters count: ${oldPosMasters.length}`); - console.log(`[AMQ] oldposMasterAssigns count: ${oldposMasterAssigns.length}`); - - console.time('[AMQ] build_assignMap'); - // สร้าง assignMap เอาไว้เก็บ posMasterAssign.ancestorDNA ของ revision เดิม - const assignMap = new Map(); - for (const posmasterAssign of oldposMasterAssigns) { - const dna = posmasterAssign.posMaster.ancestorDNA; - if (!assignMap.has(dna)) { - assignMap.set(dna, []); - } - assignMap.get(dna)!.push({ - id: posmasterAssign.id, - posMasterId: posmasterAssign.posMasterId, - assignId: posmasterAssign.assignId + select: ["id", "current_holderId", "ancestorDNA"], }); - } - console.timeEnd('[AMQ] build_assignMap'); - console.time('[AMQ] query_oldposMasterAct'); - // ดึง posMasterAct ของ revision เดิม xxx - const oldposMasterAct = await posMasterActRepository.find({ - relations: ["posMaster", "posMasterChild"], - where: { - posMaster: { - orgRevisionId: orgRevisionPublish.id, + // Task #2160 ดึง posMasterAssign ของ revision เดิม + const oldposMasterAssigns = await posMasterAssignRepository.find({ + relations: ["posMaster"], + where: { + posMaster: { + orgRevisionId: orgRevisionPublish.id, + }, }, - }, - }); - console.timeEnd('[AMQ] query_oldposMasterAct'); - console.log(`[AMQ] oldposMasterAct count: ${oldposMasterAct.length}`); - - type ActKey = string; // `${parentDNA}|${childDNA}` - - console.time('[AMQ] build_maps'); - const posMasterActMap = new Map(); - for (const act of oldposMasterAct) { - const parentDNA = act.posMaster?.ancestorDNA?.trim() ?? ''; - const childDNA = act.posMasterChild?.ancestorDNA?.trim() ?? ''; - const key = `${parentDNA}|${childDNA}`; - - if (!posMasterActMap.has(key)) { - posMasterActMap.set(key, []); - } - posMasterActMap.get(key)!.push(act); - } - - const posMasterIdMap = new Map(); - for (const pm of posMaster) { - posMasterIdMap.set(pm.ancestorDNA?.trim() ?? '', pm.id); - } - - const oldPosMasterMap = new Map(); - for (const oldPm of oldPosMasters) { - const dna = oldPm.ancestorDNA?.trim(); - if (dna) { - oldPosMasterMap.set(dna, oldPm); - } - } - console.timeEnd('[AMQ] build_maps'); - - const _null: any = null; - - // ===== BATCH PROCESSING: เตรียมข้อมูลก่อน loop ===== - console.time('[AMQ] prepare_batch_data'); - // 1. รวบรวม profileIds ทั้งหมดที่ต้องอัพเดท - const profileIds = posMaster - .filter(item => item.next_holderId != null) - .map(item => item.next_holderId!) - .filter(id => id != null && id !== ""); - - // 2. Batch load profiles ทั้งหมดในครั้งเดียว (แก้ปัญหา N+1 Query) - const profilesMap = new Map(); - if (profileIds.length > 0) { - const profiles = await repoProfile.findBy({ - id: In(profileIds) }); - profiles.forEach(p => profilesMap.set(p.id, p)); - } - console.log(`[AMQ] profiles to update: ${profilesMap.size}`); + console.timeEnd("[AMQ] query_old_data"); + console.log(`[AMQ] oldPosMasters count: ${oldPosMasters.length}`); + console.log(`[AMQ] oldposMasterAssigns count: ${oldposMasterAssigns.length}`); - // 3. เตรียม arrays สำหรับ batch operations - const profilesToSave: Profile[] = []; - const posMasterAssignsToSave: PosMasterAssign[] = []; - const historyCreateIds: string[] = []; - const posMasterUpdates: { id: string; current_holderId: string | null | undefined }[] = []; + console.time("[AMQ] build_assignMap"); + // สร้าง assignMap เอาไว้เก็บ posMasterAssign.ancestorDNA ของ revision เดิม + const assignMap = new Map(); + for (const posmasterAssign of oldposMasterAssigns) { + const dna = posmasterAssign.posMaster.ancestorDNA; + if (!assignMap.has(dna)) { + assignMap.set(dna, []); + } + assignMap.get(dna)!.push({ + id: posmasterAssign.id, + posMasterId: posmasterAssign.posMasterId, + assignId: posmasterAssign.assignId, + }); + } + console.timeEnd("[AMQ] build_assignMap"); - // ===== LOOP: เก็บข้อมูลทั้งหมด ===== - for (const item of posMaster) { - const dna = item.ancestorDNA?.trim(); - const oldPm = dna ? oldPosMasterMap.get(dna) : null; + console.time("[AMQ] query_oldposMasterAct"); + // ดึง posMasterAct ของ revision เดิม xxx + const oldposMasterAct = await posMasterActRepository.find({ + relations: ["posMaster", "posMasterChild"], + where: { + posMaster: { + orgRevisionId: orgRevisionPublish.id, + }, + }, + }); + console.timeEnd("[AMQ] query_oldposMasterAct"); + console.log(`[AMQ] oldposMasterAct count: ${oldposMasterAct.length}`); - // Task #2160 Clone posMasterAssign - const assigns = assignMap.get(item.ancestorDNA); - if (assigns && assigns.length > 0) { - const newAssigns = assigns.map(({ id, ...fields }) => - posMasterAssignRepository.create({ + type ActKey = string; // `${parentDNA}|${childDNA}` + + console.time("[AMQ] build_maps"); + const posMasterActMap = new Map(); + for (const act of oldposMasterAct) { + const parentDNA = act.posMaster?.ancestorDNA?.trim() ?? ""; + const childDNA = act.posMasterChild?.ancestorDNA?.trim() ?? ""; + const key = `${parentDNA}|${childDNA}`; + + if (!posMasterActMap.has(key)) { + posMasterActMap.set(key, []); + } + posMasterActMap.get(key)!.push(act); + } + + const posMasterIdMap = new Map(); + for (const pm of posMaster) { + posMasterIdMap.set(pm.ancestorDNA?.trim() ?? "", pm.id); + } + + const oldPosMasterMap = new Map(); + for (const oldPm of oldPosMasters) { + const dna = oldPm.ancestorDNA?.trim(); + if (dna) { + oldPosMasterMap.set(dna, oldPm); + } + } + console.timeEnd("[AMQ] build_maps"); + + const _null: any = null; + + // ===== BATCH PROCESSING: เตรียมข้อมูลก่อน loop ===== + console.time("[AMQ] prepare_batch_data"); + // 1. รวบรวม profileIds ทั้งหมดที่ต้องอัพเดท + const profileIds = posMaster + .filter((item) => item.next_holderId != null) + .map((item) => item.next_holderId!) + .filter((id) => id != null && id !== ""); + + // 2. Batch load profiles ทั้งหมดในครั้งเดียว (แก้ปัญหา N+1 Query) + const profilesMap = new Map(); + if (profileIds.length > 0) { + const profiles = await repoProfile.findBy({ + id: In(profileIds), + }); + profiles.forEach((p) => profilesMap.set(p.id, p)); + } + console.log(`[AMQ] profiles to update: ${profilesMap.size}`); + + // 3. เตรียม arrays สำหรับ batch operations + const profilesToSave: Profile[] = []; + const posMasterAssignsToSave: PosMasterAssign[] = []; + const historyCreateIds: string[] = []; + const posMasterUpdates: { id: string; current_holderId: string | null | undefined }[] = []; + + // ===== LOOP: เก็บข้อมูลทั้งหมด ===== + for (const item of posMaster) { + const dna = item.ancestorDNA?.trim(); + const oldPm = dna ? oldPosMasterMap.get(dna) : null; + + // Task #2160 Clone posMasterAssign + const assigns = assignMap.get(item.ancestorDNA); + if (assigns && assigns.length > 0) { + const newAssigns = assigns.map(({ id, ...fields }) => + posMasterAssignRepository.create({ + ...fields, + posMasterId: item.id, + createdAt: lastUpdatedAt, + createdFullName: lastUpdateFullName, + createdUserId: lastUpdateUserId, + lastUpdatedAt: lastUpdatedAt, + lastUpdateFullName: lastUpdateFullName, + lastUpdateUserId: lastUpdateUserId, + }), + ); + posMasterAssignsToSave.push(...newAssigns); + } + + // เตรียมข้อมูลสำหรับ update profile + if (item.next_holderId != null && item.next_holderId !== "") { + const profile = profilesMap.get(item.next_holderId); + if (profile) { + profile.posMasterNo = getPosMasterNo(item) ?? _null; + profile.org = getOrgFullName(item) ?? _null; + + // ถ้าไม่ใช่ตำแหน่งนั่งทับ (isSit = false) ถึงจะอัพเดทตำแหน่งในทะเบียนประวัติ + if (!item.isSit && item.positions.length > 0) { + let position = item.positions.find((x) => x.positionIsSelected == true); + if (position == null) { + position = item.positions.find((x) => x.posLevelId == profile?.posLevelId); + if (position == null) { + const sorted = [...item.positions].sort((a, b) => a.orderNo - b.orderNo); + position = sorted[0]; + } + } + + profile.posLevelId = position?.posLevelId ?? _null; + profile.posTypeId = position?.posTypeId ?? _null; + profile.position = position?.positionName ?? _null; + profile.positionField = position?.positionField ?? _null; + profile.posExecutive = position?.posExecutive?.posExecutiveName ?? _null; + profile.positionArea = position?.positionArea ?? _null; + profile.positionExecutiveField = position?.positionExecutiveField ?? _null; + } + + profilesToSave.push(profile); + } + } + + // เก็บข้อมูลสำหรับ update posMaster + posMasterUpdates.push({ + id: item.id, + current_holderId: item.next_holderId, + }); + + // เก็บ IDs ที่ต้องสร้าง history + const oldHolderId = oldPm ? oldPm.current_holderId : null; + const newHolderId = item?.next_holderId; + const isHolderChanged = oldHolderId !== newHolderId; + + if (isHolderChanged) { + historyCreateIds.push(item.id); + } + } + console.timeEnd("[AMQ] prepare_batch_data"); + console.log( + `[AMQ] Prepared - posMasterAssignsToSave: ${posMasterAssignsToSave.length}, profilesToSave: ${profilesToSave.length}, posMasterUpdates: ${posMasterUpdates.length}, historyCreateIds: ${historyCreateIds.length}`, + ); + + // ===== BATCH EXECUTION: save ทีละ batch ===== + + // 4. Batch save posMasterAssign (chunk 500) + console.time("[AMQ] batch_save_posMasterAssign"); + if (posMasterAssignsToSave.length > 0) { + const chunks = chunkArray(posMasterAssignsToSave, 500); + for (const chunk of chunks) { + await posMasterAssignRepository.save(chunk); + } + } + console.timeEnd("[AMQ] batch_save_posMasterAssign"); + + // 5. Batch save profiles (chunk 200) + console.time("[AMQ] batch_save_profiles"); + if (profilesToSave.length > 0) { + const chunks = chunkArray(profilesToSave, 200); + for (const chunk of chunks) { + await repoProfile.save(chunk); + } + } + console.timeEnd("[AMQ] batch_save_profiles"); + + // 6. Batch update posMasters + console.time("[AMQ] batch_update_posMasters"); + + const posMasterUpdatesForBatch = posMasterUpdates.map((u: any) => ({ + id: u.id, + current_holderId: u.current_holderId ?? null, + lastUpdateUserId, + lastUpdateFullName, + lastUpdatedAt, + })); + + await BatchUpdatePosMasters(AppDataSource.manager, posMasterUpdatesForBatch); + + console.timeEnd("[AMQ] batch_update_posMasters"); + + // 7. Batch create history + console.time("[AMQ] batch_create_history"); + + const historyOperations: BatchHistoryOperation[] = []; + for (const id of historyCreateIds) { + const pm = posMaster.find((p) => p.id === id); + if (pm) { + historyOperations.push({ + posMasterId: id, + posMasterData: pm, + orgRevisionId: pm.orgRevisionId, + lastUpdateUserId, + lastUpdateFullName, + }); + } + } + + await BatchCreatePosMasterHistoryOfficer(AppDataSource.manager, historyOperations); + + console.timeEnd("[AMQ] batch_create_history"); + + // Clone oldposMasterAct + console.time("[AMQ] clone_oldposMasterAct"); + for (const act of oldposMasterAct) { + const parentDNA = act.posMaster?.ancestorDNA?.trim()?.toLowerCase() ?? ""; + const childDNA = act.posMasterChild?.ancestorDNA?.trim()?.toLowerCase() ?? ""; + + const newParentId = posMasterIdMap.get(parentDNA); + const newChildId = posMasterIdMap.get(childDNA); + + if (!newParentId || !newChildId) continue; + + const { id, posMaster, posMasterChild, ...fields } = act; + + const newAct = { + ...fields, + posMasterId: newParentId, + posMasterChildId: newChildId, + createdAt: new Date(), + createdFullName: user ? user.name : "system", + createdUserId: user ? user.sub : "system", + lastUpdatedAt: new Date(), + lastUpdateFullName: user ? user.name : "system", + lastUpdateUserId: user ? user.sub : "system", + }; + + await posMasterActRepository.save(newAct); + } + console.timeEnd("[AMQ] clone_oldposMasterAct"); + + if (orgRevisionPublish != null && orgRevisionDraft != null) { + console.time("[AMQ] clone_org_structure"); + //new main revision + const before = null; + + //ทุก orgRoot และ orgChild ข้างล่างนี้จะเป็นตัวเก่าที่ไม่ได้เป็น current revision + //cone tree + console.time("[AMQ] query_old_org_structure"); + //หา dna tree + const orgRoot = await orgRootRepository.find({ + where: { orgRevisionId: orgRevisionPublish.id }, + }); + + const orgChild1 = await child1Repository.find({ + where: { orgRevisionId: orgRevisionPublish.id }, + }); + + const orgChild2 = await child2Repository.find({ + where: { orgRevisionId: orgRevisionPublish.id }, + }); + + const orgChild3 = await child3Repository.find({ + where: { orgRevisionId: orgRevisionPublish.id }, + }); + + const orgChild4 = await child4Repository.find({ + where: { orgRevisionId: orgRevisionPublish.id }, + }); + console.timeEnd("[AMQ] query_old_org_structure"); + console.log( + `[AMQ] Old structure - orgRoot: ${orgRoot.length}, orgChild1: ${orgChild1.length}, orgChild2: ${orgChild2.length}, orgChild3: ${orgChild3.length}, orgChild4: ${orgChild4.length}`, + ); + + // Task #2172 ดึง orgRoot ของ revision ใหม่ + const newRoots = await orgRootRepository.find({ + where: { orgRevisionId: orgRevisionDraft.id }, + }); + // สร้าง newRootMap เอาไว้เก็บ orgRoot.ancestorDNA ของ revision ใหม่ + const newRootMap = new Map(newRoots.map((r) => [r.ancestorDNA, r.id])); + + console.time("[AMQ] clone_permissionProfiles"); + // ดึง permissionProfiles ของ revision เดิม + const oldPermissionProfiles = await permissionProfilesRepository.find({ + relations: ["orgRootTree"], + where: { + orgRootTree: { + orgRevisionId: orgRevisionPublish.id, + }, + }, + }); + const inserts: any[] = []; + for (const permiss of oldPermissionProfiles) { + // หา orgRootId ใหม่จาก newRootMap + const newRootId = newRootMap.get(permiss.orgRootTree.ancestorDNA); + if (!newRootId) continue; + // ตัด id กับ orgRootTree ออกแล้วสร้าง object ใหม่ + const { id, orgRootTree, ...fields } = permiss; + // เตรียมข้อมูลสำหรับ insert + inserts.push({ ...fields, - posMasterId: item.id, + orgRootId: newRootId, createdAt: lastUpdatedAt, createdFullName: lastUpdateFullName, createdUserId: lastUpdateUserId, lastUpdatedAt: lastUpdatedAt, lastUpdateFullName: lastUpdateFullName, lastUpdateUserId: lastUpdateUserId, - }) + }); + } + // ทำการ insert ข้อมูลใหม่ครั้งเดียว + if (inserts.length > 0) { + await permissionProfilesRepository.insert(inserts); + } + console.timeEnd("[AMQ] clone_permissionProfiles"); + + //หา dna posmaster ถ้าไม่มีให้เอาตัวเองเป็น dna + console.time("[AMQ] query_employeePosMaster"); + const orgemployeePosMaster = await repoEmployeePosmaster.find({ + where: { orgRevisionId: orgRevisionPublish.id }, + relations: ["positions"], + }); + console.timeEnd("[AMQ] query_employeePosMaster"); + console.log(`[AMQ] orgemployeePosMaster count: ${orgemployeePosMaster.length}`); + + let _orgemployeePosMaster: EmployeePosMaster[]; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // _orgemployeePosMaster = orgemployeePosMaster.map((x) => ({ + // ...x, + // ancestorDNA: + // x.ancestorDNA == null || x.ancestorDNA == "00000000-0000-0000-0000-000000000000" + // ? x.id + // : x.ancestorDNA, + // })); + // await repoEmployeePosmaster.save(_orgemployeePosMaster); + const validProfileIds = new Set( + (await repoProfileEmployee.find({ select: ["id"] })).map((p) => p.id), ); - posMasterAssignsToSave.push(...newAssigns); - } - // เตรียมข้อมูลสำหรับ update profile - if (item.next_holderId != null && item.next_holderId !== "") { - const profile = profilesMap.get(item.next_holderId); - if (profile) { - profile.posMasterNo = getPosMasterNo(item) ?? _null; - profile.org = getOrgFullName(item) ?? _null; + _orgemployeePosMaster = orgemployeePosMaster.map((x) => ({ + ...x, + current_holderId: + x.current_holderId && validProfileIds.has(x.current_holderId) + ? x.current_holderId + : null, + ancestorDNA: + !x.ancestorDNA || x.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ? x.id + : x.ancestorDNA, + })); - // ถ้าไม่ใช่ตำแหน่งนั่งทับ (isSit = false) ถึงจะอัพเดทตำแหน่งในทะเบียนประวัติ - if (!item.isSit && item.positions.length > 0) { - let position = item.positions.find((x) => x.positionIsSelected == true); - if (position == null) { - position = item.positions.find((x) => x.posLevelId == profile?.posLevelId); - if (position == null) { - const sorted = [...item.positions].sort((a, b) => a.orderNo - b.orderNo); - position = sorted[0]; - } + console.time("[AMQ] insert_employeePosMaster"); + await repoEmployeePosmaster + .createQueryBuilder() + .insert() + .into(EmployeePosMaster) + .values(_orgemployeePosMaster) + .orUpdate({ + conflict_target: ["id"], + overwrite: ["ancestorDNA"], + }) + .execute(); + console.timeEnd("[AMQ] insert_employeePosMaster"); + + // } + //หา dna posmaster ถ้าไม่มีให้เอาตัวเองเป็น dna + console.time("[AMQ] query_employeeTempPosMaster"); + const orgemployeeTempPosMaster = await repoEmployeeTempPosmaster.find({ + where: { orgRevisionId: orgRevisionPublish.id }, + relations: ["positions"], + }); + console.timeEnd("[AMQ] query_employeeTempPosMaster"); + console.log(`[AMQ] orgemployeeTempPosMaster count: ${orgemployeeTempPosMaster.length}`); + + let _orgemployeeTempPosMaster: EmployeeTempPosMaster[]; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + _orgemployeeTempPosMaster = orgemployeeTempPosMaster.map((x) => ({ + ...x, + ancestorDNA: + x.ancestorDNA == null || x.ancestorDNA == "00000000-0000-0000-0000-000000000000" + ? x.id + : x.ancestorDNA, + })); + // await repoEmployeeTempPosmaster.save(_orgemployeeTempPosMaster); + await repoEmployeeTempPosmaster + .createQueryBuilder() + .insert() + .into(EmployeeTempPosMaster) + .values(_orgemployeeTempPosMaster) + .orUpdate({ + conflict_target: ["id"], + overwrite: ["ancestorDNA"], + }) + .execute(); + // } + + //create org - forEach orgRoot (WARNING: async forEach without await) + console.time("[AMQ] forEach_orgRoot"); + console.log(`[AMQ] Starting forEach orgRoot loop (${orgRoot.length} items)`); + let processedOrgRoot = 0; + orgRoot.forEach(async (x: any) => { + const itemStartTime = Date.now(); + var dataId = x.id; + + const orgRootCurrent = await orgRootRepository.find({ + where: { orgRevisionId: orgRevisionDraft.id }, + }); + + const matchedOrgRoot = orgRootCurrent.find((i: OrgRoot) => { + if ( + x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง + x.ancestorDNA === null || + x.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ) { + return ( + i.ancestorDNA === null || i.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ); } + return i.ancestorDNA === x.ancestorDNA; + }); - profile.posLevelId = position?.posLevelId ?? _null; - profile.posTypeId = position?.posTypeId ?? _null; - profile.position = position?.positionName ?? _null; - profile.positionField = position?.positionField ?? _null; - profile.posExecutive = position?.posExecutive?.posExecutiveName ?? _null; - profile.positionArea = position?.positionArea ?? _null; - profile.positionExecutiveField = position?.positionExecutiveField ?? _null; - } + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + //create employeePosmaster + const filteredEmployeePosMaster = _orgemployeePosMaster.filter( + (x: EmployeePosMaster) => x.orgRootId == dataId && x.orgChild1Id == null, + ); - profilesToSave.push(profile); - } - } - - // เก็บข้อมูลสำหรับ update posMaster - posMasterUpdates.push({ - id: item.id, - current_holderId: item.next_holderId, - }); - - // เก็บ IDs ที่ต้องสร้าง history - const oldHolderId = oldPm ? oldPm.current_holderId : null; - const newHolderId = item?.next_holderId; - const isHolderChanged = oldHolderId !== newHolderId; - - if (isHolderChanged) { - historyCreateIds.push(item.id); - } - } - console.timeEnd('[AMQ] prepare_batch_data'); - console.log(`[AMQ] Prepared - posMasterAssignsToSave: ${posMasterAssignsToSave.length}, profilesToSave: ${profilesToSave.length}, posMasterUpdates: ${posMasterUpdates.length}, historyCreateIds: ${historyCreateIds.length}`); - - // ===== BATCH EXECUTION: save ทีละ batch ===== - - // 4. Batch save posMasterAssign (chunk 500) - console.time('[AMQ] batch_save_posMasterAssign'); - if (posMasterAssignsToSave.length > 0) { - const chunks = chunkArray(posMasterAssignsToSave, 500); - for (const chunk of chunks) { - await posMasterAssignRepository.save(chunk); - } - } - console.timeEnd('[AMQ] batch_save_posMasterAssign'); - - // 5. Batch save profiles (chunk 200) - console.time('[AMQ] batch_save_profiles'); - if (profilesToSave.length > 0) { - const chunks = chunkArray(profilesToSave, 200); - for (const chunk of chunks) { - await repoProfile.save(chunk); - } - } - console.timeEnd('[AMQ] batch_save_profiles'); - - // 6. Batch update posMasters - console.time('[AMQ] batch_update_posMasters'); - - const posMasterUpdatesForBatch = posMasterUpdates.map((u: any) => ({ - id: u.id, - current_holderId: u.current_holderId ?? null, - lastUpdateUserId, - lastUpdateFullName, - lastUpdatedAt, - })); - - await BatchUpdatePosMasters( - AppDataSource.manager, - posMasterUpdatesForBatch - ); - - console.timeEnd('[AMQ] batch_update_posMasters'); - - // 7. Batch create history - console.time('[AMQ] batch_create_history'); - - const historyOperations: BatchHistoryOperation[] = []; - for (const id of historyCreateIds) { - const pm = posMaster.find(p => p.id === id); - if (pm) { - historyOperations.push({ - posMasterId: id, - posMasterData: pm, - orgRevisionId: pm.orgRevisionId, - lastUpdateUserId, - lastUpdateFullName, - }); - } - } - - await BatchCreatePosMasterHistoryOfficer( - AppDataSource.manager, - historyOperations - ); - - console.timeEnd('[AMQ] batch_create_history'); - - // Clone oldposMasterAct - console.time('[AMQ] clone_oldposMasterAct'); - for (const act of oldposMasterAct) { - const parentDNA = act.posMaster?.ancestorDNA?.trim()?.toLowerCase() ?? ''; - const childDNA = act.posMasterChild?.ancestorDNA?.trim()?.toLowerCase() ?? ''; - - const newParentId = posMasterIdMap.get(parentDNA); - const newChildId = posMasterIdMap.get(childDNA); - - if (!newParentId || !newChildId) continue; - - const { id, posMaster, posMasterChild, ...fields } = act; - - const newAct = { - ...fields, - posMasterId: newParentId, - posMasterChildId: newChildId, - createdAt: new Date(), - createdFullName: user ? user.name : "system", - createdUserId: user ? user.sub : "system", - lastUpdatedAt: new Date(), - lastUpdateFullName: user ? user.name : "system", - lastUpdateUserId: user ? user.sub : "system", - }; - - await posMasterActRepository.save(newAct); - } - console.timeEnd('[AMQ] clone_oldposMasterAct'); - - if (orgRevisionPublish != null && orgRevisionDraft != null) { - console.time('[AMQ] clone_org_structure'); - //new main revision - const before = null; - - //ทุก orgRoot และ orgChild ข้างล่างนี้จะเป็นตัวเก่าที่ไม่ได้เป็น current revision - //cone tree - console.time('[AMQ] query_old_org_structure'); - //หา dna tree - const orgRoot = await orgRootRepository.find({ - where: { orgRevisionId: orgRevisionPublish.id }, - }); - - const orgChild1 = await child1Repository.find({ - where: { orgRevisionId: orgRevisionPublish.id }, - }); - - const orgChild2 = await child2Repository.find({ - where: { orgRevisionId: orgRevisionPublish.id }, - }); - - const orgChild3 = await child3Repository.find({ - where: { orgRevisionId: orgRevisionPublish.id }, - }); - - const orgChild4 = await child4Repository.find({ - where: { orgRevisionId: orgRevisionPublish.id }, - }); - console.timeEnd('[AMQ] query_old_org_structure'); - console.log(`[AMQ] Old structure - orgRoot: ${orgRoot.length}, orgChild1: ${orgChild1.length}, orgChild2: ${orgChild2.length}, orgChild3: ${orgChild3.length}, orgChild4: ${orgChild4.length}`); - - // Task #2172 ดึง orgRoot ของ revision ใหม่ - const newRoots = await orgRootRepository.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - }); - // สร้าง newRootMap เอาไว้เก็บ orgRoot.ancestorDNA ของ revision ใหม่ - const newRootMap = new Map( - newRoots.map(r => [r.ancestorDNA, r.id]) - ); - - console.time('[AMQ] clone_permissionProfiles'); - // ดึง permissionProfiles ของ revision เดิม - const oldPermissionProfiles = await permissionProfilesRepository.find({ - relations: ["orgRootTree"], - where: { - orgRootTree: { - orgRevisionId: orgRevisionPublish.id, - } - } - }); - const inserts: any[] = []; - for (const permiss of oldPermissionProfiles) { - // หา orgRootId ใหม่จาก newRootMap - const newRootId = newRootMap.get(permiss.orgRootTree.ancestorDNA); - if (!newRootId) continue; - // ตัด id กับ orgRootTree ออกแล้วสร้าง object ใหม่ - const { id, orgRootTree, ...fields } = permiss; - // เตรียมข้อมูลสำหรับ insert - inserts.push({ - ...fields, - orgRootId: newRootId, - createdAt: lastUpdatedAt, - createdFullName: lastUpdateFullName, - createdUserId: lastUpdateUserId, - lastUpdatedAt: lastUpdatedAt, - lastUpdateFullName: lastUpdateFullName, - lastUpdateUserId: lastUpdateUserId, - }); - } - // ทำการ insert ข้อมูลใหม่ครั้งเดียว - if (inserts.length > 0) { - await permissionProfilesRepository.insert(inserts); - } - console.timeEnd('[AMQ] clone_permissionProfiles'); - - //หา dna posmaster ถ้าไม่มีให้เอาตัวเองเป็น dna - console.time('[AMQ] query_employeePosMaster'); - const orgemployeePosMaster = await repoEmployeePosmaster.find({ - where: { orgRevisionId: orgRevisionPublish.id }, - relations: ["positions"], - }); - console.timeEnd('[AMQ] query_employeePosMaster'); - console.log(`[AMQ] orgemployeePosMaster count: ${orgemployeePosMaster.length}`); - - let _orgemployeePosMaster: EmployeePosMaster[]; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // _orgemployeePosMaster = orgemployeePosMaster.map((x) => ({ - // ...x, - // ancestorDNA: - // x.ancestorDNA == null || x.ancestorDNA == "00000000-0000-0000-0000-000000000000" - // ? x.id - // : x.ancestorDNA, - // })); - // await repoEmployeePosmaster.save(_orgemployeePosMaster); - const validProfileIds = new Set( - (await repoProfileEmployee.find({ select: ["id"] })).map((p) => p.id), - ); - - _orgemployeePosMaster = orgemployeePosMaster.map((x) => ({ - ...x, - current_holderId: - x.current_holderId && validProfileIds.has(x.current_holderId) ? x.current_holderId : null, - ancestorDNA: - !x.ancestorDNA || x.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ? x.id - : x.ancestorDNA, - })); - - console.time('[AMQ] insert_employeePosMaster'); - await repoEmployeePosmaster - .createQueryBuilder() - .insert() - .into(EmployeePosMaster) - .values(_orgemployeePosMaster) - .orUpdate({ - conflict_target: ["id"], - overwrite: ["ancestorDNA"], - }) - .execute(); - console.timeEnd('[AMQ] insert_employeePosMaster'); - - // } - //หา dna posmaster ถ้าไม่มีให้เอาตัวเองเป็น dna - console.time('[AMQ] query_employeeTempPosMaster'); - const orgemployeeTempPosMaster = await repoEmployeeTempPosmaster.find({ - where: { orgRevisionId: orgRevisionPublish.id }, - relations: ["positions"], - }); - console.timeEnd('[AMQ] query_employeeTempPosMaster'); - console.log(`[AMQ] orgemployeeTempPosMaster count: ${orgemployeeTempPosMaster.length}`); - - let _orgemployeeTempPosMaster: EmployeeTempPosMaster[]; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - _orgemployeeTempPosMaster = orgemployeeTempPosMaster.map((x) => ({ - ...x, - ancestorDNA: - x.ancestorDNA == null || x.ancestorDNA == "00000000-0000-0000-0000-000000000000" - ? x.id - : x.ancestorDNA, - })); - // await repoEmployeeTempPosmaster.save(_orgemployeeTempPosMaster); - await repoEmployeeTempPosmaster - .createQueryBuilder() - .insert() - .into(EmployeeTempPosMaster) - .values(_orgemployeeTempPosMaster) - .orUpdate({ - conflict_target: ["id"], - overwrite: ["ancestorDNA"], - }) - .execute(); - // } - - //create org - forEach orgRoot (WARNING: async forEach without await) - console.time('[AMQ] forEach_orgRoot'); - console.log(`[AMQ] Starting forEach orgRoot loop (${orgRoot.length} items)`); - let processedOrgRoot = 0; - orgRoot.forEach(async (x: any) => { - const itemStartTime = Date.now(); - var dataId = x.id; - - const orgRootCurrent = await orgRootRepository.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - }); - - const matchedOrgRoot = orgRootCurrent.find((i: OrgRoot) => { - if ( - x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง - x.ancestorDNA === null || - x.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ) { - return ( - i.ancestorDNA === null || i.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ); - } - return i.ancestorDNA === x.ancestorDNA; - }); - - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - //create employeePosmaster - const filteredEmployeePosMaster = _orgemployeePosMaster - .filter((x: EmployeePosMaster) => x.orgRootId == dataId && x.orgChild1Id == null); - - await Promise.all( - filteredEmployeePosMaster - .map(async (item: any) => { + await Promise.all( + filteredEmployeePosMaster.map(async (item: any) => { delete item.id; const employeePosMaster = Object.assign(new EmployeePosMaster(), item); employeePosMaster.positions = []; @@ -1125,7 +1135,7 @@ async function handler_org(msg: amqp.ConsumeMessage): Promise { await repoEmployeePosmaster.save(employeePosMaster); for (const pos of item.positions) { - delete pos.id; + delete pos.id; const employeePosition: EmployeePosition = Object.assign( new EmployeePosition(), pos, @@ -1145,813 +1155,806 @@ async function handler_org(msg: amqp.ConsumeMessage): Promise { employeePosition.lastUpdatedAt = new Date(); await employeePositionRepository.save(employeePosition); } - }), - ); - //create employeeTempPosmaster - await Promise.all( - _orgemployeeTempPosMaster - .filter((x: EmployeeTempPosMaster) => x.orgRootId == dataId && x.orgChild1Id == null) - .map(async (item: any) => { - delete item.id; - const employeeTempPosMaster = Object.assign(new EmployeeTempPosMaster(), item); - employeeTempPosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.current_holderId = item.current_holderId; - // } else { - // // employeeTempPosMaster.next_holderId = null; - // employeeTempPosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.authRoleId = item.authRoleId; - // } else { - // employeeTempPosMaster.authRoleId = null; - // } - // employeeTempPosMaster.current_holderId = null; - employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; - employeeTempPosMaster.orgRootId = matchedOrgRoot?.id ?? null; - employeeTempPosMaster.createdUserId = ""; - employeeTempPosMaster.createdFullName = "System Administrator"; - employeeTempPosMaster.createdAt = new Date(); - employeeTempPosMaster.lastUpdateUserId = ""; - employeeTempPosMaster.lastUpdateFullName = "System Administrator"; - employeeTempPosMaster.lastUpdatedAt = new Date(); - await repoEmployeeTempPosmaster.save(employeeTempPosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterTempId = employeeTempPosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); - // } - - //create org - orgChild1 - .filter((x: OrgChild1) => x.orgRootId == dataId) - .forEach(async (x: any) => { - var data1Id = x.id; - const orgChild1Current = await child1Repository.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - }); - - const matchedOrgChild1 = orgChild1Current.find((i: OrgChild1) => { - if ( - x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง - x.ancestorDNA === null || - x.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ) { - return ( - i.ancestorDNA === null || i.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ); - } - return i.ancestorDNA === x.ancestorDNA; - }); - // ("[in case Child1] ancestorDNA", `${x.orgChild1Id == matchedOrgChild1?.id}`); - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - //create employeePosmaster - await Promise.all( - _orgemployeePosMaster - .filter((x: EmployeePosMaster) => x.orgChild1Id == data1Id && x.orgChild2Id == null) - .map(async (item: any) => { - delete item.id; - // console.log("[in case Child1] orgChild1Id == data1Id"); - const employeePosMaster = Object.assign(new EmployeePosMaster(), item); - employeePosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeePosMaster.current_holderId = item.current_holderId; - // } else { - // // employeePosMaster.next_holderId = null; - // employeePosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeePosMaster.authRoleId = item.authRoleId; - // } else { - // employeePosMaster.authRoleId = null; - // } - // employeePosMaster.current_holderId = null; - employeePosMaster.orgRevisionId = orgRevisionDraft.id; - employeePosMaster.orgRootId = matchedOrgRoot?.id ?? null; - employeePosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; - employeePosMaster.createdUserId = ""; - employeePosMaster.createdFullName = "System Administrator"; - employeePosMaster.createdAt = new Date(); - employeePosMaster.lastUpdateUserId = ""; - employeePosMaster.lastUpdateFullName = "System Administrator"; - employeePosMaster.lastUpdatedAt = new Date(); - await repoEmployeePosmaster.save(employeePosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterId = employeePosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); - // create employeeTempPosmaster - await Promise.all( - _orgemployeeTempPosMaster - .filter( - (x: EmployeeTempPosMaster) => x.orgChild1Id == data1Id && x.orgChild2Id == null, - ) - .map(async (item: any) => { - delete item.id; - const employeeTempPosMaster = Object.assign(new EmployeeTempPosMaster(), item); - employeeTempPosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.current_holderId = item.current_holderId; - // } else { - // // employeeTempPosMaster.next_holderId = null; - // employeeTempPosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.authRoleId = item.authRoleId; - // } else { - // employeeTempPosMaster.authRoleId = null; - // } - // employeeTempPosMaster.current_holderId = null; - employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; - employeeTempPosMaster.orgRootId = matchedOrgRoot?.id ?? null; - employeeTempPosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; - employeeTempPosMaster.createdUserId = ""; - employeeTempPosMaster.createdFullName = "System Administrator"; - employeeTempPosMaster.createdAt = new Date(); - employeeTempPosMaster.lastUpdateUserId = ""; - employeeTempPosMaster.lastUpdateFullName = "System Administrator"; - employeeTempPosMaster.lastUpdatedAt = new Date(); - await repoEmployeeTempPosmaster.save(employeeTempPosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterTempId = employeeTempPosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); - // } - - //create org - orgChild2 - .filter((x: OrgChild2) => x.orgChild1Id == data1Id) - .forEach(async (x: any) => { - var data2Id = x.id; - const orgChild2Current = await child2Repository.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - }); - - const matchedOrgChild2 = orgChild2Current.find((i: OrgChild2) => { - if ( - x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง - x.ancestorDNA === null || - x.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ) { - return ( - i.ancestorDNA === null || - i.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ); - } - return i.ancestorDNA === x.ancestorDNA; - }); - // console.log("[in case Child2] ancestorDNA", `${x.orgChild2Id == matchedOrgChild2?.id}`); + ); + //create employeeTempPosmaster + await Promise.all( + _orgemployeeTempPosMaster + .filter((x: EmployeeTempPosMaster) => x.orgRootId == dataId && x.orgChild1Id == null) + .map(async (item: any) => { + delete item.id; + const employeeTempPosMaster = Object.assign(new EmployeeTempPosMaster(), item); + employeeTempPosMaster.positions = []; // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.current_holderId = item.current_holderId; + // } else { + // // employeeTempPosMaster.next_holderId = null; + // employeeTempPosMaster.isSit = false; + // } + // if ( // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" // ) { - //create employeePosmaster - await Promise.all( - _orgemployeePosMaster - .filter( - (x: EmployeePosMaster) => x.orgChild2Id == data2Id && x.orgChild3Id == null, - ) - .map(async (item: any) => { - delete item.id; - // console.log("[in case Child2] orgChild2Id == data2Id"); - const employeePosMaster = Object.assign(new EmployeePosMaster(), item); - employeePosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeePosMaster.current_holderId = item.current_holderId; - // } else { - // // employeePosMaster.next_holderId = null; - // employeePosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeePosMaster.authRoleId = item.authRoleId; - // } else { - // employeePosMaster.authRoleId = null; - // } - // employeePosMaster.current_holderId = null; - employeePosMaster.orgRevisionId = orgRevisionDraft.id; - employeePosMaster.orgRootId = matchedOrgRoot?.id ?? null; - employeePosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; - employeePosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; - employeePosMaster.createdUserId = ""; - employeePosMaster.createdFullName = "System Administrator"; - employeePosMaster.createdAt = new Date(); - employeePosMaster.lastUpdateUserId = ""; - employeePosMaster.lastUpdateFullName = "System Administrator"; - employeePosMaster.lastUpdatedAt = new Date(); - await repoEmployeePosmaster.save(employeePosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterId = employeePosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); - // create employeeTempPosmaster - await Promise.all( - _orgemployeeTempPosMaster - .filter( - (x: EmployeeTempPosMaster) => - x.orgChild2Id == data2Id && x.orgChild3Id == null, - ) - .map(async (item: any) => { - delete item.id; - const employeeTempPosMaster = Object.assign( - new EmployeeTempPosMaster(), - item, - ); - employeeTempPosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.current_holderId = item.current_holderId; - // } else { - // // employeeTempPosMaster.next_holderId = null; - // employeeTempPosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.authRoleId = item.authRoleId; - // } else { - // employeeTempPosMaster.authRoleId = null; - // } - // employeeTempPosMaster.current_holderId = null; - employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; - employeeTempPosMaster.orgRootId = dataId; - employeeTempPosMaster.orgChild1Id = data1Id; - employeeTempPosMaster.orgChild2Id = data2Id; - employeeTempPosMaster.createdUserId = ""; - employeeTempPosMaster.createdFullName = "System Administrator"; - employeeTempPosMaster.createdAt = new Date(); - employeeTempPosMaster.lastUpdateUserId = ""; - employeeTempPosMaster.lastUpdateFullName = "System Administrator"; - employeeTempPosMaster.lastUpdatedAt = new Date(); - await repoEmployeeTempPosmaster.save(employeeTempPosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterTempId = employeeTempPosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); + // employeeTempPosMaster.authRoleId = item.authRoleId; + // } else { + // employeeTempPosMaster.authRoleId = null; // } + // employeeTempPosMaster.current_holderId = null; + employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; + employeeTempPosMaster.orgRootId = matchedOrgRoot?.id ?? null; + employeeTempPosMaster.createdUserId = ""; + employeeTempPosMaster.createdFullName = "System Administrator"; + employeeTempPosMaster.createdAt = new Date(); + employeeTempPosMaster.lastUpdateUserId = ""; + employeeTempPosMaster.lastUpdateFullName = "System Administrator"; + employeeTempPosMaster.lastUpdatedAt = new Date(); + await repoEmployeeTempPosmaster.save(employeeTempPosMaster); - //create org - orgChild3 - .filter((x: OrgChild3) => x.orgChild2Id == data2Id) - .forEach(async (x: any) => { - var data3Id = x.id; - const orgChild3Current = await child3Repository.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - }); + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterTempId = employeeTempPosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + // } - const matchedOrgChild3 = orgChild3Current.find((i: OrgChild3) => { - if ( - x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง - x.ancestorDNA === null || - x.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ) { - return ( - i.ancestorDNA === null || - i.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ); - } - return i.ancestorDNA === x.ancestorDNA; - }); - // console.log("[in case Child3] ancestorDNA", `${x.orgChild3Id == matchedOrgChild3?.id}`); + //create org + orgChild1 + .filter((x: OrgChild1) => x.orgRootId == dataId) + .forEach(async (x: any) => { + var data1Id = x.id; + const orgChild1Current = await child1Repository.find({ + where: { orgRevisionId: orgRevisionDraft.id }, + }); + + const matchedOrgChild1 = orgChild1Current.find((i: OrgChild1) => { + if ( + x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง + x.ancestorDNA === null || + x.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ) { + return ( + i.ancestorDNA === null || + i.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ); + } + return i.ancestorDNA === x.ancestorDNA; + }); + // ("[in case Child1] ancestorDNA", `${x.orgChild1Id == matchedOrgChild1?.id}`); + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + //create employeePosmaster + await Promise.all( + _orgemployeePosMaster + .filter( + (x: EmployeePosMaster) => x.orgChild1Id == data1Id && x.orgChild2Id == null, + ) + .map(async (item: any) => { + delete item.id; + // console.log("[in case Child1] orgChild1Id == data1Id"); + const employeePosMaster = Object.assign(new EmployeePosMaster(), item); + employeePosMaster.positions = []; // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeePosMaster.current_holderId = item.current_holderId; + // } else { + // // employeePosMaster.next_holderId = null; + // employeePosMaster.isSit = false; + // } + // if ( // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" // ) { - //create employeePosmaster - await Promise.all( - _orgemployeePosMaster - .filter( - (x: EmployeePosMaster) => - x.orgChild3Id == data3Id && x.orgChild4Id == null, - ) - .map(async (item: any) => { - delete item.id; - // console.log("[in case Child3] orgChild3Id == data3Id"); - const employeePosMaster = Object.assign(new EmployeePosMaster(), item); - employeePosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeePosMaster.current_holderId = item.current_holderId; - // } else { - // // employeePosMaster.next_holderId = null; - // employeePosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeePosMaster.authRoleId = item.authRoleId; - // } else { - // employeePosMaster.authRoleId = null; - // } - // employeePosMaster.current_holderId = null; - employeePosMaster.orgRevisionId = orgRevisionDraft.id; - employeePosMaster.orgRootId = matchedOrgRoot?.id ?? null; - employeePosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; - employeePosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; - employeePosMaster.orgChild3Id = matchedOrgChild3?.id ?? null; - employeePosMaster.createdUserId = ""; - employeePosMaster.createdFullName = "System Administrator"; - employeePosMaster.createdAt = new Date(); - employeePosMaster.lastUpdateUserId = ""; - employeePosMaster.lastUpdateFullName = "System Administrator"; - employeePosMaster.lastUpdatedAt = new Date(); - await repoEmployeePosmaster.save(employeePosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterId = employeePosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); - // create employeeTempPosmaster - await Promise.all( - _orgemployeeTempPosMaster - .filter( - (x: EmployeeTempPosMaster) => - x.orgChild3Id == data3Id && x.orgChild4Id == null, - ) - .map(async (item: any) => { - delete item.id; - const employeeTempPosMaster = Object.assign( - new EmployeeTempPosMaster(), - item, - ); - employeeTempPosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.current_holderId = item.current_holderId; - // } else { - // // employeeTempPosMaster.next_holderId = null; - // employeeTempPosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.authRoleId = item.authRoleId; - // } else { - // employeeTempPosMaster.authRoleId = null; - // } - // employeeTempPosMaster.current_holderId = null; - employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; - employeeTempPosMaster.orgRootId = matchedOrgRoot?.id ?? null; - employeeTempPosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; - employeeTempPosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; - employeeTempPosMaster.orgChild3Id = matchedOrgChild3?.id ?? null; - employeeTempPosMaster.createdUserId = ""; - employeeTempPosMaster.createdFullName = "System Administrator"; - employeeTempPosMaster.createdAt = new Date(); - employeeTempPosMaster.lastUpdateUserId = ""; - employeeTempPosMaster.lastUpdateFullName = "System Administrator"; - employeeTempPosMaster.lastUpdatedAt = new Date(); - await repoEmployeeTempPosmaster.save(employeeTempPosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterTempId = employeeTempPosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); + // employeePosMaster.authRoleId = item.authRoleId; + // } else { + // employeePosMaster.authRoleId = null; // } + // employeePosMaster.current_holderId = null; + employeePosMaster.orgRevisionId = orgRevisionDraft.id; + employeePosMaster.orgRootId = matchedOrgRoot?.id ?? null; + employeePosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; + employeePosMaster.createdUserId = ""; + employeePosMaster.createdFullName = "System Administrator"; + employeePosMaster.createdAt = new Date(); + employeePosMaster.lastUpdateUserId = ""; + employeePosMaster.lastUpdateFullName = "System Administrator"; + employeePosMaster.lastUpdatedAt = new Date(); + await repoEmployeePosmaster.save(employeePosMaster); - //create org - orgChild4 - .filter((x: OrgChild4) => x.orgChild3Id == data3Id) - .forEach(async (x: any) => { - var data4Id = x.id; - const orgChild4Current = await child4Repository.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - }); + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterId = employeePosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + // create employeeTempPosmaster + await Promise.all( + _orgemployeeTempPosMaster + .filter( + (x: EmployeeTempPosMaster) => x.orgChild1Id == data1Id && x.orgChild2Id == null, + ) + .map(async (item: any) => { + delete item.id; + const employeeTempPosMaster = Object.assign(new EmployeeTempPosMaster(), item); + employeeTempPosMaster.positions = []; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.current_holderId = item.current_holderId; + // } else { + // // employeeTempPosMaster.next_holderId = null; + // employeeTempPosMaster.isSit = false; + // } + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.authRoleId = item.authRoleId; + // } else { + // employeeTempPosMaster.authRoleId = null; + // } + // employeeTempPosMaster.current_holderId = null; + employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; + employeeTempPosMaster.orgRootId = matchedOrgRoot?.id ?? null; + employeeTempPosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; + employeeTempPosMaster.createdUserId = ""; + employeeTempPosMaster.createdFullName = "System Administrator"; + employeeTempPosMaster.createdAt = new Date(); + employeeTempPosMaster.lastUpdateUserId = ""; + employeeTempPosMaster.lastUpdateFullName = "System Administrator"; + employeeTempPosMaster.lastUpdatedAt = new Date(); + await repoEmployeeTempPosmaster.save(employeeTempPosMaster); - const matchedOrgChild4 = orgChild4Current.find((i: OrgChild4) => { - if ( - x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง - x.ancestorDNA === null || - x.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ) { - return ( - i.ancestorDNA === null || - i.ancestorDNA === "00000000-0000-0000-0000-000000000000" - ); - } - return i.ancestorDNA === x.ancestorDNA; - }); - // console.log("[in case Child4] ancestorDNA", `${x.orgChild4Id == matchedOrgChild4?.id}`); + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterTempId = employeeTempPosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + // } + + //create org + orgChild2 + .filter((x: OrgChild2) => x.orgChild1Id == data1Id) + .forEach(async (x: any) => { + var data2Id = x.id; + const orgChild2Current = await child2Repository.find({ + where: { orgRevisionId: orgRevisionDraft.id }, + }); + + const matchedOrgChild2 = orgChild2Current.find((i: OrgChild2) => { + if ( + x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง + x.ancestorDNA === null || + x.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ) { + return ( + i.ancestorDNA === null || + i.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ); + } + return i.ancestorDNA === x.ancestorDNA; + }); + // console.log("[in case Child2] ancestorDNA", `${x.orgChild2Id == matchedOrgChild2?.id}`); + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + //create employeePosmaster + await Promise.all( + _orgemployeePosMaster + .filter( + (x: EmployeePosMaster) => x.orgChild2Id == data2Id && x.orgChild3Id == null, + ) + .map(async (item: any) => { + delete item.id; + // console.log("[in case Child2] orgChild2Id == data2Id"); + const employeePosMaster = Object.assign(new EmployeePosMaster(), item); + employeePosMaster.positions = []; // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeePosMaster.current_holderId = item.current_holderId; + // } else { + // // employeePosMaster.next_holderId = null; + // employeePosMaster.isSit = false; + // } + // if ( // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" // ) { - //create employeePosmaster - await Promise.all( - _orgemployeePosMaster - .filter((x: EmployeePosMaster) => x.orgChild4Id == data4Id) - .map(async (item: any) => { - delete item.id; - // console.log("[in case Child4] orgChild4Id == data4Id"); - const employeePosMaster = Object.assign( - new EmployeePosMaster(), - item, - ); - employeePosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeePosMaster.current_holderId = item.current_holderId; - // } else { - // // employeePosMaster.next_holderId = null; - // employeePosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeePosMaster.authRoleId = item.authRoleId; - // } else { - // employeePosMaster.authRoleId = null; - // } - // employeePosMaster.current_holderId = null; - employeePosMaster.orgRevisionId = orgRevisionDraft.id; - employeePosMaster.orgRootId = matchedOrgRoot?.id ?? null; - employeePosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; - employeePosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; - employeePosMaster.orgChild3Id = matchedOrgChild3?.id ?? null; - employeePosMaster.orgChild4Id = matchedOrgChild4?.id ?? null; - employeePosMaster.createdUserId = ""; - employeePosMaster.createdFullName = "System Administrator"; - employeePosMaster.createdAt = new Date(); - employeePosMaster.lastUpdateUserId = ""; - employeePosMaster.lastUpdateFullName = "System Administrator"; - employeePosMaster.lastUpdatedAt = new Date(); - await repoEmployeePosmaster.save(employeePosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterId = employeePosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); - //create employeeTempPosmaster - await Promise.all( - _orgemployeeTempPosMaster - .filter((x: EmployeeTempPosMaster) => x.orgChild4Id == data4Id) - .map(async (item: any) => { - delete item.id; - const employeeTempPosMaster = Object.assign( - new EmployeeTempPosMaster(), - item, - ); - employeeTempPosMaster.positions = []; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.current_holderId = item.current_holderId; - // } else { - // // employeeTempPosMaster.next_holderId = null; - // employeeTempPosMaster.isSit = false; - // } - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" - // ) { - // employeeTempPosMaster.authRoleId = item.authRoleId; - // } else { - // employeeTempPosMaster.authRoleId = null; - // } - // employeeTempPosMaster.current_holderId = null; - employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; - employeeTempPosMaster.orgRootId = matchedOrgRoot?.id ?? null; - employeeTempPosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; - employeeTempPosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; - employeeTempPosMaster.orgChild3Id = matchedOrgChild3?.id ?? null; - employeeTempPosMaster.orgChild4Id = matchedOrgChild4?.id ?? null; - employeeTempPosMaster.createdUserId = ""; - employeeTempPosMaster.createdFullName = "System Administrator"; - employeeTempPosMaster.createdAt = new Date(); - employeeTempPosMaster.lastUpdateUserId = ""; - employeeTempPosMaster.lastUpdateFullName = "System Administrator"; - employeeTempPosMaster.lastUpdatedAt = new Date(); - await repoEmployeeTempPosmaster.save(employeeTempPosMaster); - - for (const pos of item.positions) { - delete pos.id; - const employeePosition: EmployeePosition = Object.assign( - new EmployeePosition(), - pos, - ); - employeePosition.posMasterTempId = employeeTempPosMaster.id; - // if ( - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || - // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" - // ) { - // employeePosition.positionIsSelected = false; - // } - employeePosition.createdUserId = ""; - employeePosition.createdFullName = "System Administrator"; - employeePosition.createdAt = new Date(); - employeePosition.lastUpdateUserId = ""; - employeePosition.lastUpdateFullName = "System Administrator"; - employeePosition.lastUpdatedAt = new Date(); - await employeePositionRepository.save(employeePosition); - } - - }), - ); + // employeePosMaster.authRoleId = item.authRoleId; + // } else { + // employeePosMaster.authRoleId = null; // } + // employeePosMaster.current_holderId = null; + employeePosMaster.orgRevisionId = orgRevisionDraft.id; + employeePosMaster.orgRootId = matchedOrgRoot?.id ?? null; + employeePosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; + employeePosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; + employeePosMaster.createdUserId = ""; + employeePosMaster.createdFullName = "System Administrator"; + employeePosMaster.createdAt = new Date(); + employeePosMaster.lastUpdateUserId = ""; + employeePosMaster.lastUpdateFullName = "System Administrator"; + employeePosMaster.lastUpdatedAt = new Date(); + await repoEmployeePosmaster.save(employeePosMaster); + + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterId = employeePosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + // create employeeTempPosmaster + await Promise.all( + _orgemployeeTempPosMaster + .filter( + (x: EmployeeTempPosMaster) => + x.orgChild2Id == data2Id && x.orgChild3Id == null, + ) + .map(async (item: any) => { + delete item.id; + const employeeTempPosMaster = Object.assign( + new EmployeeTempPosMaster(), + item, + ); + employeeTempPosMaster.positions = []; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.current_holderId = item.current_holderId; + // } else { + // // employeeTempPosMaster.next_holderId = null; + // employeeTempPosMaster.isSit = false; + // } + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.authRoleId = item.authRoleId; + // } else { + // employeeTempPosMaster.authRoleId = null; + // } + // employeeTempPosMaster.current_holderId = null; + employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; + employeeTempPosMaster.orgRootId = dataId; + employeeTempPosMaster.orgChild1Id = data1Id; + employeeTempPosMaster.orgChild2Id = data2Id; + employeeTempPosMaster.createdUserId = ""; + employeeTempPosMaster.createdFullName = "System Administrator"; + employeeTempPosMaster.createdAt = new Date(); + employeeTempPosMaster.lastUpdateUserId = ""; + employeeTempPosMaster.lastUpdateFullName = "System Administrator"; + employeeTempPosMaster.lastUpdatedAt = new Date(); + await repoEmployeeTempPosmaster.save(employeeTempPosMaster); + + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterTempId = employeeTempPosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + // } + + //create org + orgChild3 + .filter((x: OrgChild3) => x.orgChild2Id == data2Id) + .forEach(async (x: any) => { + var data3Id = x.id; + const orgChild3Current = await child3Repository.find({ + where: { orgRevisionId: orgRevisionDraft.id }, }); - }); - }); - }); - }); - // } - const employeePosMaster = await repoEmployeePosmaster.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - relations: ["positions", "positions.posLevel", "positions.posType"], - }); - for (const item of employeePosMaster) { - if (item.next_holderId != null) { - const profile = await repoProfileEmployee.findOne({ - where: { id: item.next_holderId == null ? "" : item.next_holderId }, - }); - const position = await item.positions.find((x) => x.positionIsSelected == true); - const _null: any = null; - if (profile != null) { - profile.posLevelId = position?.posLevelId ?? _null; - profile.posTypeId = position?.posTypeId ?? _null; - profile.position = position?.positionName ?? _null; - await repoProfileEmployee.save(profile); + const matchedOrgChild3 = orgChild3Current.find((i: OrgChild3) => { + if ( + x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง + x.ancestorDNA === null || + x.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ) { + return ( + i.ancestorDNA === null || + i.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ); + } + return i.ancestorDNA === x.ancestorDNA; + }); + // console.log("[in case Child3] ancestorDNA", `${x.orgChild3Id == matchedOrgChild3?.id}`); + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + //create employeePosmaster + await Promise.all( + _orgemployeePosMaster + .filter( + (x: EmployeePosMaster) => + x.orgChild3Id == data3Id && x.orgChild4Id == null, + ) + .map(async (item: any) => { + delete item.id; + // console.log("[in case Child3] orgChild3Id == data3Id"); + const employeePosMaster = Object.assign(new EmployeePosMaster(), item); + employeePosMaster.positions = []; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeePosMaster.current_holderId = item.current_holderId; + // } else { + // // employeePosMaster.next_holderId = null; + // employeePosMaster.isSit = false; + // } + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeePosMaster.authRoleId = item.authRoleId; + // } else { + // employeePosMaster.authRoleId = null; + // } + // employeePosMaster.current_holderId = null; + employeePosMaster.orgRevisionId = orgRevisionDraft.id; + employeePosMaster.orgRootId = matchedOrgRoot?.id ?? null; + employeePosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; + employeePosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; + employeePosMaster.orgChild3Id = matchedOrgChild3?.id ?? null; + employeePosMaster.createdUserId = ""; + employeePosMaster.createdFullName = "System Administrator"; + employeePosMaster.createdAt = new Date(); + employeePosMaster.lastUpdateUserId = ""; + employeePosMaster.lastUpdateFullName = "System Administrator"; + employeePosMaster.lastUpdatedAt = new Date(); + await repoEmployeePosmaster.save(employeePosMaster); + + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterId = employeePosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + // create employeeTempPosmaster + await Promise.all( + _orgemployeeTempPosMaster + .filter( + (x: EmployeeTempPosMaster) => + x.orgChild3Id == data3Id && x.orgChild4Id == null, + ) + .map(async (item: any) => { + delete item.id; + const employeeTempPosMaster = Object.assign( + new EmployeeTempPosMaster(), + item, + ); + employeeTempPosMaster.positions = []; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.current_holderId = item.current_holderId; + // } else { + // // employeeTempPosMaster.next_holderId = null; + // employeeTempPosMaster.isSit = false; + // } + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.authRoleId = item.authRoleId; + // } else { + // employeeTempPosMaster.authRoleId = null; + // } + // employeeTempPosMaster.current_holderId = null; + employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; + employeeTempPosMaster.orgRootId = matchedOrgRoot?.id ?? null; + employeeTempPosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; + employeeTempPosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; + employeeTempPosMaster.orgChild3Id = matchedOrgChild3?.id ?? null; + employeeTempPosMaster.createdUserId = ""; + employeeTempPosMaster.createdFullName = "System Administrator"; + employeeTempPosMaster.createdAt = new Date(); + employeeTempPosMaster.lastUpdateUserId = ""; + employeeTempPosMaster.lastUpdateFullName = "System Administrator"; + employeeTempPosMaster.lastUpdatedAt = new Date(); + await repoEmployeeTempPosmaster.save(employeeTempPosMaster); + + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterTempId = employeeTempPosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + // } + + //create org + orgChild4 + .filter((x: OrgChild4) => x.orgChild3Id == data3Id) + .forEach(async (x: any) => { + var data4Id = x.id; + const orgChild4Current = await child4Repository.find({ + where: { orgRevisionId: orgRevisionDraft.id }, + }); + + const matchedOrgChild4 = orgChild4Current.find((i: OrgChild4) => { + if ( + x.ancestorDNA === x.id || // ถ้า ancestorDNA ถูกตั้งเป็น id ตัวเอง + x.ancestorDNA === null || + x.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ) { + return ( + i.ancestorDNA === null || + i.ancestorDNA === "00000000-0000-0000-0000-000000000000" + ); + } + return i.ancestorDNA === x.ancestorDNA; + }); + // console.log("[in case Child4] ancestorDNA", `${x.orgChild4Id == matchedOrgChild4?.id}`); + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + //create employeePosmaster + await Promise.all( + _orgemployeePosMaster + .filter((x: EmployeePosMaster) => x.orgChild4Id == data4Id) + .map(async (item: any) => { + delete item.id; + // console.log("[in case Child4] orgChild4Id == data4Id"); + const employeePosMaster = Object.assign( + new EmployeePosMaster(), + item, + ); + employeePosMaster.positions = []; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeePosMaster.current_holderId = item.current_holderId; + // } else { + // // employeePosMaster.next_holderId = null; + // employeePosMaster.isSit = false; + // } + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeePosMaster.authRoleId = item.authRoleId; + // } else { + // employeePosMaster.authRoleId = null; + // } + // employeePosMaster.current_holderId = null; + employeePosMaster.orgRevisionId = orgRevisionDraft.id; + employeePosMaster.orgRootId = matchedOrgRoot?.id ?? null; + employeePosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; + employeePosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; + employeePosMaster.orgChild3Id = matchedOrgChild3?.id ?? null; + employeePosMaster.orgChild4Id = matchedOrgChild4?.id ?? null; + employeePosMaster.createdUserId = ""; + employeePosMaster.createdFullName = "System Administrator"; + employeePosMaster.createdAt = new Date(); + employeePosMaster.lastUpdateUserId = ""; + employeePosMaster.lastUpdateFullName = "System Administrator"; + employeePosMaster.lastUpdatedAt = new Date(); + await repoEmployeePosmaster.save(employeePosMaster); + + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterId = employeePosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + //create employeeTempPosmaster + await Promise.all( + _orgemployeeTempPosMaster + .filter((x: EmployeeTempPosMaster) => x.orgChild4Id == data4Id) + .map(async (item: any) => { + delete item.id; + const employeeTempPosMaster = Object.assign( + new EmployeeTempPosMaster(), + item, + ); + employeeTempPosMaster.positions = []; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.current_holderId = item.current_holderId; + // } else { + // // employeeTempPosMaster.next_holderId = null; + // employeeTempPosMaster.isSit = false; + // } + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_PERSON_ROLE" + // ) { + // employeeTempPosMaster.authRoleId = item.authRoleId; + // } else { + // employeeTempPosMaster.authRoleId = null; + // } + // employeeTempPosMaster.current_holderId = null; + employeeTempPosMaster.orgRevisionId = orgRevisionDraft.id; + employeeTempPosMaster.orgRootId = matchedOrgRoot?.id ?? null; + employeeTempPosMaster.orgChild1Id = matchedOrgChild1?.id ?? null; + employeeTempPosMaster.orgChild2Id = matchedOrgChild2?.id ?? null; + employeeTempPosMaster.orgChild3Id = matchedOrgChild3?.id ?? null; + employeeTempPosMaster.orgChild4Id = matchedOrgChild4?.id ?? null; + employeeTempPosMaster.createdUserId = ""; + employeeTempPosMaster.createdFullName = "System Administrator"; + employeeTempPosMaster.createdAt = new Date(); + employeeTempPosMaster.lastUpdateUserId = ""; + employeeTempPosMaster.lastUpdateFullName = "System Administrator"; + employeeTempPosMaster.lastUpdatedAt = new Date(); + await repoEmployeeTempPosmaster.save(employeeTempPosMaster); + + for (const pos of item.positions) { + delete pos.id; + const employeePosition: EmployeePosition = Object.assign( + new EmployeePosition(), + pos, + ); + employeePosition.posMasterTempId = employeeTempPosMaster.id; + // if ( + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION" || + // requestBody.typeDraft.toUpperCase() == "ORG_POSITION_ROLE" + // ) { + // employeePosition.positionIsSelected = false; + // } + employeePosition.createdUserId = ""; + employeePosition.createdFullName = "System Administrator"; + employeePosition.createdAt = new Date(); + employeePosition.lastUpdateUserId = ""; + employeePosition.lastUpdateFullName = "System Administrator"; + employeePosition.lastUpdatedAt = new Date(); + await employeePositionRepository.save(employeePosition); + } + }), + ); + // } + }); + }); + }); + }); + }); + // } + + const employeePosMaster = await repoEmployeePosmaster.find({ + where: { orgRevisionId: orgRevisionDraft.id }, + relations: ["positions", "positions.posLevel", "positions.posType"], + }); + for (const item of employeePosMaster) { + if (item.next_holderId != null) { + const profile = await repoProfileEmployee.findOne({ + where: { id: item.next_holderId == null ? "" : item.next_holderId }, + }); + const position = await item.positions.find((x) => x.positionIsSelected == true); + const _null: any = null; + if (profile != null) { + profile.posLevelId = position?.posLevelId ?? _null; + profile.posTypeId = position?.posTypeId ?? _null; + profile.position = position?.positionName ?? _null; + await repoProfileEmployee.save(profile); + } } + // item.current_holderId = item.next_holderId; + // item.next_holderId = null; + item.lastUpdateUserId = lastUpdateUserId; + item.lastUpdateFullName = lastUpdateFullName; + item.lastUpdatedAt = lastUpdatedAt; + await repoEmployeePosmaster.save(item).catch((e) => console.log(e)); } - // item.current_holderId = item.next_holderId; - // item.next_holderId = null; - item.lastUpdateUserId = lastUpdateUserId; - item.lastUpdateFullName = lastUpdateFullName; - item.lastUpdatedAt = lastUpdatedAt; - await repoEmployeePosmaster.save(item).catch((e) => console.log(e)); - } - const employeeTempPosMaster = await repoEmployeeTempPosmaster.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - relations: ["positions", "positions.posLevel", "positions.posType"], - }); - for (const item of employeeTempPosMaster) { - if (item.next_holderId != null) { - const profile = await repoProfileEmployee.findOne({ - where: { id: item.next_holderId == null ? "" : item.next_holderId }, - }); - const position = await item.positions.find((x) => x.positionIsSelected == true); - const _null: any = null; - if (profile != null) { - profile.posLevelId = position?.posLevelId ?? _null; - profile.posTypeId = position?.posTypeId ?? _null; - profile.position = position?.positionName ?? _null; - await repoProfileEmployee.save(profile); + const employeeTempPosMaster = await repoEmployeeTempPosmaster.find({ + where: { orgRevisionId: orgRevisionDraft.id }, + relations: ["positions", "positions.posLevel", "positions.posType"], + }); + for (const item of employeeTempPosMaster) { + if (item.next_holderId != null) { + const profile = await repoProfileEmployee.findOne({ + where: { id: item.next_holderId == null ? "" : item.next_holderId }, + }); + const position = await item.positions.find((x) => x.positionIsSelected == true); + const _null: any = null; + if (profile != null) { + profile.posLevelId = position?.posLevelId ?? _null; + profile.posTypeId = position?.posTypeId ?? _null; + profile.position = position?.positionName ?? _null; + await repoProfileEmployee.save(profile); + } } + // item.current_holderId = item.next_holderId; + // item.next_holderId = null; + item.lastUpdateUserId = lastUpdateUserId; + item.lastUpdateFullName = lastUpdateFullName; + item.lastUpdatedAt = lastUpdatedAt; + await repoEmployeeTempPosmaster.save(item).catch((e) => console.log(e)); } - // item.current_holderId = item.next_holderId; - // item.next_holderId = null; - item.lastUpdateUserId = lastUpdateUserId; - item.lastUpdateFullName = lastUpdateFullName; - item.lastUpdatedAt = lastUpdatedAt; - await repoEmployeeTempPosmaster.save(item).catch((e) => console.log(e)); } - } - console.log("[AMQ] Excecute Organization Success"); - if (user) { - sendWebSocket( - "send-publish-org", - { - success: true, - message: `ระบบทำการเผยแพร่โครงสร้างหน่วยงานเรียบร้อยแล้ว`, - }, - { userId: user?.sub }, - ).catch(console.error); - } - console.timeEnd('[AMQ] clone_org_structure'); + console.log("[AMQ] Excecute Organization Success"); + if (user) { + sendWebSocket( + "send-publish-org", + { + success: true, + message: `ระบบทำการเผยแพร่โครงสร้างหน่วยงานเรียบร้อยแล้ว`, + }, + { userId: user?.sub }, + ).catch(console.error); + } + console.timeEnd("[AMQ] clone_org_structure"); - // อัปเดตสถานะ orgRevision หลังจากทำงานเสร็จทั้งหมด - console.time('[AMQ] save_revision_status'); - orgRevisionPublish.orgRevisionIsDraft = false; - orgRevisionPublish.orgRevisionIsCurrent = false; - await repoOrgRevision.save(orgRevisionPublish); + // อัปเดตสถานะ orgRevision หลังจากทำงานเสร็จทั้งหมด + console.time("[AMQ] save_revision_status"); + orgRevisionPublish.orgRevisionIsDraft = false; + orgRevisionPublish.orgRevisionIsCurrent = false; + await repoOrgRevision.save(orgRevisionPublish); - orgRevisionDraft.orgRevisionIsCurrent = true; - orgRevisionDraft.orgRevisionIsDraft = false; - await repoOrgRevision.save(orgRevisionDraft); - console.timeEnd('[AMQ] save_revision_status'); + orgRevisionDraft.orgRevisionIsCurrent = true; + orgRevisionDraft.orgRevisionIsDraft = false; + await repoOrgRevision.save(orgRevisionDraft); + console.timeEnd("[AMQ] save_revision_status"); console.log(`[AMQ] handler_org SUCCESS - Total time: ${Date.now() - startTime}ms`); - console.timeEnd('[AMQ] handler_org_total'); + console.timeEnd("[AMQ] handler_org_total"); return true; }); // ✅ END TRANSACTION - All operations succeeded, data is committed } catch (error) { // ✅ TRANSACTION AUTOMATICALLY ROLLED BACK - No data was saved const totalTime = Date.now() - startTime; console.error(`[AMQ] handler_org ERROR after ${totalTime}ms:`, error); - console.error('[AMQ] Transaction rolled back - all changes were undone'); + console.error("[AMQ] Transaction rolled back - all changes were undone"); if (user) { sendWebSocket( "send-publish-org", @@ -1962,7 +1965,7 @@ async function handler_org(msg: amqp.ConsumeMessage): Promise { { userId: user?.sub }, ).catch(console.error); } - console.timeEnd('[AMQ] handler_org_total'); + console.timeEnd("[AMQ] handler_org_total"); throw error; // ✅ Re-throw to be caught by createConsumer's try-catch } } @@ -2637,7 +2640,8 @@ async function handler_org_draft(msg: amqp.ConsumeMessage): Promise { }); await posMasterAssignRepository.delete({ posMasterId: In(_posMasters.map((x) => x.id)) }); await posMasterActRepository.delete({ posMasterId: In(_posMasters.map((x) => x.id)) }); //ใช้ posMasterId ของ revision: draft *แต่ยังไม่เจอช็อดไหนที่ใช้โครงสร้างแบบร่างในรักษาการแทน - await posMasterActRepository.delete({ //ใช้ posMasterId ของ revision: draft *แต่ยังไม่เจอช็อดไหนที่ใช้โครงสร้างแบบร่างในรักษาการแทน + await posMasterActRepository.delete({ + //ใช้ posMasterId ของ revision: draft *แต่ยังไม่เจอช็อดไหนที่ใช้โครงสร้างแบบร่างในรักษาการแทน posMasterChildId: In(_posMasters.map((x) => x.id)), }); // await posMasterRepository.remove(_posMasters); @@ -2665,24 +2669,26 @@ async function handler_org_draft(msg: amqp.ConsumeMessage): Promise { await child2Repository.delete({ orgRevisionId: In(_orgRevisions.map((x) => x.id)) }); await child1Repository.delete({ orgRevisionId: In(_orgRevisions.map((x) => x.id)) }); // Task #2160 อัพเดทหน้าที่จัดการโครงสร้างแบบร่าง - if (["ORG", "ORG_POSITION", "ORG_POSITION_PERSON", "ORG_POSITION_ROLE", "ORG_POSITION_PERSON_ROLE"].includes(requestBody.typeDraft?.toUpperCase())) { + if ( + [ + "ORG", + "ORG_POSITION", + "ORG_POSITION_PERSON", + "ORG_POSITION_ROLE", + "ORG_POSITION_PERSON_ROLE", + ].includes(requestBody.typeDraft?.toUpperCase()) + ) { const _newRoots = await orgRootRepository.find({ - where: { orgRevisionId: revision.id } + where: { orgRevisionId: revision.id }, }); - const newRootMap = new Map( - _newRoots.map(r => [r.ancestorDNA, r.id]) - ); + const newRootMap = new Map(_newRoots.map((r) => [r.ancestorDNA, r.id])); for (const oldRoot of _roots) { const newRootId = newRootMap.get(oldRoot.ancestorDNA); if (!newRootId) continue; // อัพเดท orgRootId ที่อยู่ภายใต้ orgRevision แบบร่างเดิมเป็นของ orgRevision แบบร่างใหม่ - await permissionOrgRepository.update( - { orgRootId: oldRoot.id }, - { orgRootId: newRootId } - ); + await permissionOrgRepository.update({ orgRootId: oldRoot.id }, { orgRootId: newRootId }); } - } - else { + } else { await permissionOrgRepository.delete({ orgRootId: In(_roots.map((x) => x.id)), });