-- 框架合同与框架订单关系（幂等：已存在的列/字段跳过，可安全重复执行）

-- sales_ledger.contract_type / parent_contract_id
SET @c1 = (SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sales_ledger' AND COLUMN_NAME = 'contract_type');
SET @ddl1 = IF(@c1 = 0,
    'ALTER TABLE `sales_ledger` ADD COLUMN `contract_type` tinyint NOT NULL DEFAULT 1 COMMENT ''合同类型：1普通销售合同，2框架合同，3框架订单'' AFTER `sales_contract_no`',
    'SELECT 1');
PREPARE stmt1 FROM @ddl1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

SET @c2 = (SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sales_ledger' AND COLUMN_NAME = 'parent_contract_id');
SET @ddl2 = IF(@c2 = 0,
    'ALTER TABLE `sales_ledger` ADD COLUMN `parent_contract_id` bigint NULL COMMENT ''父框架合同ID'' AFTER `contract_type`',
    'SELECT 1');
PREPARE stmt2 FROM @ddl2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;

-- sales_ledger_product.quantity 允许为空
SET @c3 = (SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sales_ledger_product' AND COLUMN_NAME = 'quantity'
      AND IS_NULLABLE = 'NO');
SET @ddl3 = IF(@c3 = 1,
    'ALTER TABLE `sales_ledger_product` MODIFY COLUMN `quantity` decimal(18, 2) NULL COMMENT ''数量，框架合同和框架订单不记录数量，实际发货数量记录在发货明细''',
    'SELECT 1');
PREPARE stmt3 FROM @ddl3;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;

-- sales_ledger_product.parent_product_id
SET @c4 = (SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sales_ledger_product' AND COLUMN_NAME = 'parent_product_id');
SET @ddl4 = IF(@c4 = 0,
    'ALTER TABLE `sales_ledger_product` ADD COLUMN `parent_product_id` bigint NULL COMMENT ''父框架合同产品ID'' AFTER `sales_ledger_id`',
    'SELECT 1');
PREPARE stmt4 FROM @ddl4;
EXECUTE stmt4;
DEALLOCATE PREPARE stmt4;

-- sales_ledger_product.delivery_date
SET @c5 = (SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sales_ledger_product' AND COLUMN_NAME = 'delivery_date');
SET @ddl5 = IF(@c5 = 0,
    'ALTER TABLE `sales_ledger_product` ADD COLUMN `delivery_date` date NULL COMMENT ''框架订单交货日期'' AFTER `parent_product_id`',
    'SELECT 1');
PREPARE stmt5 FROM @ddl5;
EXECUTE stmt5;
DEALLOCATE PREPARE stmt5;
