'use strict'; /** * 订单绑定下属公司(货主):order_index 与各订单状态表增加 subsidiary_id。 * * 取值跟随订单所属店铺的货主(店铺 = 货主),历史数据按店铺回填; * 货主权限仅可见自己所属公司的订单,且不可越界操作。 */ const STATUS_TABLES = [ 'order_status_pending', 'order_status_queued', 'order_status_exception', 'order_status_outsourcing', 'order_status_delivery', 'order_status_void', 'order_status_canceled', 'order_status_history', ]; module.exports = { async up(queryInterface, Sequelize) { await queryInterface.addColumn('order_index', 'subsidiary_id', { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '所属货主(下属公司ID),跟随店铺', references: { model: 'principal_subsidiaries', key: 'id' }, after: 'principal_id', }); await queryInterface.addIndex('order_index', [ 'principal_id', 'subsidiary_id' ], { name: 'idx_order_index_principal_subsidiary', }); for (const table of STATUS_TABLES) { await queryInterface.addColumn(table, 'subsidiary_id', { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '所属货主(下属公司ID),跟随店铺', references: { model: 'principal_subsidiaries', key: 'id' }, after: 'principal_id', }); await queryInterface.addIndex(table, [ 'principal_id', 'subsidiary_id' ], { name: `idx_${table}_principal_subsidiary`, }); } // 按订单所属店铺的货主回填历史数据(状态表自带 shop_id;索引表按状态表回填) for (const table of STATUS_TABLES) { await queryInterface.sequelize.query( `UPDATE ${table} t` + ' JOIN shops s ON s.id = t.shop_id' + ' SET t.subsidiary_id = s.subsidiary_id' + ' WHERE t.subsidiary_id IS NULL AND s.subsidiary_id IS NOT NULL' ); } const unionSql = STATUS_TABLES .map(table => `SELECT id, subsidiary_id FROM ${table} WHERE subsidiary_id IS NOT NULL`) .join(' UNION ALL '); await queryInterface.sequelize.query( 'UPDATE order_index oi' + ` JOIN (${unionSql}) st ON st.id = oi.id` + ' SET oi.subsidiary_id = st.subsidiary_id' + ' WHERE oi.subsidiary_id IS NULL' ); }, async down(queryInterface) { for (const table of STATUS_TABLES) { await queryInterface.removeIndex(table, `idx_${table}_principal_subsidiary`); await queryInterface.removeColumn(table, 'subsidiary_id'); } await queryInterface.removeIndex('order_index', 'idx_order_index_principal_subsidiary'); await queryInterface.removeColumn('order_index', 'subsidiary_id'); }, };