'use strict'; const { Service } = require('egg'); const { Op } = require('sequelize'); /** 下线原因(写进 `workstation_login_records.logout_reason`) */ const LOGOUT_REASON = { /** 管理员在工作台成员列表手动下线 */ MANUAL: 'manual', /** 管理员一键下线该工作台所有成员 */ OFFLINE_ALL: 'offline_all', /** 旧版「重置登录码」留下的原因(登录码已废弃,仅历史记录里还会出现) */ RESET_CODE: 'reset_code', /** 长时间不活跃,定时任务自动下线 */ IDLE_TIMEOUT: 'idle_timeout', /** 同一个人再次扫码登录,旧的在线记录自动下线 */ RELOGIN: 'relogin', /** 工作台被删除 */ WORKSTATION_DELETED: 'workstation_deleted', }; /** 登录类型(`type`):预留给后续登录方式扩展,当前只有扫码登录 */ const LOGIN_TYPE = { SCAN: 1, }; /** 秒级精度(设备上报的扫码时间是秒级,库里 login_at 带毫秒,比较时统一取整秒) */ const SECOND = 1000; /** * 工作台成员登录记录 service * * 一句话:谁在什么时候登进了哪台工作台、什么时候下线,以及「某次扫码时谁在线」(运单回放定位打包人)。 * * 关键约定: * 1. 一行记录用 `status`(1 在线 / 0 下线)+ `logoutAt` 表达生命周期,**不删记录**(要能查历史); * 2. 判断「扫码那一刻谁在线」= `loginAt <= scanTime && (logoutAt == null || logoutAt >= scanTime)`, * 所以查询入口是 `workstationId` + 时间区间(表上有 `(workstation_id, login_at)` 索引); * 3. 自动下线只看「工作台最后活跃时间」,没有活跃时间时退化为「最晚一条在线记录的登录时间」, * 否则新建的工作台(从没上报过条码)永远不会被下线。 */ class WorkstationLoginService extends Service { get Record() { return this.app.model.WorkstationLoginRecord; } get Workstation() { return this.app.model.Workstation; } /** * 扫码登入工作台(网关回调确认了「谁」之后调,见 `service/wx_gateway.js#handleWorkstationLogin`) * * 名字规则:**是该主体的成员 → 记成员姓名(= 工号)**,否则记用户自己设置的昵称。 * * @param {object} params * @param {object} params.user 平台账号(网关 openid 反查出来的) * @param {object} params.workstation 工作台(Sequelize 实例) * @param {string} [params.ip] 登录 IP(网关回调没有真实客户端 IP,通常为空) * @return {Promise} { workstation, name, isMember, member, record } */ async loginByUser({ user, workstation, ip } = {}) { if (!user) this.ctx.throw(401, '缺少登录用户'); if (!workstation) this.ctx.throw(404, '工作台不存在或已被删除'); const subjectId = Number(workstation.subjectId); const state = await this.ctx.service.subjectState.get(subjectId); if (!state) this.ctx.throw(404, '工作台不存在或已被删除'); if (state.disabled) this.ctx.throw(403, '所属主体已被停用,请联系管理员'); if (state.expired) this.ctx.throw(403, `主体「${state.name}」使用期限已到,请联系管理员续期`); if (Number(workstation.status) !== 1) this.ctx.throw(403, '工作台已停用,请联系管理员'); const member = await this.app.model.SubjectMember.findOne({ where: { subjectId, userId: Number(user.id), status: 1 }, }); const name = member ? String(member.name || '').trim() : String(user.nickname || user.username || '').trim() || `用户${user.id}`; const now = new Date(); // 同一个人在同一台工作台只保留一条在线记录:重新扫码 = 旧记录下线 const replaced = await this.Record.update({ status: 0, logoutAt: now, logoutReason: LOGOUT_REASON.RELOGIN, }, { where: { workstationId: workstation.id, userId: Number(user.id), status: 1 } }); const record = await this.Record.create({ subjectId, workstationId: Number(workstation.id), userId: Number(user.id), memberId: member ? Number(member.id) : null, name, type: LOGIN_TYPE.SCAN, loginAt: now, status: 1, loginIp: ip ? String(ip).slice(0, 45) : null, }); // 有人登进来也算一次活跃,避免刚登录就被自动下线 await workstation.update({ lastActiveAt: now }); this.ctx.logger.info( '[workstation-login] 工作台 %s 登录:%s(%s)%s,旧在线记录下线 %d 条', workstation.code, name, user.id, member ? '(主体成员)' : '(非成员,记昵称)', Array.isArray(replaced) ? replaced[0] : 0, ); return { workstation: { id: Number(workstation.id), code: workstation.code, name: workstation.name, wsType: Number(workstation.wsType) === 2 ? 2 : 1, subjectId, subjectName: state.name, }, isMember: !!member, member: member ? { id: Number(member.id), name: member.name, role: Number(member.role) } : null, name, record: this.present(record), }; } /** * 成员列表(含历史) * * @param {object} params * @param {number} params.workstationId * @param {number} params.subjectId * @param {string} [params.status] 1 只看在线 / 0 只看已下线 / 不传 = 全部 * @param {string} [params.startTime] 登录时间起(含) * @param {string} [params.endTime] 登录时间止(含) * @param {number} [params.page] * @param {number} [params.pageSize] * @return {Promise} { list, total, page, pageSize, onlineCount } */ async list({ workstationId, subjectId, status, startTime, endTime, page = 1, pageSize = 20 } = {}) { const workstation = await this.ctx.service.workstation.findOwned(workstationId, subjectId); const size = Math.min(Number(pageSize) || 20, 100); const current = Math.max(Number(page) || 1, 1); const where = { workstationId: Number(workstation.id) }; if (status !== undefined && status !== '' && status !== null) { where.status = Number(status) === 1 ? 1 : 0; } // 时间段:按「登录时间」过滤(配合工作台 id 就能查某天谁在这台工作台上) const from = parseTime(startTime); const to = parseTime(endTime); if (from || to) { where.loginAt = {}; if (from) where.loginAt[Op.gte] = from; if (to) where.loginAt[Op.lte] = to; } const { rows, count } = await this.Record.findAndCountAll({ where, include: [{ model: this.app.model.User, as: 'user', required: false, attributes: [ 'id', 'username', 'nickname' ], }], order: [[ 'status', 'DESC' ], [ 'loginAt', 'DESC' ], [ 'id', 'DESC' ]], limit: size, offset: (current - 1) * size, }); const onlineCount = await this.Record.count({ where: { workstationId: Number(workstation.id), status: 1 }, }); return { list: rows.map(row => { const data = row.toJSON(); return Object.assign(this.present(row), { user: data.user ? { id: Number(data.user.id), username: data.user.username, nickname: data.user.nickname, } : null, }); }), total: count, page: current, pageSize: size, onlineCount, }; } /** * 手动下线某条在线记录(成员列表页的「下线」按钮) * * 幂等:已经下线的直接返回(`alreadyOffline: true`),不报错。 */ async offlineOne({ workstationId, subjectId, recordId, reason = LOGOUT_REASON.MANUAL } = {}) { const workstation = await this.ctx.service.workstation.findOwned(workstationId, subjectId); const record = await this.Record.findOne({ where: { id: Number(recordId), workstationId: Number(workstation.id) }, }); if (!record) this.ctx.throw(404, '登录记录不存在'); if (Number(record.status) !== 1) { return Object.assign(this.present(record), { alreadyOffline: true }); } const now = new Date(); await record.update({ status: 0, logoutAt: now, logoutReason: reason }); this.ctx.logger.info('[workstation-login] 手动下线:工作台 %s 记录 %s(%s)', workstation.code, record.id, record.name); return Object.assign(this.present(record), { alreadyOffline: false }); } /** * 下线某台工作台的全部在线成员 * * @param {number} workstationId * @param {string} reason 见 `LOGOUT_REASON` * @return {Promise} 受影响条数 */ async offlineAll(workstationId, reason) { const [ affected ] = await this.Record.update({ status: 0, logoutAt: new Date(), logoutReason: reason, }, { where: { workstationId: Number(workstationId), status: 1 } }); return Number(affected) || 0; } /** * 定时任务:扫描在线成员,按「工作台设置的不活跃秒数」批量下线 * * 判断基准 `idleBase`: * - 工作台有 `last_active_at` → 用它(扫码上报 / 有人登录都会刷新); * - 没有(新建后从没上报过)→ 用该工作台**最晚一条在线记录的登录时间**; * - 工作台已被删除 → 直接下线。 * * @return {Promise} { online, offline, workstations } */ async sweepIdle() { const rows = await this.Record.findAll({ where: { status: 1 }, attributes: [ 'id', 'workstationId', 'loginAt' ], order: [[ 'id', 'ASC' ]], }); if (!rows.length) return { online: 0, offline: 0, workstations: 0 }; // 按工作台聚合「最晚登录时间」 const latestLogin = new Map(); for (const row of rows) { const key = Number(row.workstationId); const at = new Date(row.loginAt).getTime(); if (!latestLogin.has(key) || at > latestLogin.get(key)) latestLogin.set(key, at); } const workstations = await this.Workstation.findAll({ where: { id: { [Op.in]: [ ...latestLogin.keys() ] } }, attributes: [ 'id', 'code', 'wsType', 'status', 'lastActiveAt', 'idleTimeoutSec' ], }); const byId = new Map(workstations.map(row => [ Number(row.id), row ])); const now = Date.now(); let offline = 0; let touched = 0; for (const [ workstationId, latest ] of latestLogin) { const workstation = byId.get(workstationId); if (!workstation) { // 工作台被删除:记录不能悬着,直接下线(历史仍然可查) offline += await this.offlineAll(workstationId, LOGOUT_REASON.WORKSTATION_DELETED); touched++; continue; } const timeoutSec = Number(workstation.idleTimeoutSec) > 0 ? Number(workstation.idleTimeoutSec) : (Number(workstation.wsType) === 2 ? 3600 : 1800); const idleBase = workstation.lastActiveAt ? new Date(workstation.lastActiveAt).getTime() : latest; if (now - idleBase < timeoutSec * 1000) continue; const affected = await this.offlineAll(workstationId, LOGOUT_REASON.IDLE_TIMEOUT); if (affected) { offline += affected; touched++; this.ctx.logger.info( '[workstation-login] 工作台 %s 超过 %d 秒无活跃,自动下线 %d 人', workstation.code, timeoutSec, affected, ); } } return { online: rows.length, offline, workstations: touched }; } /** * 批量取「这些扫码记录当时的在线成员」 * * @param {Array<{key:*, workstationId:number|string, scanTime:Date|string}>} items * @return {Promise>>} key 同入参的 `key` */ async packersMap(items) { const map = new Map(); const list = Array.isArray(items) ? items.filter(item => item && item.workstationId && item.scanTime) : []; if (!list.length) return map; const workstationIds = [ ...new Set(list.map(item => Number(item.workstationId))) ]; const times = list.map(item => new Date(item.scanTime).getTime()); // 多留 1 秒余量:设备上报的扫码时间是**秒级**,落在数据库里会被截断到整秒, // 不放大一点的话「登录与扫码同一秒」会被判成扫码早于登录而漏掉 const minTime = new Date(Math.min(...times) - SECOND); const maxTime = new Date(Math.max(...times) + SECOND); const rows = await this.Record.findAll({ where: { workstationId: { [Op.in]: workstationIds }, loginAt: { [Op.lte]: maxTime }, [Op.or]: [ { logoutAt: null }, { logoutAt: { [Op.gte]: minTime } }, ], }, attributes: [ 'id', 'subjectId', 'workstationId', 'userId', 'memberId', 'name', 'type', 'loginCode', 'loginAt', 'logoutAt', 'status', 'logoutReason', 'loginIp' ], order: [[ 'loginAt', 'ASC' ], [ 'id', 'ASC' ]], }); // 按工作台分组,减少逐条扫描量 const byWorkstation = new Map(); for (const row of rows) { const key = Number(row.workstationId); if (!byWorkstation.has(key)) byWorkstation.set(key, []); byWorkstation.get(key).push(row); } for (const item of list) { const candidates = byWorkstation.get(Number(item.workstationId)) || []; const at = new Date(item.scanTime).getTime(); map.set(item.key, candidates.filter(row => covers(row, at)).map(row => this.present(row))); } return map; } /** 统一输出(camelCase,前端/桌面端直接用) */ present(row) { const data = row && typeof row.toJSON === 'function' ? row.toJSON() : (row || {}); return { id: Number(data.id), subjectId: Number(data.subjectId), workstationId: Number(data.workstationId), userId: Number(data.userId), memberId: data.memberId ? Number(data.memberId) : null, name: data.name || '', type: Number(data.type) || LOGIN_TYPE.SCAN, loginCode: data.loginCode || null, loginAt: data.loginAt, logoutAt: data.logoutAt || null, status: Number(data.status), logoutReason: data.logoutReason || null, loginIp: data.loginIp || null, }; } } /** 时间参数解析:支持 `2026-10-24 12:00:00` / `2026/10/24 12:00` / 10 位或 13 位时间戳 */ function parseTime(value) { if (value === undefined || value === null || value === '') return null; if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value; const str = String(value).trim(); if (!str) return null; let date; if (/^\d{10}$/.test(str)) { date = new Date(Number(str) * 1000); } else if (/^\d{13}$/.test(str)) { date = new Date(Number(str)); } else { date = new Date(str.replace(/\//g, '-').replace(' ', 'T')); } return date && !Number.isNaN(date.getTime()) ? date : null; } /** 这条登录记录是否覆盖某个时间点(在线中 = 到当前时间为止) */ function covers(row, at) { const toSec = value => Math.floor(value / SECOND) * SECOND; const loginAt = toSec(new Date(row.loginAt).getTime()); const point = toSec(at); if (loginAt > point) return false; if (!row.logoutAt) return true; return toSec(new Date(row.logoutAt).getTime()) >= point; } module.exports = WorkstationLoginService;