From fd7a2af0a1297052d8006a7153f6750f28d38ba7 Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Fri, 1 May 2026 17:08:53 +0700 Subject: [PATCH] rollback code handler_org --- src/services/PositionService.ts | 143 -- src/services/rabbitmq.ts | 2692 +++++++++++++++---------------- 2 files changed, 1320 insertions(+), 1515 deletions(-) diff --git a/src/services/PositionService.ts b/src/services/PositionService.ts index f60539fa..44916aee 100644 --- a/src/services/PositionService.ts +++ b/src/services/PositionService.ts @@ -11,7 +11,6 @@ import { PosMasterHistory } from "../entities/PosMasterHistory"; import { Position } from "../entities/Position"; import { ProfileEducation } from "../entities/ProfileEducation"; import { RequestWithUser } from "../middlewares/user"; -import { chunkArray } from "../interfaces/utils"; export async function CreatePosMasterHistoryOfficer( posMasterId: string, @@ -418,145 +417,3 @@ export async function BatchSavePosMasterHistoryOfficer( return false; } } - -export interface BatchHistoryOperation { - posMasterId: string; - posMasterData: PosMaster; - orgRevisionId: string; - lastUpdateUserId: string; - lastUpdateFullName: string; -} - -export async function BatchUpdatePosMasters( - manager: any, - updates: { id: string; current_holderId: string | null; lastUpdateUserId: string; lastUpdateFullName: string; lastUpdatedAt: Date }[] -): Promise { - if (updates.length === 0) return; - - const CHUNK_SIZE = 5000; - const chunks = chunkArray(updates, CHUNK_SIZE); - - for (const chunk of chunks) { - // Create a temporary table for this batch - const tempTableName = `temp_posmaster_update_${Date.now()}_${Math.random().toString(36).substring(7)}`; - - 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(() => {}); - } - } -} - -export async function BatchCreatePosMasterHistoryOfficer( - manager: any, - operations: BatchHistoryOperation[] -): Promise { - if (operations.length === 0) return; - - const repoHistory = manager.getRepository(PosMasterHistory); - const repoOrgRevision = manager.getRepository(OrgRevision); - const _null: any = null; - - const orgRevisionIds = [...new Set(operations.map(op => op.orgRevisionId))]; - const revisions = await repoOrgRevision.findBy({ - id: In(orgRevisionIds), - orgRevisionIsCurrent: true, - orgRevisionIsDraft: false, - }); - const currentRevisionIds = new Set(revisions.map((r: any) => r.id)); - - const historyRecords: PosMasterHistory[] = []; - - for (const op of operations) { - const pm = op.posMasterData; - const checkCurrentRevision = currentRevisionIds.has(pm.orgRevisionId); - - const h = new PosMasterHistory(); - h.ancestorDNA = pm.ancestorDNA ?? _null; - - if (checkCurrentRevision) { - h.prefix = pm.current_holder?.prefix ?? _null; - h.firstName = pm.current_holder?.firstName ?? _null; - h.lastName = pm.current_holder?.lastName ?? _null; - h.profileId = pm.current_holder?.id ?? _null; - } else { - h.prefix = pm.next_holder?.prefix ?? _null; - h.firstName = pm.next_holder?.firstName ?? _null; - h.lastName = pm.next_holder?.lastName ?? _null; - } - - const selectedPosition = pm.positions?.find((p: any) => p.positionIsSelected === true) ?? null; - h.position = selectedPosition?.positionName ?? _null; - h.posType = selectedPosition?.posType?.posTypeName ?? _null; - h.posLevel = selectedPosition?.posLevel?.posLevelName ?? _null; - h.posExecutive = selectedPosition?.posExecutive?.posExecutiveName ?? _null; - - h.rootDnaId = pm.orgRoot?.ancestorDNA ?? _null; - h.child1DnaId = pm.orgChild1?.ancestorDNA ?? _null; - h.child2DnaId = pm.orgChild2?.ancestorDNA ?? _null; - h.child3DnaId = pm.orgChild3?.ancestorDNA ?? _null; - h.child4DnaId = pm.orgChild4?.ancestorDNA ?? _null; - - h.posMasterNoPrefix = pm.posMasterNoPrefix ?? _null; - h.posMasterNo = pm.posMasterNo ?? _null; - h.posMasterNoSuffix = pm.posMasterNoSuffix ?? _null; - h.shortName = [ - pm.orgChild4?.orgChild4ShortName, - pm.orgChild3?.orgChild3ShortName, - pm.orgChild2?.orgChild2ShortName, - pm.orgChild1?.orgChild1ShortName, - pm.orgRoot?.orgRootShortName, - ].find((s: any) => typeof s === "string" && s.trim().length > 0) ?? _null; - - h.createdUserId = op.lastUpdateUserId; - h.createdFullName = op.lastUpdateFullName; - h.lastUpdateUserId = op.lastUpdateUserId; - h.lastUpdateFullName = op.lastUpdateFullName; - h.createdAt = new Date(); - h.lastUpdatedAt = new Date(); - - historyRecords.push(h); - } - - const CHUNK_SIZE = 500; - const chunks = chunkArray(historyRecords, CHUNK_SIZE); - for (const chunk of chunks) { - await repoHistory.save(chunk); - } -} diff --git a/src/services/rabbitmq.ts b/src/services/rabbitmq.ts index 2f560531..31a4269d 100644 --- a/src/services/rabbitmq.ts +++ b/src/services/rabbitmq.ts @@ -1,4 +1,4 @@ -import * as amqp from "amqplib"; +import amqp from "amqplib"; import { AppDataSource } from "../database/data-source"; import { Command } from "../entities/Command"; import { chunkArray, commandTypePath } from "../interfaces/utils"; @@ -24,12 +24,7 @@ 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 } from "./PositionService"; import { PayloadSendNoti } from "../interfaces/utils"; import { PermissionProfile } from "../entities/PermissionProfile"; @@ -97,6 +92,8 @@ export async function init() { // createConsumer(queue2, channel, handler2); } +let retries = 0; + function createConsumer( //----> consumer queue: string, channel: amqp.Channel, @@ -106,15 +103,13 @@ function createConsumer( //----> consumer queue, async (msg) => { if (!msg) return; - try { - await handler(msg); + if ((await handler(msg)) || retries++ >= 3) { + retries = 0; console.log("[AMQ] Process Consumer success"); - } catch (error) { - console.log("[AMQ] Process Consumer failed"); - } finally { - // Always acknowledge - no retries return channel.ack(msg); } + console.log("[AMQ] Process Consumer failed"); + return await new Promise((resolve) => setTimeout(() => resolve(channel.nack(msg)), 3000)); }, { noAck: false }, ); @@ -410,7 +405,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 } }, @@ -446,14 +441,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() @@ -487,7 +482,8 @@ 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]); } @@ -501,608 +497,559 @@ 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()}`); + const repoPosmaster = AppDataSource.getRepository(PosMaster); + const posMasterAssignRepository = AppDataSource.getRepository(PosMasterAssign); + const posMasterActRepository = AppDataSource.getRepository(PosMasterAct); + const permissionProfilesRepository = AppDataSource.getRepository(PermissionProfile); + const repoEmployeePosmaster = AppDataSource.getRepository(EmployeePosMaster); + const repoEmployeeTempPosmaster = AppDataSource.getRepository(EmployeeTempPosMaster); + const repoProfile = AppDataSource.getRepository(Profile); + const repoProfileEmployee = AppDataSource.getRepository(ProfileEmployee); + const employeePositionRepository = AppDataSource.getRepository(EmployeePosition); + const repoOrgRevision = AppDataSource.getRepository(OrgRevision); + const orgRootRepository = AppDataSource.getRepository(OrgRoot); + const child1Repository = AppDataSource.getRepository(OrgChild1); + const child2Repository = AppDataSource.getRepository(OrgChild2); + const child3Repository = AppDataSource.getRepository(OrgChild3); + const child4Repository = AppDataSource.getRepository(OrgChild4); const { data, token, user } = JSON.parse(msg.content.toString()); + const { id, status, lastUpdateUserId, lastUpdateFullName, lastUpdatedAt } = data; + console.log(`[AMQ] Received message - revisionId: ${id}, status: ${status}`); + + if (user) { + 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(); + + 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: ต้องมี 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) try { - // ✅ WRAP ALL DATABASE OPERATIONS IN TRANSACTION FOR AUTOMATIC ROLLBACK ON ERROR - return await AppDataSource.transaction(async (manager) => { - const repoPosmaster = manager.getRepository(PosMaster); - const posMasterAssignRepository = manager.getRepository(PosMasterAssign); - const posMasterActRepository = manager.getRepository(PosMasterAct); - const permissionProfilesRepository = manager.getRepository(PermissionProfile); - const repoEmployeePosmaster = manager.getRepository(EmployeePosMaster); - const repoEmployeeTempPosmaster = manager.getRepository(EmployeeTempPosMaster); - const repoProfile = manager.getRepository(Profile); - const repoProfileEmployee = manager.getRepository(ProfileEmployee); - const employeePositionRepository = manager.getRepository(EmployeePosition); - const repoOrgRevision = manager.getRepository(OrgRevision); - const orgRootRepository = manager.getRepository(OrgRoot); - const child1Repository = manager.getRepository(OrgChild1); - const child2Repository = manager.getRepository(OrgChild2); - const child3Repository = manager.getRepository(OrgChild3); - const child4Repository = manager.getRepository(OrgChild4); - const { id, status, lastUpdateUserId, lastUpdateFullName, lastUpdatedAt } = data; - console.log(`[AMQ] Received message - revisionId: ${id}, status: ${status}`); + console.time('[AMQ] query_posMaster'); + const posMaster = await repoPosmaster.find({ + where: { orgRevisionId: id }, + relations: [ + "orgRoot", + "orgChild4", + "orgChild3", + "orgChild2", + "orgChild1", + "positions", + "positions.posLevel", + "positions.posType", + "positions.posExecutive", + ], + }); + console.timeEnd('[AMQ] query_posMaster'); + console.log(`[AMQ] posMaster count: ${posMaster.length}`); - if (user) { - sendWebSocket( - "send-publish-org", - { - success: true, - message: `ระบบกำลังทำการเผยแพร่โครงสร้างหน่วยงาน`, - }, - { userId: user?.sub }, - ).catch(console.error); - } + console.time('[AMQ] query_old_data'); + const oldPosMasters = await repoPosmaster.find({ + where: { + orgRevisionId: orgRevisionPublish.id, + }, + select: ['id', 'current_holderId', 'ancestorDNA'] + }); - 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"}`, - ); - - // 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; - } - - // 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[] = []; - - 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; - - 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: { + // Task #2160 ดึง posMasterAssign ของ revision เดิม + const oldposMasterAssigns = await posMasterAssignRepository.find({ + relations: ["posMaster"], + where: { + posMaster: { orgRevisionId: orgRevisionPublish.id, }, - select: ["id", "current_holderId", "ancestorDNA"], - }); + }, + }); + console.timeEnd('[AMQ] query_old_data'); + console.log(`[AMQ] oldPosMasters count: ${oldPosMasters.length}`); + console.log(`[AMQ] oldposMasterAssigns count: ${oldposMasterAssigns.length}`); - // Task #2160 ดึง posMasterAssign ของ revision เดิม - const oldposMasterAssigns = await posMasterAssignRepository.find({ - relations: ["posMaster"], - where: { - posMaster: { - orgRevisionId: orgRevisionPublish.id, - }, + 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'); + + 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}`); + + 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) }); - console.timeEnd("[AMQ] query_old_data"); - console.log(`[AMQ] oldPosMasters count: ${oldPosMasters.length}`); - console.log(`[AMQ] oldposMasterAssigns count: ${oldposMasterAssigns.length}`); + profiles.forEach(p => profilesMap.set(p.id, p)); + } + console.log(`[AMQ] profiles to update: ${profilesMap.size}`); - 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"); + // 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] 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}`); + // ===== LOOP: เก็บข้อมูลทั้งหมด ===== + for (const item of posMaster) { + const dna = item.ancestorDNA?.trim(); + const oldPm = dna ? oldPosMasterMap.get(dna) : null; - 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({ + // Task #2160 Clone posMasterAssign + const assigns = assignMap.get(item.ancestorDNA); + if (assigns && assigns.length > 0) { + const newAssigns = assigns.map(({ id, ...fields }) => + posMasterAssignRepository.create({ ...fields, - orgRootId: newRootId, + posMasterId: item.id, 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); + } - _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, - })); + // เตรียมข้อมูลสำหรับ 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; - 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" - ); + // ถ้าไม่ใช่ตำแหน่งนั่งทับ (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]; + } } - 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, - ); + 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; + } - await Promise.all( - filteredEmployeePosMaster.map(async (item: any) => { + 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'); + for (const update of posMasterUpdates) { + await repoPosmaster.update(update.id, { + current_holderId: update.current_holderId, + next_holderId: null, + lastUpdateUserId, + lastUpdateFullName, + lastUpdatedAt, + }); + } + console.timeEnd('[AMQ] batch_update_posMasters'); + + // 7. Batch create history + console.time('[AMQ] batch_create_history'); + for (const id of historyCreateIds) { + await CreatePosMasterHistoryOfficer(id, null); + } + 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) => { delete item.id; const employeePosMaster = Object.assign(new EmployeePosMaster(), item); employeePosMaster.positions = []; @@ -1134,7 +1081,8 @@ async function handler_org(msg: amqp.ConsumeMessage): Promise { employeePosMaster.lastUpdatedAt = new Date(); await repoEmployeePosmaster.save(employeePosMaster); - for (const pos of item.positions) { + //create employeePosition + item.positions.map(async (pos: any) => { delete pos.id; const employeePosition: EmployeePosition = Object.assign( new EmployeePosition(), @@ -1154,819 +1102,822 @@ async function handler_org(msg: amqp.ConsumeMessage): Promise { employeePosition.lastUpdateFullName = "System Administrator"; 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}`); + ); + //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.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); - } - }), - ); + // 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 - orgChild2 - .filter((x: OrgChild2) => x.orgChild1Id == data1Id) - .forEach(async (x: any) => { - var data2Id = x.id; - const orgChild2Current = await child2Repository.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - }); + //create employeePosition + item.positions.map(async (pos: any) => { + 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 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 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.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); - } - }), - ); + // 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 - orgChild3 - .filter((x: OrgChild3) => x.orgChild2Id == data2Id) - .forEach(async (x: any) => { - var data3Id = x.id; - const orgChild3Current = await child3Repository.find({ - where: { orgRevisionId: orgRevisionDraft.id }, - }); + //create employeePosition + item.positions.map(async (pos: any) => { + 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 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 employeePosition + item.positions.map(async (pos: any) => { + 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.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.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); - //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 }, - }); + //create employeePosition + item.positions.map(async (pos: any) => { + 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); - 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}`); + //create employeePosition + item.positions.map(async (pos: any) => { + 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 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" || // 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.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); + + //create employeePosition + item.positions.map(async (pos: any) => { + 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); + + //create employeePosition + item.positions.map(async (pos: any) => { + 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 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 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); + + //create employeePosition + item.positions.map(async (pos: any) => { + 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); + + //create employeePosition + item.positions.map(async (pos: any) => { + 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)); } - 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 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); } - // 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"); - return true; - }); // ✅ END TRANSACTION - All operations succeeded, data is committed + console.log(`[AMQ] handler_org SUCCESS - Total time: ${Date.now() - startTime}ms`); + console.timeEnd('[AMQ] handler_org_total'); + return true; } 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"); if (user) { sendWebSocket( "send-publish-org", { success: false, - message: `เผยแพร่โครงสร้างหน่วยงานไม่สำเร็จ: ${error instanceof Error ? error.message : String(error)}`, + message: `ระบบทำการเผยแพร่โครงสร้างหน่วยงานไม่สำเร็จ`, }, { userId: user?.sub }, ).catch(console.error); } - console.timeEnd("[AMQ] handler_org_total"); - throw error; // ✅ Re-throw to be caught by createConsumer's try-catch + console.timeEnd('[AMQ] handler_org_total'); + return false; } } @@ -2640,8 +2591,7 @@ 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); @@ -2669,26 +2619,24 @@ 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)), });