'use strict'; /** * 入库单 / 出库单:新增仓库(warehouse_id)、商品总数(item_total)、商品种类数(item_kind) * 并把旧状态值重映射为新状态机:1待入/出库->已创建(1);2已入/出库->完成(4);3已取消->已取消(9) * 同时按现有明细回算商品总数与种类数 */ module.exports = { async up(queryInterface, Sequelize) { const tables = [ { name: 'inbound_orders', billType: 1 }, { name: 'outbound_orders', billType: 2 }, ]; for (const { name, billType } of tables) { await queryInterface.addColumn(name, 'warehouse_id', { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '仓库ID(关联 warehouses)', references: { model: 'warehouses', key: 'id' }, onDelete: 'SET NULL', }); await queryInterface.addColumn(name, 'item_total', { type: Sequelize.DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '商品总数(明细数量合计)', }); await queryInterface.addColumn(name, 'item_kind', { type: Sequelize.INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '商品种类数(不重复商品数)', }); await queryInterface.addIndex(name, { fields: ['warehouse_id'], name: `idx_${name}_warehouse` }); // 旧状态重映射 await queryInterface.sequelize.query( `UPDATE ${name} SET status = CASE WHEN status = 2 THEN 4 WHEN status = 3 THEN 9 ELSE 1 END WHERE status IN (1, 2, 3)` ); // 按现有明细回算总数/种类数 const recalc = ` UPDATE ${name} t SET item_total = COALESCE((SELECT SUM(quantity) FROM stock_items si WHERE si.bill_type = ? AND si.bill_id = t.id), 0), item_kind = COALESCE((SELECT COUNT(DISTINCT CASE WHEN si.product_id IS NOT NULL THEN CONCAT('p', si.product_id) ELSE CONCAT('i', si.id) END) FROM stock_items si WHERE si.bill_type = ? AND si.bill_id = t.id), 0) `; await queryInterface.sequelize.query(recalc, { replacements: [billType, billType] }); } }, async down(queryInterface) { for (const name of ['inbound_orders', 'outbound_orders']) { await queryInterface.removeColumn(name, 'warehouse_id'); await queryInterface.removeColumn(name, 'item_total'); await queryInterface.removeColumn(name, 'item_kind'); } }, };