-- 1.0.347 模块看板统一异步重算任务表与作用域锁。
SET NAMES utf8mb4;

CREATE TABLE IF NOT EXISTS `ado_module_dashboard_rebuild_job` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `module_code` VARCHAR(8) NOT NULL,
  `tenant_id` BIGINT NOT NULL,
  `factory_id` BIGINT NOT NULL DEFAULT 1,
  `status` VARCHAR(20) NOT NULL,
  `trigger_type` VARCHAR(20) NOT NULL,
  `requested_by` BIGINT NULL,
  `batch_id` VARCHAR(100) NULL,
  `transform_run_log_id` BIGINT NULL,
  `current_stage` VARCHAR(32) NOT NULL DEFAULT 'QUEUED',
  `stage_index` TINYINT NOT NULL DEFAULT 0,
  `stage_total` TINYINT NOT NULL DEFAULT 0,
  `progress_percent` TINYINT NOT NULL DEFAULT 0,
  `progress_message` VARCHAR(255) NULL,
  `failed_stage` VARCHAR(32) NULL,
  `stage_rows` INT NOT NULL DEFAULT 0,
  `standard_rows` INT NOT NULL DEFAULT 0,
  `dwd_rows` INT NOT NULL DEFAULT 0,
  `kpi_rows` INT NOT NULL DEFAULT 0,
  `atomic_rows` INT NOT NULL DEFAULT 0,
  `detail_json` TEXT NULL,
  `error_message` VARCHAR(2000) NULL,
  `submitted_at` DATETIME(3) NOT NULL,
  `started_at` DATETIME(3) NULL,
  `finished_at` DATETIME(3) NULL,
  `heartbeat_at` DATETIME(3) NULL,
  `last_progress_at` DATETIME(3) NULL,
  `duration_ms` BIGINT NULL,
  `create_time` DATETIME(3) NOT NULL,
  `update_time` DATETIME(3) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ix_mdp_rebuild_scope` (`module_code`, `tenant_id`, `factory_id`, `status`, `submitted_at`),
  KEY `ix_mdp_rebuild_status` (`status`, `submitted_at`),
  KEY `ix_mdp_rebuild_heartbeat` (`heartbeat_at`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `ado_mdp_rebuild_lock` (
  `lock_name` VARCHAR(160) NOT NULL,
  `module_code` VARCHAR(8) NOT NULL,
  `tenant_id` BIGINT NOT NULL,
  `factory_id` BIGINT NOT NULL,
  `holder_id` VARCHAR(100) NULL,
  `job_id` BIGINT NULL,
  `status` VARCHAR(20) NOT NULL DEFAULT 'FREE',
  `acquired_at` DATETIME(3) NULL,
  `heartbeat_at` DATETIME(3) NULL,
  `create_time` DATETIME(3) NOT NULL,
  `update_time` DATETIME(3) NOT NULL,
  PRIMARY KEY (`lock_name`),
  KEY `ix_mdp_rebuild_lock_scope` (`module_code`, `tenant_id`, `factory_id`),
  KEY `ix_mdp_rebuild_lock_heartbeat` (`status`, `heartbeat_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
