-- 采购计划 (erp_purchase_plan) 相关 DDL
-- 在主库 jdbc:mysql://140.143.206.120:13306/klp-oa-test 上执行

-- 1. 采购计划头
CREATE TABLE IF NOT EXISTS `erp_purchase_plan` (
  `plan_id`        BIGINT        NOT NULL AUTO_INCREMENT COMMENT '计划ID',
  `plan_no`        VARCHAR(64)   NOT NULL                COMMENT '采购计划号',
  `plan_status`    CHAR(1)       NOT NULL DEFAULT '0'    COMMENT '计划状态: 0-进行中 1-已完成归档',
  `audit_status`   CHAR(1)       NOT NULL DEFAULT '0'    COMMENT '审核状态: 0-待审核 1-通过 2-驳回',
  `audit_opinion`  VARCHAR(512)  DEFAULT NULL            COMMENT '申请/审核意见',
  `auditor`        VARCHAR(64)   DEFAULT NULL            COMMENT '审核人',
  `audit_time`     DATETIME      DEFAULT NULL            COMMENT '审核时间',
  `supplier`       VARCHAR(128)  DEFAULT NULL            COMMENT '供货商',
  `purchase_date`  DATE          DEFAULT NULL            COMMENT '采购日期',
  `plan_weight`    DECIMAL(14,3) NOT NULL DEFAULT 0      COMMENT '计划总重量(T)',
  `arrived_weight` DECIMAL(14,3) NOT NULL DEFAULT 0      COMMENT '已到货重量(T)',
  `del_flag`       CHAR(1)       NOT NULL DEFAULT '0'    COMMENT '删除标志: 0-存在 2-删除',
  `create_by`      VARCHAR(64)   DEFAULT NULL,
  `create_time`    DATETIME      DEFAULT NULL,
  `update_by`      VARCHAR(64)   DEFAULT NULL,
  `update_time`    DATETIME      DEFAULT NULL,
  `remark`         VARCHAR(512)  DEFAULT NULL            COMMENT '备注',
  PRIMARY KEY (`plan_id`),
  UNIQUE KEY `uk_plan_no` (`plan_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购计划头';

-- 2. 采购计划明细（多规格行，字段对齐 crm_order_item）
CREATE TABLE IF NOT EXISTS `erp_purchase_plan_item` (
  `item_id`             BIGINT        NOT NULL AUTO_INCREMENT COMMENT '明细ID',
  `plan_id`             BIGINT        NOT NULL               COMMENT '关联计划ID',
  `product_type`        VARCHAR(64)   DEFAULT NULL           COMMENT '产品(如热轧卷板)',
  `material`            VARCHAR(64)   DEFAULT NULL           COMMENT '材质',
  `grade`               VARCHAR(64)   DEFAULT NULL           COMMENT '牌号',
  `coil_no`             VARCHAR(64)   DEFAULT NULL           COMMENT '卷号',
  `width`               VARCHAR(64)   DEFAULT NULL           COMMENT '宽度(mm，可为区间文本，对齐 crm_order_item)',
  `thickness`           VARCHAR(64)   DEFAULT NULL           COMMENT '厚度(mm，可为区间文本)',
  `width_tolerance`     VARCHAR(64)   DEFAULT '0'            COMMENT '宽度公差(自由文本)',
  `thickness_tolerance` VARCHAR(64)   DEFAULT '0'            COMMENT '厚度公差(自由文本)',
  `weight`              DECIMAL(14,3) DEFAULT NULL           COMMENT '重量(T)',
  `quantity`            INT           DEFAULT NULL           COMMENT '数量(件/卷数，来自合同 product_num)',
  `arrived_weight`      DECIMAL(14,3) NOT NULL DEFAULT 0     COMMENT '已到货重量(T)，由到货Excel按牌号+规格累加',
  `item_status`         CHAR(1)       NOT NULL DEFAULT '0'   COMMENT '到货状态: 0-未到货 1-部分到货 2-已到货',
  `supplier`            VARCHAR(128)  DEFAULT NULL           COMMENT '供货商',
  `del_flag`            CHAR(1)       NOT NULL DEFAULT '0'   COMMENT '删除标志',
  `create_by`           VARCHAR(64)   DEFAULT NULL,
  `create_time`         DATETIME      DEFAULT NULL,
  `update_by`           VARCHAR(64)   DEFAULT NULL,
  `update_time`         DATETIME      DEFAULT NULL,
  `remark`              VARCHAR(512)  DEFAULT NULL,
  PRIMARY KEY (`item_id`),
  KEY `idx_plan_id` (`plan_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购计划明细';

-- 3. 计划↔销售合同(crm_order) 中间表（多对多，挂合同头）
CREATE TABLE IF NOT EXISTS `erp_purchase_plan_contract_rel` (
  `rel_id`      BIGINT      NOT NULL AUTO_INCREMENT COMMENT '关系ID',
  `plan_id`     BIGINT      NOT NULL               COMMENT '采购计划ID',
  `order_id`    BIGINT      NOT NULL               COMMENT '销售合同ID(crm_order.order_id)',
  `del_flag`    CHAR(1)     NOT NULL DEFAULT '0'   COMMENT '删除标志',
  `create_by`   VARCHAR(64) DEFAULT NULL,
  `create_time` DATETIME    DEFAULT NULL,
  `update_by`   VARCHAR(64) DEFAULT NULL,
  `update_time` DATETIME    DEFAULT NULL,
  `remark`      VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`rel_id`),
  KEY `idx_plan_id`  (`plan_id`),
  KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购计划-销售合同关联表';

-- 4. 到货明细（对应上传的到货 Excel，一行一卷，独立于 WMS）
CREATE TABLE IF NOT EXISTS `erp_purchase_plan_delivery` (
  `delivery_id`     BIGINT        NOT NULL AUTO_INCREMENT COMMENT '到货明细ID',
  `plan_id`         BIGINT        NOT NULL               COMMENT '关联计划ID',
  `arrival_date`    DATE          DEFAULT NULL           COMMENT '日期',
  `grade`           VARCHAR(64)   DEFAULT NULL           COMMENT '牌号',
  `spec`            VARCHAR(64)   DEFAULT NULL           COMMENT '规格(厚×宽)',
  `coil_no`         VARCHAR(64)   DEFAULT NULL           COMMENT '卷号',
  `coil_weight`     DECIMAL(14,3) DEFAULT NULL           COMMENT '单卷重量(T)',
  `truck_no`        VARCHAR(64)   DEFAULT NULL           COMMENT '车号',
  `truck_weight`    DECIMAL(14,3) DEFAULT NULL           COMMENT '整车数量(T)',
  `piece_count`     INT           DEFAULT NULL           COMMENT '件数',
  `sales_code`      VARCHAR(64)   DEFAULT NULL           COMMENT '销售代码',
  `arrival_station` VARCHAR(64)   DEFAULT NULL           COMMENT '钢厂到站',
  `del_flag`        CHAR(1)       NOT NULL DEFAULT '0'   COMMENT '删除标志',
  `create_by`       VARCHAR(64)   DEFAULT NULL,
  `create_time`     DATETIME      DEFAULT NULL,
  `update_by`       VARCHAR(64)   DEFAULT NULL,
  `update_time`     DATETIME      DEFAULT NULL,
  `remark`          VARCHAR(512)  DEFAULT NULL,
  PRIMARY KEY (`delivery_id`),
  KEY `idx_plan_id` (`plan_id`),
  KEY `idx_coil_no` (`coil_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购计划到货明细';

-- 5. 到货上传批次（每上传一份到货表格记一条，便于随时回看每一次上传）
CREATE TABLE IF NOT EXISTS `erp_purchase_plan_delivery_batch` (
  `batch_id`        BIGINT        NOT NULL AUTO_INCREMENT COMMENT '批次ID',
  `plan_id`         BIGINT        NOT NULL               COMMENT '关联计划ID',
  `file_name`       VARCHAR(255)  DEFAULT NULL           COMMENT '文件名',
  `row_count`       INT           DEFAULT 0              COMMENT '本次到货行数',
  `matched_count`   INT           DEFAULT 0              COMMENT '本次匹配上明细卷号的卷数',
  `arrived_percent` DECIMAL(6,2)  DEFAULT 0              COMMENT '上传后到货百分比快照',
  `del_flag`        CHAR(1)       NOT NULL DEFAULT '0'   COMMENT '删除标志',
  `create_by`       VARCHAR(64)   DEFAULT NULL,
  `create_time`     DATETIME      DEFAULT NULL,
  `update_by`       VARCHAR(64)   DEFAULT NULL,
  `update_time`     DATETIME      DEFAULT NULL,
  `remark`          VARCHAR(512)  DEFAULT NULL,
  PRIMARY KEY (`batch_id`),
  KEY `idx_plan_id` (`plan_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购计划到货上传批次';

-- 6. 供应商往来流水台账
CREATE TABLE IF NOT EXISTS `erp_supplier_transaction` (
  `txn_id`      BIGINT        NOT NULL AUTO_INCREMENT COMMENT '往来流水ID',
  `supplier_id` BIGINT        NOT NULL               COMMENT '关联供应商ID',
  `txn_date`    DATE          DEFAULT NULL           COMMENT '发生日期',
  `txn_type`    CHAR(1)       NOT NULL DEFAULT '1'   COMMENT '类型: 1-采购应付 2-付款 3-退货 4-其他',
  `amount`      DECIMAL(16,2) NOT NULL DEFAULT 0     COMMENT '金额',
  `doc_no`      VARCHAR(64)   DEFAULT NULL           COMMENT '单据号',
  `del_flag`    CHAR(1)       NOT NULL DEFAULT '0'   COMMENT '删除标志',
  `create_by`   VARCHAR(64)   DEFAULT NULL,
  `create_time` DATETIME      DEFAULT NULL,
  `update_by`   VARCHAR(64)   DEFAULT NULL,
  `update_time` DATETIME      DEFAULT NULL,
  `remark`      VARCHAR(512)  DEFAULT NULL,
  PRIMARY KEY (`txn_id`),
  KEY `idx_supplier_id` (`supplier_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='供应商往来流水台账';

-- ====== 既有表增列（幂等：列不存在才加） ======
SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan_delivery' AND COLUMN_NAME = 'batch_id');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan_delivery ADD COLUMN batch_id BIGINT NULL COMMENT ''关联上传批次ID'' AFTER plan_id', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- 到货行是否 WMS 钢卷表已确认到货(supplier_coil_no 存在且 data_type<>10)
SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan_delivery' AND COLUMN_NAME = 'arrived');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan_delivery ADD COLUMN arrived TINYINT NOT NULL DEFAULT 0 COMMENT ''是否WMS确认到货:1是0否'' AFTER batch_id', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- 计划要求总数量(卷/件) = Σ明细数量
SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan' AND COLUMN_NAME = 'plan_qty');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan ADD COLUMN plan_qty INT NOT NULL DEFAULT 0 COMMENT ''计划要求总数量(卷/件)'' AFTER arrived_weight', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- 已到货卷数 = WMS确认到货的上传卷数
SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan' AND COLUMN_NAME = 'arrived_count');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan ADD COLUMN arrived_count INT NOT NULL DEFAULT 0 COMMENT ''已到货卷数'' AFTER plan_qty', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- 2026-06-29 大改：采购计划→采购合同；要求改为 规格+总重量+厂商；到货区分已到/在途
SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan_item' AND COLUMN_NAME = 'spec');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan_item ADD COLUMN spec VARCHAR(128) DEFAULT NULL COMMENT ''规格'' AFTER plan_id', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan_item' AND COLUMN_NAME = 'manufacturer');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan_item ADD COLUMN manufacturer VARCHAR(128) DEFAULT NULL COMMENT ''厂商(手填，历史记忆)'' AFTER spec', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan_delivery' AND COLUMN_NAME = 'in_transit');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan_delivery ADD COLUMN in_transit TINYINT NOT NULL DEFAULT 0 COMMENT ''是否在途:1是0否(钢卷表存在且data_type=10)'' AFTER arrived', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan' AND COLUMN_NAME = 'in_transit_count');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan ADD COLUMN in_transit_count INT NOT NULL DEFAULT 0 COMMENT ''在途卷数'' AFTER arrived_count', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @c := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'erp_purchase_plan' AND COLUMN_NAME = 'in_transit_weight');
SET @s := IF(@c = 0, 'ALTER TABLE erp_purchase_plan ADD COLUMN in_transit_weight DECIMAL(14,3) NOT NULL DEFAULT 0 COMMENT ''在途重量(T)'' AFTER in_transit_count', 'SELECT 1');
PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt;


-- ============ 菜单 ============
-- 采购目录挂在「生产辅助」(path=helper) 下；父 id 按 path 动态解析，兼容不同环境的不同 menu_id。
-- 整段可重复执行（叶子菜单用 REPLACE，目录用 存在判断 + 归位 UPDATE）。

-- 1) 解析「生产辅助」目录 id
SET @helper_id = (SELECT menu_id FROM (SELECT menu_id FROM sys_menu WHERE path = 'helper' AND parent_id = 0 LIMIT 1) t);

-- 2) 确保「采购」目录存在（不存在则在「生产辅助」下创建；用派生表规避同表 INSERT...SELECT 限制）
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query_param, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
SELECT 2100000000000000000, '采购', @helper_id, 50, 'purchase', '', '', 1, 0, 'M', '0', '0', '', 'shopping', 'admin', sysdate(), '采购目录'
FROM dual
WHERE NOT EXISTS (SELECT 1 FROM (SELECT menu_id FROM sys_menu WHERE path = 'purchase' AND menu_type = 'M') x);

-- 3) 无论新建还是已存在，确保「采购」目录归位到「生产辅助」下，并设为显示（visible=0，否则其下所有菜单都不会出现在侧边栏）
UPDATE sys_menu SET parent_id = @helper_id, visible = '0', status = '0' WHERE path = 'purchase' AND menu_type = 'M';

-- 4) 解析「采购」目录 id（供下方叶子菜单使用）
SET @purchase_id = (SELECT menu_id FROM (SELECT menu_id FROM sys_menu WHERE path = 'purchase' AND menu_type = 'M' LIMIT 1) t);

-- 5) 采购计划 + 按钮（REPLACE 可重复执行）
REPLACE INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query_param, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark) VALUES
(2100000000000000001, '采购合同', @purchase_id,                2, 'purchasePlan', 'erp/purchasePlan/index', '', 1, 0, 'C', '0', '0', 'erp:purchasePlan:list',   'form', 'admin', sysdate(), '采购合同菜单'),
(2100000000000000002, '采购合同查询', 2100000000000000001, 1, '', '', '', 1, 0, 'F', '0', '0', 'erp:purchasePlan:query',  '#', 'admin', sysdate(), ''),
(2100000000000000003, '采购合同新增', 2100000000000000001, 2, '', '', '', 1, 0, 'F', '0', '0', 'erp:purchasePlan:add',    '#', 'admin', sysdate(), ''),
(2100000000000000004, '采购合同修改', 2100000000000000001, 3, '', '', '', 1, 0, 'F', '0', '0', 'erp:purchasePlan:edit',   '#', 'admin', sysdate(), ''),
(2100000000000000005, '采购合同删除', 2100000000000000001, 4, '', '', '', 1, 0, 'F', '0', '0', 'erp:purchasePlan:remove', '#', 'admin', sysdate(), ''),
(2100000000000000006, '到货导入',     2100000000000000001, 5, '', '', '', 1, 0, 'F', '0', '0', 'erp:purchasePlan:import', '#', 'admin', sysdate(), '');

-- 6) 采购审核 + 按钮（REPLACE 可重复执行）
REPLACE INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query_param, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark) VALUES
(2100000000000000010, '采购审核', @purchase_id,             3, 'purchaseAudit', 'erp/purchaseAudit/index', '', 1, 0, 'C', '0', '0', 'erp:purchasePlan:auditList', 'validCode', 'admin', sysdate(), '采购审核菜单'),
(2100000000000000011, '审核操作', 2100000000000000010, 1, '', '', '', 1, 0, 'F', '0', '0', 'erp:purchasePlan:audit', '#', 'admin', sysdate(), '');

-- 7) 到货记录（审核通过的计划上传到货表格、按卷号比对、到货百分比）
REPLACE INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query_param, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark) VALUES
(2100000000000000020, '到货记录', @purchase_id, 4, 'purchaseDelivery', 'erp/purchaseDelivery/index', '', 1, 0, 'C', '0', '0', 'erp:purchasePlan:list', 'truck', 'admin', sysdate(), '到货记录与卷号比对');
