'use strict'; /** * 主体(租户)体系 * * - `subjects`:主体,带管理员(默认创建人)与使用期限 `expire_at` * - `subject_members`:主体成员(姓名 + 可选账号绑定),一个主体下同一账号只能有一条 * - 把「设备 / 录像机 / 摄像头 / 工作台 / 扫码记录 / 扫码通道」全部挂到主体上(`subject_id`) * * 数据迁移:给**已有数据**的用户各建一个主体(管理员=本人,期限 +365 天), * 并把其名下数据回填到该主体,保证升级后旧数据仍然可见。 * * 注意:`sql/schema.sql` 基线可能已经包含 `scan_records.subject_id` 等列, * 所以这里所有建表 / 加列 / 加索引都做成幂等,空库和旧库都能反复执行。 */ async function hasTable(queryInterface, table) { const tables = await queryInterface.showAllTables(); return tables.some(item => (typeof item === 'string' ? item : Object.values(item)[0]) === table); } async function hasColumn(queryInterface, table, column) { try { const description = await queryInterface.describeTable(table); return Boolean(description[column]); } catch (error) { return false; } } async function hasIndex(queryInterface, table, name) { try { const indexes = await queryInterface.showIndex(table); return indexes.some(item => item.name === name); } catch (error) { return false; } } module.exports = { async up(queryInterface, Sequelize) { const { BIGINT, STRING, TINYINT, DATE } = Sequelize; const audit = { created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, deleted_at: { type: DATE, allowNull: true }, }; if (!await hasTable(queryInterface, 'subjects')) { await queryInterface.createTable('subjects', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false }, name: { type: STRING(64), allowNull: false, comment: '主体名称' }, admin_user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '管理员用户 users.id(默认创建人)' }, expire_at: { type: DATE, allowNull: false, comment: '使用期限(到期后不可进入)' }, status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' }, remark: { type: STRING(255), allowNull: true, comment: '备注' }, ...audit, }, { comment: '主体表' }); } if (!await hasIndex(queryInterface, 'subjects', 'idx_subjects_admin')) { await queryInterface.addIndex('subjects', [ 'admin_user_id' ], { name: 'idx_subjects_admin' }); } if (!await hasIndex(queryInterface, 'subjects', 'idx_subjects_expire')) { await queryInterface.addIndex('subjects', [ 'expire_at' ], { name: 'idx_subjects_expire' }); } if (!await hasTable(queryInterface, 'subject_members')) { await queryInterface.createTable('subject_members', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false }, subject_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' }, user_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '绑定账号 users.id(未绑定为空)' }, name: { type: STRING(32), allowNull: false, comment: '成员姓名' }, role: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 2, comment: '角色:1管理员 2成员' }, wechat_openid: { type: STRING(64), allowNull: true, comment: '绑定的微信 openid' }, bound_at: { type: DATE, allowNull: true, comment: '成员绑定账号/微信的时间' }, status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' }, ...audit, }, { comment: '主体成员表' }); } // 同一主体下同一账号只能有一条(NULL 不参与唯一性,所以「未绑定的成员」可以有多条) if (!await hasIndex(queryInterface, 'subject_members', 'uk_subject_members_subject_user')) { await queryInterface.addIndex('subject_members', [ 'subject_id', 'user_id' ], { name: 'uk_subject_members_subject_user', unique: true, }); } if (!await hasIndex(queryInterface, 'subject_members', 'idx_subject_members_user')) { await queryInterface.addIndex('subject_members', [ 'user_id' ], { name: 'idx_subject_members_user' }); } // 业务表挂到主体 const targets = [ [ 'scanners', '设备表' ], [ 'nvrs', 'NVR 录像机表' ], [ 'cameras', '摄像头表' ], [ 'workstations', '工作台表' ], [ 'scan_channels', '扫码通道表' ], [ 'scan_records', '扫码记录表' ], ]; for (const [ table ] of targets) { if (!await hasColumn(queryInterface, table, 'subject_id')) { await queryInterface.addColumn(table, 'subject_id', { type: BIGINT.UNSIGNED, allowNull: true, comment: '所属主体 subjects.id', after: 'id', }); } if (!await hasIndex(queryInterface, table, `idx_${table}_subject`)) { await queryInterface.addIndex(table, [ 'subject_id' ], { name: `idx_${table}_subject` }); } } // ---------------- 回填:给已有数据的用户建主体 ---------------- const expireExpr = 'DATE_ADD(NOW(), INTERVAL 365 DAY)'; await queryInterface.sequelize.query(` INSERT INTO subjects (name, admin_user_id, expire_at, status, remark, created_at, updated_at) SELECT LEFT(CONCAT(COALESCE(NULLIF(u.nickname, ''), NULLIF(u.username, ''), CONCAT('用户', u.id)), ' 的主体'), 64), u.id, ${expireExpr}, 1, '升级时自动创建的历史主体', NOW(), NOW() FROM users u WHERE ( EXISTS (SELECT 1 FROM nvrs n WHERE n.user_id = u.id AND n.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM workstations w WHERE w.user_id = u.id AND w.deleted_at IS NULL) OR EXISTS (SELECT 1 FROM scanners s WHERE s.user_id = u.id AND s.deleted_at IS NULL) ) AND NOT EXISTS ( SELECT 1 FROM subjects s2 WHERE s2.admin_user_id = u.id AND s2.deleted_at IS NULL ) `); await queryInterface.sequelize.query(` INSERT INTO subject_members (subject_id, user_id, name, role, bound_at, status, created_at, updated_at) SELECT s.id, s.admin_user_id, LEFT(COALESCE(NULLIF(u.nickname, ''), NULLIF(u.username, ''), CONCAT('用户', u.id)), 32), 1, NOW(), 1, NOW(), NOW() FROM subjects s JOIN users u ON u.id = s.admin_user_id WHERE NOT EXISTS ( SELECT 1 FROM subject_members m WHERE m.subject_id = s.id AND m.user_id = s.admin_user_id ) `); const pairs = [ [ 'nvrs', 'user_id' ], [ 'workstations', 'user_id' ], [ 'scanners', 'user_id' ], ]; for (const [ table, column ] of pairs) { await queryInterface.sequelize.query(` UPDATE ${table} t JOIN subjects s ON s.admin_user_id = t.${column} AND s.deleted_at IS NULL SET t.subject_id = s.id WHERE t.subject_id IS NULL `); } await queryInterface.sequelize.query(` UPDATE cameras c JOIN nvrs n ON n.id = c.nvr_id SET c.subject_id = n.subject_id WHERE c.subject_id IS NULL AND n.subject_id IS NOT NULL `); await queryInterface.sequelize.query(` UPDATE scan_records r JOIN scanners s ON s.id = r.scanner_id SET r.subject_id = s.subject_id WHERE r.subject_id IS NULL AND s.subject_id IS NOT NULL `); await queryInterface.sequelize.query(` UPDATE scan_channels c JOIN scanners s ON s.id = c.scanner_id SET c.subject_id = s.subject_id WHERE c.subject_id IS NULL AND s.subject_id IS NOT NULL `); }, async down(queryInterface) { const targets = [ 'scanners', 'nvrs', 'cameras', 'workstations', 'scan_channels', 'scan_records' ]; for (const table of targets) { await queryInterface.removeIndex(table, `idx_${table}_subject`); await queryInterface.removeColumn(table, 'subject_id'); } await queryInterface.dropTable('subject_members'); await queryInterface.dropTable('subjects'); }, };