USE jiaheng_erp;

SET NAMES utf8mb4;

CREATE TABLE IF NOT EXISTS document_archives (
  id BIGINT NOT NULL AUTO_INCREMENT COMMENT '归档记录ID',
  document_type VARCHAR(50) NOT NULL COMMENT '单据类型：销售订单/采购订单',
  business_id BIGINT NOT NULL COMMENT '业务单据ID',
  document_no VARCHAR(100) NOT NULL COMMENT '业务单据编号',
  archive_version INT NOT NULL COMMENT '归档版本号',
  template_version VARCHAR(50) NOT NULL COMMENT '模板版本',
  file_format VARCHAR(20) NOT NULL COMMENT '文件格式',
  file_name VARCHAR(255) NOT NULL COMMENT '文件名',
  file_path VARCHAR(500) NOT NULL COMMENT '文件路径',
  file_hash VARCHAR(128) NULL COMMENT '文件哈希',
  status VARCHAR(32) NOT NULL COMMENT '归档状态：未生成/已归档/归档失败',
  error_message TEXT NULL COMMENT '归档失败原因',
  created_by BIGINT NULL COMMENT '创建人用户ID',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (id),
  UNIQUE KEY uk_document_archives_version (document_type, business_id, archive_version, file_format),
  KEY idx_document_archives_business_latest (document_type, business_id, archive_version),
  KEY idx_document_archives_document_no (document_no),
  KEY idx_document_archives_status (status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='单据PDF归档记录';
