import { MigrationInterface, QueryRunner } from "typeorm"; import { AUDIT, genRevisionUUID } from "../mockData"; /** * CP3 — Curate orgRevision: wipe all existing org/position structure and seed * a single current revision "โครงสร้าง 2569". Mock org tree + positions are * inserted by later migrations (CP4/CP5a). * * DESTRUCTIVE — relies on CP1 mysqldump backup for rollback. */ export class SeedOrgRevision25691782100000001 implements MigrationInterface { public name = "SeedOrgRevision25691782100000001"; public async up(queryRunner: QueryRunner): Promise { const REV = genRevisionUUID(0); const audit = [AUDIT.createdUserId, AUDIT.lastUpdateUserId, AUDIT.createdFullName, AUDIT.lastUpdateFullName]; await queryRunner.query("SET FOREIGN_KEY_CHECKS = 0"); // Wipe all org/position tables (child → parent order). FK constraints are // mostly stripped in this repo, but FK_CHECKS=0 guards the few that remain. // Some tables may already be gone (e.g. positionOfficer was dropped in the // cleanup step) — only DELETE tables that still exist. const wipeTables = [ "posMasterHistory", "posMasterEmployeeHistory", "posMasterEmployeeTempHistory", "posMasterAct", "posMasterAssign", "positionSalaryEditHistory", "position", "employeePosition", "posMaster", "employeePosMaster", "employeeTempPosMaster", "orgChild4", "orgChild3", "orgChild2", "orgChild1", "permissionOrg", // FK -> orgRoot "orgRoot", "orgRevision", ]; const existingRows = (await queryRunner.query( `SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (${wipeTables.map(() => "?").join(",")})`, wipeTables, )) as Array<{ t: string }>; const existing = new Set(existingRows.map((r) => r.t)); for (const t of wipeTables) { if (existing.has(t)) { await queryRunner.query(`DELETE FROM \`${t}\``); } } // Seed single current revision "โครงสร้าง 2569" (idempotent). await queryRunner.query( `INSERT INTO orgRevision (id, orgRevisionName, orgRevisionIsCurrent, orgRevisionIsDraft, isLock, orgRevisionCreatedAt, createdAt, lastUpdatedAt, createdUserId, lastUpdateUserId, createdFullName, lastUpdateFullName) SELECT ?, 'โครงสร้าง 2569', true, false, false, NOW(), NOW(), NOW(), ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM orgRevision WHERE id = ?)`, [REV, ...audit, REV], ); await queryRunner.query("SET FOREIGN_KEY_CHECKS = 1"); } public async down(queryRunner: QueryRunner): Promise { // Best-effort: remove only the seeded revision row. Full restore = CP1 backup. await queryRunner.query("SET FOREIGN_KEY_CHECKS = 0"); await queryRunner.query(`DELETE FROM orgRevision WHERE id = ?`, [genRevisionUUID(0)]); await queryRunner.query("SET FOREIGN_KEY_CHECKS = 1"); } }