import { MigrationInterface, QueryRunner } from 'typeorm'; export class F4InventoryFunctionHistory1790000100000 implements MigrationInterface { name = 'F4InventoryFunctionHistory1790000100000'; public async up(queryRunner: QueryRunner): Promise { await queryRunner.query(` CREATE TABLE inventory_functions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), code varchar(120) NOT NULL UNIQUE, name varchar(240) NOT NULL, description text, is_active boolean NOT NULL DEFAULT true, sort_order integer NOT NULL DEFAULT 0, created_by uuid, updated_by uuid, created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT fk_inventory_functions_created_by FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL, CONSTRAINT fk_inventory_functions_updated_by FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL ) `); await queryRunner.query(` CREATE INDEX idx_inventory_functions_active_sort ON inventory_functions(is_active,sort_order,name) `); await queryRunner.query(` CREATE TABLE inventory_function_assignments ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), asset_id uuid NOT NULL, function_id uuid NOT NULL, valid_from timestamptz NOT NULL, valid_until timestamptz, change_reason text, changed_by uuid, created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT fk_inventory_function_assignment_asset FOREIGN KEY (asset_id) REFERENCES assets(id) ON DELETE CASCADE, CONSTRAINT fk_inventory_function_assignment_function FOREIGN KEY (function_id) REFERENCES inventory_functions(id) ON DELETE RESTRICT, CONSTRAINT fk_inventory_function_assignment_user FOREIGN KEY (changed_by) REFERENCES users(id) ON DELETE SET NULL, CONSTRAINT chk_inventory_function_assignment_dates CHECK ( valid_until IS NULL OR valid_until > valid_from ) ) `); await queryRunner.query(` CREATE UNIQUE INDEX uq_inventory_function_assignment_current ON inventory_function_assignments(asset_id) WHERE valid_until IS NULL `); await queryRunner.query(` CREATE INDEX idx_inventory_function_assignment_history ON inventory_function_assignments(asset_id,valid_from DESC,created_at DESC) `); await queryRunner.query(` CREATE INDEX idx_inventory_function_assignment_function ON inventory_function_assignments(function_id,valid_from DESC) `); await queryRunner.query(` INSERT INTO inventory_functions(code,name,description,sort_order) VALUES ('BOMBEO_MECANICO_AIB','Bombeo mecánico AIB', 'Función técnica de bombeo mecánico mediante aparato individual de bombeo (AIB).',10), ('BOMBEO_MECANICO_ROTAFLEX','Bombeo mecánico Rotaflex', 'Función técnica de bombeo mecánico mediante sistema Rotaflex.',20) ON CONFLICT (code) DO NOTHING `); } public async down(queryRunner: QueryRunner): Promise { await queryRunner.query('DROP TABLE IF EXISTS inventory_function_assignments'); await queryRunner.query('DROP TABLE IF EXISTS inventory_functions'); } }