'use strict'; const crypto = require('crypto'); /** 登录码字符集(去掉容易看错的 0/O/1/I) */ const ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; /** * 生成一个工作台登录码(形如 `WSC-7K3M9QX2AB`) * * ⚠️ 这张码后来被**废弃**了(见 20261028121000-drop-workstation-login-code): * 扫码登入改走微信登录网关。这里保留一份自包含的生成逻辑, * 只是为了这个迁移能被完整重放(新库从零跑迁移时不会缺依赖)。 */ function generateLoginCode() { let out = ''; for (let i = 0; i < 10; i++) { out += ALPHABET[crypto.randomInt(ALPHABET.length)]; } return `WSC-${out}`; } /** 不活跃自动下线默认值:散单 30 分钟 */ const DEFAULT_IDLE_TIMEOUT_SEC = 30 * 60; /** 团购 1 小时 */ const GROUP_IDLE_TIMEOUT_SEC = 60 * 60; /** * 工作台登录相关字段 * * - `login_code`:现场贴的登录码(前缀 `WSC-`,建工作台时生成;重置后旧码立即失效) * - `last_active_at`:最后活跃时间(扫码上报时刷新),配合 `idle_timeout_sec` 做自动下线 * - `idle_timeout_sec`:多少秒不活跃自动下线该工作台所有在线成员 * 团购(ws_type=2)默认 3600 秒,散单默认 1800 秒 * * 已有工作台在这里回填登录码(唯一索引不能有 NULL 重复,必须逐条生成)。 */ module.exports = { async up(queryInterface, Sequelize) { const { STRING, INTEGER, DATE } = Sequelize; await queryInterface.addColumn('workstations', 'login_code', { type: STRING(64), allowNull: true, after: 'code', comment: '登录码(扫码登入本工作台,前缀 WSC-)', }); await queryInterface.addColumn('workstations', 'last_active_at', { type: DATE, allowNull: true, after: 'status', comment: '最后活跃时间(扫码上报时刷新)', }); await queryInterface.addColumn('workstations', 'idle_timeout_sec', { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: DEFAULT_IDLE_TIMEOUT_SEC, after: 'last_active_at', comment: '多少秒不活跃自动下线所有成员(团购 3600 / 散单 1800)', }); // 回填:历史工作台也要有登录码(唯一索引下不允许 NULL,也不允许重复) const rows = await queryInterface.sequelize.query( 'SELECT id, ws_type FROM workstations', { type: queryInterface.sequelize.QueryTypes.SELECT }, ); const used = new Set(); for (const row of rows) { let code = generateLoginCode(); while (used.has(code)) code = generateLoginCode(); used.add(code); await queryInterface.sequelize.query( 'UPDATE workstations SET login_code = ?, idle_timeout_sec = ? WHERE id = ?', { replacements: [ code, Number(row.ws_type) === 2 ? GROUP_IDLE_TIMEOUT_SEC : DEFAULT_IDLE_TIMEOUT_SEC, row.id, ], }, ); } await queryInterface.addIndex('workstations', [ 'login_code' ], { name: 'uk_workstations_login_code', unique: true, }); }, async down(queryInterface) { await queryInterface.removeIndex('workstations', 'uk_workstations_login_code'); await queryInterface.removeColumn('workstations', 'idle_timeout_sec'); await queryInterface.removeColumn('workstations', 'last_active_at'); await queryInterface.removeColumn('workstations', 'login_code'); }, };