-- =====================================================================
-- tradingSystem (PMS) V1 建表 DDL
-- 目标库: 153 代理侧 (与 decision_ledger 等同库), 一律经代理严格单表访问
-- 字符集: utf8mb4; 代码格式: Tushare 点式 (600000.SH); 时区: Asia/Shanghai
-- 对应设计: POSITION_MGMT_DESIGN.md V0.4 §11
-- 注: pms_order_request (指令通道) 归属待 B1.7 协商, 其 DDL 见
--     QMT_INTERFACE_REQUIREMENTS.md, 不在本文件建立。
-- =====================================================================

-- 1. 命令表 (参数命令 + 任务命令; 参数命令当前值 = 该类型最新一条 EFFECTIVE 记录)
CREATE TABLE IF NOT EXISTS pms_command (
  id            BIGINT PRIMARY KEY AUTO_INCREMENT,
  command_id    VARCHAR(64)  NOT NULL UNIQUE COMMENT '幂等键: CMD_{ymd}_{seq}',
  cmd_class     VARCHAR(8)   NOT NULL COMMENT 'param(参数命令) / task(任务命令)',
  cmd_type      VARCHAR(32)  NOT NULL COMMENT 'SET_SCALE / REDUCE_EXPOSURE / OPEN_TARGET / T0_ENABLE ...',
  ts_code       VARCHAR(16)  NULL     COMMENT '个股级命令的标的; 组合级为 NULL',
  params_json   TEXT         NOT NULL COMMENT '命令参数 (比例/窗口/价格等)',
  status        VARCHAR(16)  NOT NULL DEFAULT 'PENDING'
                COMMENT '参数命令: EFFECTIVE/SUPERSEDED; 任务命令: PENDING/PLANNING/EXECUTING/PARTIAL/DONE/CANCELLED',
  progress_json TEXT         NULL     COMMENT '任务进度 (目标额/已完成额/明细指针/回执)',
  issued_by     VARCHAR(32)  NOT NULL DEFAULT 'user',
  issued_at     DATETIME     NOT NULL,
  done_at       DATETIME     NULL,
  note          VARCHAR(500) NULL,
  KEY idx_type_status (cmd_type, status),
  KEY idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户命令与进度';

-- 2. 方案明细 (任务命令展开的分股行动清单)
CREATE TABLE IF NOT EXISTS pms_plan (
  id            BIGINT PRIMARY KEY AUTO_INCREMENT,
  plan_id       VARCHAR(64)  NOT NULL UNIQUE COMMENT 'PLAN_{command_id}_{seq}',
  command_id    VARCHAR(64)  NOT NULL,
  ts_code       VARCHAR(16)  NOT NULL,
  action        VARCHAR(16)  NOT NULL COMMENT 'OPEN/FILL/ADD/DCA/TRIM/EXIT/HALT/T0_ROUND',
  qty           INT          NULL     COMMENT '目标股数 (与 amount 二选一)',
  amount        DECIMAL(14,2) NULL    COMMENT '目标金额 (元)',
  priority      INT          NOT NULL DEFAULT 100 COMMENT '越小越先执行',
  deadline      DATE         NULL     COMMENT '执行窗口截止日',
  status        VARCHAR(16)  NOT NULL DEFAULT 'PENDING'
                COMMENT 'PENDING/EXECUTING/DONE/PARTIAL/CANCELLED',
  filled_qty    INT          NOT NULL DEFAULT 0,
  reason        VARCHAR(300) NULL     COMMENT '进方案的理由 (弱票清仓/收利润/等比减 等)',
  created_at    DATETIME     NOT NULL,
  updated_at    DATETIME     NOT NULL,
  KEY idx_cmd (command_id),
  KEY idx_code_status (ts_code, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='方案明细';

-- 3. 持仓主档 (一票一行; 实际持仓以下游 trading_position 为准, 本表是结构解释账本)
CREATE TABLE IF NOT EXISTS pms_position (
  id                BIGINT PRIMARY KEY AUTO_INCREMENT,
  ts_code           VARCHAR(16)  NOT NULL UNIQUE,
  status            VARCHAR(16)  NOT NULL DEFAULT 'HOLDING'
                    COMMENT 'PLANNED/OPENING/HOLDING/EXITING/CLOSED',
  frozen_reason     VARCHAR(16)  NOT NULL DEFAULT 'NONE'
                    COMMENT 'NONE/COMMAND_HALT/BRAKE/MANUAL (只禁增持不禁减持)',
  total_qty         INT          NOT NULL DEFAULT 0,
  avail_qty         INT          NOT NULL DEFAULT 0 COMMENT 'T+1 可卖数, 日初重置',
  base_qty          INT          NOT NULL DEFAULT 0,
  fill_qty          INT          NOT NULL DEFAULT 0,
  add_qty           INT          NOT NULL DEFAULT 0,
  dca_qty           INT          NOT NULL DEFAULT 0,
  t0_qty            INT          NOT NULL DEFAULT 0 COMMENT '日内T仓 (收盘应为0)',
  avg_cost          DECIMAL(10,3) NULL COMMENT '摊薄成本 (含已实现T利润与批次盈亏)',
  realized_t_profit DECIMAL(14,2) NOT NULL DEFAULT 0,
  cushion_pct       DECIMAL(8,4) NULL COMMENT '安全垫 = 现价/摊薄成本 - 1',
  cushion_state     VARCHAR(8)   NOT NULL DEFAULT 'NONE' COMMENT 'NONE/THIN/SOLID',
  cushion_peak      DECIMAL(8,4) NOT NULL DEFAULT 0,
  pct_of_scale      DECIMAL(8,4) NULL COMMENT '市值占总规模比',
  target_pct        DECIMAL(8,4) NULL COMMENT '目标仓位比 (建仓命令设定)',
  stop_ref          DECIMAL(10,2) NULL COMMENT '止损参考位',
  support_ref       DECIMAL(10,2) NULL,
  pressure_ref      DECIMAL(10,2) NULL,
  ref_source        VARCHAR(16)  NULL COMMENT 'bionic / self_calc(兜底自算) / user(命令覆盖)',
  t0_enabled        TINYINT      NOT NULL DEFAULT 0,
  t0_ratio          DECIMAL(6,4) NULL,
  opened_date       DATE         NULL,
  fill_count        INT          NOT NULL DEFAULT 0,
  last_add_date     DATE         NULL,
  dca_count         INT          NOT NULL DEFAULT 0,
  t0_count_today    INT          NOT NULL DEFAULT 0,
  updated_at        DATETIME     NOT NULL,
  KEY idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='持仓主档';

-- 4. 批次账
CREATE TABLE IF NOT EXISTS pms_lot (
  id              BIGINT PRIMARY KEY AUTO_INCREMENT,
  ts_code         VARCHAR(16)  NOT NULL,
  lot_type        VARCHAR(8)   NOT NULL COMMENT 'BASE/FILL/ADD/DCA/T0/RECON(对账调整)',
  qty             INT          NOT NULL,
  open_price      DECIMAL(10,3) NOT NULL,
  open_date       DATE         NOT NULL,
  closed_qty      INT          NOT NULL DEFAULT 0,
  close_avg_price DECIMAL(10,3) NULL,
  realized_pnl    DECIMAL(14,2) NOT NULL DEFAULT 0,
  status          VARCHAR(8)   NOT NULL DEFAULT 'OPEN' COMMENT 'OPEN/CLOSED',
  instruction_id  VARCHAR(64)  NULL COMMENT '来源指令; NULL=外部成交并入',
  note            VARCHAR(200) NULL,
  created_at      DATETIME     NOT NULL,
  updated_at      DATETIME     NOT NULL,
  KEY idx_code_status (ts_code, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='批次账';

-- 5. 指令状态机 (父指令; 分日出手的子单记 progress_json)
CREATE TABLE IF NOT EXISTS pms_instruction (
  id             BIGINT PRIMARY KEY AUTO_INCREMENT,
  instruction_id VARCHAR(64)  NOT NULL UNIQUE COMMENT '幂等键: INS_{ymd}_{code}_{action}_{seq}',
  origin_type    VARCHAR(8)   NOT NULL COMMENT 'plan(命令方案) / proposal(自主提议) / system(保垫等自动)',
  origin_id      VARCHAR(64)  NULL,
  ts_code        VARCHAR(16)  NOT NULL,
  action         VARCHAR(16)  NOT NULL,
  side           VARCHAR(8)   NOT NULL COMMENT 'buy/sell',
  qty            INT          NOT NULL,
  limit_price    DECIMAL(10,2) NULL,
  window_tdays   INT          NOT NULL DEFAULT 3,
  status         VARCHAR(20)  NOT NULL DEFAULT 'PROPOSED'
                 COMMENT 'PROPOSED/RULE_PASSED/JUDGE_PASSED/DISPATCHED/CONFIRMED/REJECTED/EXPIRED/CANCELLED',
  dispatch_ref   VARCHAR(64)  NULL COMMENT '下游通道引用 (pms_order_request.instruction_id)',
  exec_qty       INT          NOT NULL DEFAULT 0,
  exec_avg_price DECIMAL(10,3) NULL,
  progress_json  TEXT         NULL COMMENT '分日子单与出手记录',
  created_at     DATETIME     NOT NULL,
  updated_at     DATETIME     NOT NULL,
  KEY idx_code_status (ts_code, status),
  KEY idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='指令状态机';

-- 6. 自主提议待确认队列 (propose_only 档)
CREATE TABLE IF NOT EXISTS pms_proposal (
  id                BIGINT PRIMARY KEY AUTO_INCREMENT,
  proposal_id       VARCHAR(64)  NOT NULL UNIQUE,
  ts_code           VARCHAR(16)  NOT NULL,
  action            VARCHAR(16)  NOT NULL,
  qty               INT          NOT NULL,
  hard_numbers_json TEXT         NOT NULL COMMENT '安全垫/浮亏/参考位距离/敞口等, 页面展示',
  judge_verdict     VARCHAR(16)  NULL COMMENT '决策系统研判结论 (接通后)',
  judge_reason      VARCHAR(500) NULL,
  status            VARCHAR(16)  NOT NULL DEFAULT 'WAIT_USER'
                    COMMENT 'WAIT_USER/ACCEPTED/DECLINED/EXPIRED',
  expire_at         DATETIME     NOT NULL,
  decided_at        DATETIME     NULL,
  created_at        DATETIME     NOT NULL,
  KEY idx_status (status),
  KEY idx_code (ts_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='自主提议待确认';

-- 7. 评审账本 (规则闸/研判闸/人工确认 全量留痕, 判分锚)
CREATE TABLE IF NOT EXISTS pms_action_ledger (
  id                BIGINT PRIMARY KEY AUTO_INCREMENT,
  ts_code           VARCHAR(16)  NOT NULL,
  decided_at        DATETIME     NOT NULL,
  action            VARCHAR(16)  NOT NULL,
  arbiter           VARCHAR(8)   NOT NULL COMMENT 'rule/judge/user',
  verdict           VARCHAR(8)   NOT NULL COMMENT 'PASS/REJECT',
  price_at          DECIMAL(10,3) NOT NULL COMMENT '评审时现价 (反事实判分锚, 必填)',
  hard_numbers_json TEXT         NULL,
  failed_checks_json TEXT        NULL COMMENT '未通过项列表 (规则闸)',
  reason            VARCHAR(500) NULL COMMENT '理由 (研判闸/人工)',
  ref_id            VARCHAR(64)  NULL COMMENT '关联 instruction/proposal/plan',
  outcome_scored    TINYINT      NOT NULL DEFAULT 0 COMMENT '判分位图: 1=T+1, 2=T+5, 4=T+20',
  KEY idx_code_time (ts_code, decided_at),
  KEY idx_scored (outcome_scored)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='评审账本';

-- 8. 运营日报 (可重跑覆盖)
CREATE TABLE IF NOT EXISTS pms_daily_report (
  id          BIGINT PRIMARY KEY AUTO_INCREMENT,
  ymd         INT          NOT NULL UNIQUE COMMENT 'YYYYMMDD',
  report_json MEDIUMTEXT   NOT NULL,
  created_at  DATETIME     NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='运营日报';

-- 9. 行业映射 (行业划分接口的 custom_table 数据源; 用户后续灌数, 灌何种划分不限)
CREATE TABLE IF NOT EXISTS pms_industry_map (
  ts_code    VARCHAR(16) PRIMARY KEY,
  industry   VARCHAR(64) NOT NULL,
  updated_at DATETIME    NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='行业映射 (自定义数据源)';

-- 10. 运行参数持久层 (页面修改的参数落此, 优先于 settings 文件初值)
CREATE TABLE IF NOT EXISTS pms_runtime_param (
  param_key   VARCHAR(64) PRIMARY KEY,
  param_value VARCHAR(200) NOT NULL,
  updated_by  VARCHAR(32)  NOT NULL DEFAULT 'user',
  updated_at  DATETIME     NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='页面可调参数当前值';
