-- 给 psi_sales 表增加 item_type 字段，用于精确识别成品/物料类型
-- 幂等升级：可多次安全执行

DROP PROCEDURE IF EXISTS `psi_add_item_type`;
DELIMITER $$
CREATE PROCEDURE `psi_add_item_type`()
BEGIN
  IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='psi_sales' AND COLUMN_NAME='item_type') THEN
    ALTER TABLE psi_sales ADD COLUMN item_type VARCHAR(16) DEFAULT '' AFTER item_id;
  END IF;
END$$
DELIMITER ;
CALL `psi_add_item_type`();
DROP PROCEDURE IF EXISTS `psi_add_item_type`;

-- 如果有 stock_moves 记录，尝试补齐现有数据的 item_type
UPDATE psi_sales s
LEFT JOIN psi_stock_moves m ON m.ref_no = s.order_no AND m.item_id = s.item_id AND m.qty = s.qty
SET s.item_type = m.item_type
WHERE s.item_type = '' AND m.item_type IS NOT NULL AND m.item_type != '';
