feat(backend): 主体/工作站/摄像机/NVR/打包查询与扫码鉴权增强

This commit is contained in:
liufumingren 2026-10-19 22:04:03 +08:00
parent 77661b91b1
commit 881b8d52f5
43 changed files with 3734 additions and 87 deletions

View File

@ -0,0 +1,66 @@
'use strict';
const { Controller } = require('egg');
/**
* 成员绑定(手机扫码侧)
*
* 流程与扫码登录一个套路:
* 1. 电脑端 `POST /api/web/subjects/:id/members/:memberId/bind-code` 生成 6 位码 → 画二维码
* 2. 手机扫码打开前端 `/wechat?bind=<码>`
* 3. 手机侧轮询 `GET /api/subject/member-bind?code=`(公开)拿状态
* 4. 已登录的账号点「确认绑定」→ `POST /api/subject/member-bind/confirm`(要 user JWT)
* → 该账号被写进 `subject_members.user_id`,从此可以进入这个主体
*/
class MemberBindController extends Controller {
/** GET /api/subject/member-bind?code=ABC123 —— 绑定码状态(公开) */
async status() {
const { ctx } = this;
const code = String(ctx.query.code || '').trim();
if (!code) {
ctx.status = 422;
ctx.body = { ok: false, status: 'bad_format', message: '缺少绑定码' };
return;
}
if (!/^[0-9A-Z]{4,12}$/i.test(code)) {
ctx.status = 422;
ctx.body = { ok: false, status: 'bad_format', message: '绑定码格式不对' };
return;
}
const result = await ctx.service.subject.bindStatus(code);
ctx.status = result.status === 'expired' ? 410 : 200;
ctx.body = { ok: true, data: result };
}
/** POST /api/subject/member-bind/confirm —— body { code },把当前登录账号绑到该成员 */
async confirm() {
const { ctx } = this;
const body = ctx.request.body || {};
const code = String(body.code || ctx.query.code || '').trim();
if (!code) ctx.throw(422, '缺少绑定码');
const user = ctx.state.user;
const result = await ctx.service.subject.confirmBind(code, user.id);
if (!result.ok) {
const mapping = {
bad_param: 422,
expired: 410,
used: 410,
bound: 409,
joined: 409,
};
ctx.status = mapping[result.reason] || 400;
ctx.body = { ok: false, status: result.reason, message: result.message };
return;
}
ctx.logger.info('[subject] %s 扫码确认成为主体 %s 的成员「%s」',
user.username || user.id, result.subjectId, result.memberName);
ctx.body = { ok: true, data: result };
}
}
module.exports = MemberBindController;

View File

@ -11,18 +11,41 @@ const { Controller } = require('egg');
class WechatAuthController extends Controller {
/**
* GET /api/wechat/qrcode.svg?code=xxxxxx —— 登录码的二维码(SVG,**本地生成**,零外链)
* 内容就是本站地址 `/wechat?spm=1.0.<码>.1`(手机扫到后打开前端路由)
*
* - 默认:内容是本站在址 `/wechat?spm=1.0.<码>.1`(扫码登录)
* - `?mode=member`:内容是 `/wechat?bind=<码>`(主体成员绑定码,同一个扫码页、不同处理逻辑)
*/
async qrcode() {
const { ctx } = this;
const code = String(ctx.query.code || '');
const content = ctx.service.wechatLogin.qrContent({ code, origin: ctx.app.config.email.siteUrl || ctx.origin });
const origin = ctx.app.config.email.siteUrl || ctx.origin;
const content = String(ctx.query.mode || '') === 'member'
? `${String(origin).replace(/\/+$/, '')}/wechat?bind=${encodeURIComponent(code)}`
: ctx.service.wechatLogin.qrContent({ code, origin });
ctx.set('Cache-Control', 'no-store');
ctx.type = 'image/svg+xml; charset=utf-8';
ctx.body = ctx.service.wechatLogin.qrSvg(content);
}
/**
* GET /api/wechat/qrcode.gif?code=xxxxxx&mode=member —— 二维码的 **GIF** 版
*
* 桌面端(WPF)没法渲染 SVG,只能直接拉位图;内容和 `qrcode.svg` 完全一致。
*/
async qrcodeGif() {
const { ctx } = this;
const code = String(ctx.query.code || '');
const origin = ctx.app.config.email.siteUrl || ctx.origin;
const content = String(ctx.query.mode || '') === 'member'
? `${String(origin).replace(/\/+$/, '')}/wechat?bind=${encodeURIComponent(code)}`
: ctx.service.wechatLogin.qrContent({ code, origin });
ctx.set('Cache-Control', 'no-store');
ctx.type = 'image/gif';
ctx.body = ctx.service.wechatLogin.qrGif(content);
}
/**
* GET /api/wechat/login —— 扫码登录接口(前端 JS/SPA 用,不依赖页面渲染)
* - **不带参数**:生成一个 6 位串码(数字+字母,存 Redis)并返回二维码地址,前端拿去画二维码;

View File

@ -194,8 +194,11 @@ class DeviceController extends Controller {
// ③ 有人确认了 —— **这一步才注册/绑定**(归属就是确认登录的人),并换发长期 JWT
const user = result.user;
const merged = mergeInfo(info, await svc.takeDeviceInfo(code));
// 设备可以在发码时带上 `?subjectId=` 指定要进哪个主体(不传则用确认人可进入的第一个主体)
const wantedSubjectId = Number(ctx.query.subjectId || merged.subjectId || 0) || null;
const data = await ctx.service.scanner.loginByScan(Object.assign({}, merged, {
userId: user.id,
subjectId: wantedSubjectId,
ip: ctx.ip,
expiresIn: tokenDuration.seconds,
}));
@ -232,6 +235,28 @@ class DeviceController extends Controller {
},
};
}
/**
* POST /api/device/refresh —— 用刷新令牌换新的访问令牌(**无需访问令牌**)
*
* body: `{ refreshToken, sn? }`;也认 header `X-Refresh-Token`。
*
* 后台扫码服务在访问令牌快过期(或已 401)时调用,成功后:
* - 拿到新的长期 JWT(旧 JWT 的 jti 已轮换 → 立即失效)
* - 拿到新的刷新令牌(旧刷新令牌立即失效,必须覆盖保存)
* 响应:`{ ok:true, data:{ sn, token, tokenType, expiresIn, refreshToken, refreshExpiresIn, refreshExpiresAt } }`
*/
async refresh() {
const { ctx } = this;
const body = ctx.request.body || {};
const refreshToken = String(body.refreshToken || ctx.get('X-Refresh-Token') || '').trim();
const sn = body.sn || ctx.query.sn || null;
const data = await ctx.service.scanner.refreshToken({ refreshToken, sn, ip: ctx.ip });
ctx.logger.info('[device] %s 刷新令牌成功', data.sn);
ctx.body = { ok: true, data };
}
}
module.exports = DeviceController;

View File

@ -58,7 +58,8 @@ class ScanController extends Controller {
/**
* POST /api/scan/records —— 中控上报扫码结果(需长期 JWT)
* body: { records: [{ barcode, scanTime, channelId }] }
* 同一中控 + 通道 + 条码 + 扫描时间(秒) 重复上报只入库一次,不报错
* 同一中控 + 通道 + 条码 + 扫描时间(秒) 重复上报只入库一次;
* **同一运单号 24 小时内只保留一条**:扫描时间更新 → 覆盖时间与工作台快照;旧上报忽略,都不报错。
*/
async reportRecords() {
const { ctx } = this;

View File

@ -14,21 +14,32 @@ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
* 统一响应:成功 `{ ok:true, data }`;失败 `{ ok:false, status?, message }`。
*/
class WebAuthController extends Controller {
/** 签发令牌 + 返回脱敏用户(登录 / 注册成功后都走它) */
issue(user) {
/**
* 签发令牌 + 返回脱敏用户(登录 / 注册成功后都走它)
*
* `subjects` 带上当前账号可进入的主体列表(前端登录后直接拿它渲染切换器,不用再请求一次)
*/
async issue(user) {
const { ctx } = this;
let subjects = [];
try {
subjects = await ctx.service.subject.listForUser(user.id);
} catch (err) {
ctx.logger.warn('[web] 登录时读取主体列表失败: %s', err.message);
}
return {
token: ctx.service.jwt.signUser(user),
tokenType: 'Bearer',
expiresIn: ctx.app.config.jwt.userExpiresIn,
user,
subjects,
};
}
/**
* POST /api/web/auth/login
* body: `{ account, password }`(account 支持 用户名 / 手机号 / 邮箱)
* → `{ token, tokenType, expiresIn, user }`
* → `{ token, tokenType, expiresIn, user, subjects }`
*/
async login() {
const { ctx } = this;
@ -47,7 +58,7 @@ class WebAuthController extends Controller {
}
ctx.logger.info('[web] %s 登录成功(API)', user.username || account);
ctx.body = { ok: true, data: this.issue(user) };
ctx.body = { ok: true, data: await this.issue(user) };
}
/**
@ -112,7 +123,7 @@ class WebAuthController extends Controller {
// 注册成功才消费验证码(用户名/邮箱冲突时可改完重提,不用重新收码)
await ctx.service.verifyCode.consume('register', email);
ctx.logger.info('[web] %s 注册成功(API,id=%s)', username, user.id);
ctx.body = { ok: true, data: this.issue(user) };
ctx.body = { ok: true, data: await this.issue(user) };
} catch (err) {
// 唯一键冲突(409):翻成页面能直接显示的文案
if (err.status === 409) {
@ -144,7 +155,13 @@ class WebAuthController extends Controller {
if (user && Number(user.status) === 1) {
const origin = ctx.app.config.email.siteUrl || ctx.origin;
const result = await ctx.service.passwordReset.send(user, origin);
if (!result.ok) ctx.throw(500, result.message);
if (!result.ok) {
// 直接回状态码 + 原文(不走 ctx.throw:5xx 会被 error_handler 盖成「服务器内部错误」)
// 节流 → 429(前端把 message 展示给用户);Redis/发信异常 → 503
ctx.status = result.reason === 'throttled' ? 429 : 503;
ctx.body = { ok: false, status: result.reason || 'error', message: result.message };
return;
}
ctx.logger.info('[web] 已向 %s 发送重置密码链接', email);
ctx.body = {

View File

@ -0,0 +1,83 @@
'use strict';
const { Controller } = require('egg');
/** 路径参数转正整数,非法返回 null */
function toId(value) {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
}
/**
* web 用户端:**我的摄像头**(`/api/web/cameras`)
*
* 摄像头由「NVR + 通道」产生,归属看所属 NVR 的 user_id。
* 添加走 `/api/web/nvrs/:id/channels`(批量导入),这里只做列表 / 改名 / 启停 / 删除。
*/
class WebCameraController extends Controller {
/** GET /api/web/cameras?page=&pageSize=&nvrId=&keyword=&status= */
async index() {
const { ctx } = this;
const { page, pageSize, nvrId, keyword, status } = ctx.query;
const data = await ctx.service.camera.list({
page,
pageSize,
nvrId: nvrId ? Number(nvrId) : undefined,
keyword,
status,
subjectId: ctx.state.subjectId,
});
ctx.body = { ok: true, data };
}
/** GET /api/web/cameras/:id */
async show() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const camera = await ctx.service.camera.findOwned(id, ctx.state.subjectId);
ctx.body = { ok: true, data: camera.toJSON() };
}
/** PUT /api/web/cameras/:id —— 改名 / 启停 / 备注 / 是否带云台 */
async update() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { name, status, remark, hasPtz } = ctx.request.body || {};
const data = await ctx.service.camera.update(id, ctx.state.subjectId, { name, status, remark, hasPtz });
ctx.body = { ok: true, data: data.toJSON() };
}
/** DELETE /api/web/cameras/:id —— 软删除并解除工作台绑定 */
async destroy() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const data = await ctx.service.camera.remove(id, ctx.state.subjectId);
ctx.body = { ok: true, data };
}
/** POST /api/web/cameras/batch-delete —— { ids: number[] } 批量删除 */
async batchDestroy() {
const { ctx } = this;
const { ids } = ctx.request.body || {};
const data = await ctx.service.camera.batchRemove({ subjectId: ctx.state.subjectId, ids });
ctx.body = { ok: true, data };
}
/** GET /api/web/cameras/options —— 我的全部摄像头(工作台绑定选择器,带 boundWorkstation) */
async options() {
const { ctx } = this;
const list = await ctx.service.camera.optionsOfUser(ctx.state.subjectId);
ctx.body = { ok: true, data: { list } };
}
}
module.exports = WebCameraController;

View File

@ -9,27 +9,27 @@ function toId(value) {
}
/**
* web 用户端:**我自己的设备**(`/api/web/devices`)
* web 主体端:**当前主体的设备**(`/api/web/devices`)
*
* 鉴权:`middleware.apiAuth()`(header 里的 user JWT),用户 ID 一律取自令牌。
* 鉴权:`middleware.apiAuth()` + `middleware.subjectAuth()`,主体 id 取自 header `X-Subject-Id`。
* 与 `controller/internal/device.js` 的区别:那边是运维视角(可看/可管**所有人**的设备),
* 这边只能看/动自己的 —— 不属于自己的设备直接 404(不暴露别人有哪些设备)。
* 这边只能看/动本主体的 —— 不属于本主体的一律 404(不暴露其他主体有哪些设备)。
*/
class WebDeviceController extends Controller {
/** 取「我的设备」;不是自己的(或不存在)一律 404 */
/** 取「本主体的设备」;不是本主体的(或不存在)一律 404 */
async own(rawId) {
const { ctx } = this;
const id = toId(rawId);
if (!id) ctx.throw(400, 'id 必须是正整数');
const data = await ctx.service.scanner.findById(id);
if (!data || Number(data.userId) !== Number(ctx.state.user.id)) {
ctx.throw(404, '设备不存在或不属于当前账号');
if (!data || Number(data.subjectId) !== Number(ctx.state.subjectId)) {
ctx.throw(404, '设备不存在或不属于当前主体');
}
return data;
}
/** GET /api/web/devices?page=&pageSize=&keyword=&status= —— 我的设备列表 */
/** GET /api/web/devices?page=&pageSize=&keyword=&status= —— 本主体设备列表 */
async index() {
const { ctx } = this;
const { page, pageSize, keyword, status } = ctx.query;
@ -38,8 +38,8 @@ class WebDeviceController extends Controller {
pageSize,
keyword,
status,
// ⚠️ 强制按当前用户过滤,忽略前端传的 userId
userId: ctx.state.user.id,
// ⚠️ 强制按当前主体过滤,忽略前端传的 subjectId
subjectId: ctx.state.subjectId,
});
ctx.body = { ok: true, data };
}
@ -50,6 +50,60 @@ class WebDeviceController extends Controller {
ctx.body = { ok: true, data: await this.own(ctx.params.id) };
}
/**
* GET /api/web/devices/active —— 本主体当前已绑定的设备
*
* 桌面端「开启设备服务」前用它检查:已有设备 -> 提示「开启后会踢掉它」。
*/
async active() {
const { ctx } = this;
const data = await ctx.service.scanner.list({
page: 1,
pageSize: 100,
subjectId: ctx.state.subjectId,
});
ctx.body = { ok: true, data };
}
/**
* POST /api/web/devices/activate —— 桌面端开启设备服务(**仅主体管理员**)
*
* body: `{ sn?, name?, vendor?, model? }`
* → `{ device, token, tokenType, expiresIn, kicked: [{ id, sn, name }] }`
*
* 规则:**一个主体只允许一台设备在线**,开启时同主体其他设备会被踢下线(旧令牌 401)。
*/
async activate() {
const { ctx } = this;
const { sn, name, vendor, model } = ctx.request.body || {};
// 只有主体管理员能开设备服务
await ctx.service.subject.ensureAdmin(ctx.state.subjectId, ctx.state.user.id);
const data = await ctx.service.scanner.activateForSubject({
subjectId: ctx.state.subjectId,
userId: ctx.state.user.id,
sn,
name,
vendor,
model,
});
ctx.logger.info('[web] 用户 %s 在主体 %s 开启设备服务 %s(踢下线 %d 台)',
ctx.state.user.id, ctx.state.subjectId, data.sn, data.kicked.length);
ctx.body = { ok: true, data };
}
/** POST /api/web/devices/:id/logout —— 关闭设备服务(让该设备令牌立即失效) */
async logout() {
const { ctx } = this;
const device = await this.own(ctx.params.id);
await ctx.service.scanner.revokeToken(device.id);
ctx.logger.info('[web] 用户 %s 在主体 %s 关闭设备服务 %s', ctx.state.user.id, ctx.state.subjectId, device.sn);
ctx.body = { ok: true, data: { id: device.id } };
}
/** GET /api/web/devices/:id/channels —— 该设备(中控)下已登记的通道 */
async channels() {
const { ctx } = this;
@ -64,17 +118,17 @@ class WebDeviceController extends Controller {
const device = await this.own(ctx.params.id);
const data = await ctx.service.scanner.unbind({ scannerId: device.id });
ctx.logger.info('[web] 用户 %s 解绑了设备 %s', ctx.state.user.id, device.sn);
ctx.logger.info('[web] 用户 %s 在主体 %s 解绑了设备 %s', ctx.state.user.id, ctx.state.subjectId, device.sn);
ctx.body = { ok: true, data };
}
/** DELETE /api/web/devices/:id —— 删除(软删除)自己的设备 */
/** DELETE /api/web/devices/:id —— 删除(软删除)本主体的设备 */
async destroy() {
const { ctx } = this;
const device = await this.own(ctx.params.id);
await ctx.service.scanner.remove(device.id);
ctx.logger.info('[web] 用户 %s 删除了设备 %s', ctx.state.user.id, device.sn);
ctx.logger.info('[web] 用户 %s 在主体 %s 删除了设备 %s', ctx.state.user.id, ctx.state.subjectId, device.sn);
ctx.body = { ok: true, data: { id: device.id } };
}
}

View File

@ -0,0 +1,162 @@
'use strict';
const { Controller } = require('egg');
/** 路径参数转正整数,非法返回 null */
function toId(value) {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
}
/**
* web 用户端:**我的 NVR**(`/api/web/nvrs`)
*
* 拉取通道是由**前端**发起的两步:
* 1. 页面直接调本机软件 `POST http://localhost:17300/api/hik/channels`(带 host/port/user/password)
* 2. 用户勾选通道后,把结果 POST 到 `/api/web/nvrs/:id/channels` 落库
* 后端服务器**不接触设备**(设备在用户内网)。
*/
class WebNvrController extends Controller {
async index() {
const { ctx } = this;
const { page, pageSize, keyword, status } = ctx.query;
const data = await ctx.service.nvr.list({
page,
pageSize,
keyword,
status,
subjectId: ctx.state.subjectId,
});
ctx.body = { ok: true, data };
}
async show() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
ctx.body = { ok: true, data: await ctx.service.nvr.findOwned(id, ctx.state.subjectId) };
}
/**
* GET /api/web/nvrs/:id/credential —— 拉取通道用的登录凭据
*
* 密码同时存在库里(密文)与前端(下面这步返回的明文),
* 前端拿到后立刻转给本机软件,不再回存到页面状态里。
*/
async credential() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const data = await ctx.service.nvr.credentialOf(id, ctx.state.subjectId);
ctx.logger.info('[web] 主体 %s 读取 NVR %s 登录凭据(拉取通道)', ctx.state.subjectId, id);
ctx.body = { ok: true, data };
}
/** POST /api/web/nvrs —— 新增(同 host+port+username 已存在时更新) */
async create() {
const { ctx } = this;
const { name, host, port, username, user, password, serialNumber, deviceModel, remark } = ctx.request.body || {};
const data = await ctx.service.nvr.create({
subjectId: ctx.state.subjectId,
userId: ctx.state.user.id,
name,
host,
port,
username: username || user,
password,
serialNumber,
deviceModel,
remark,
});
ctx.logger.info('[web] 主体 %s 新增/更新 NVR %s', ctx.state.subjectId, data.id);
ctx.status = 201;
ctx.body = { ok: true, data };
}
/** PUT /api/web/nvrs/:id */
async update() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { name, host, port, username, user, password, remark, status } = ctx.request.body || {};
const data = await ctx.service.nvr.update(id, ctx.state.subjectId, {
name,
host,
port,
username: username || user,
password,
remark,
status,
});
ctx.body = { ok: true, data };
}
/** DELETE /api/web/nvrs/:id —— 连带删除其下摄像头并解除工作台绑定 */
async destroy() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const data = await ctx.service.nvr.remove(id, ctx.state.subjectId);
ctx.body = { ok: true, data };
}
/** GET /api/web/nvrs/:id/channels —— 该 NVR 已导入的摄像头 */
async cameras() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const list = await ctx.service.camera.listByNvr(id, ctx.state.subjectId);
ctx.body = { ok: true, data: { nvrId: id, list } };
}
/**
* POST /api/web/nvrs/:id/channels —— 导入(勾选)通道为摄像头
*
* body: { serialNumber?, deviceModel?, channels: [{ channel, type, name?, ip?, port?, enabled? }] }
*/
async syncChannels() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { serialNumber, deviceModel, channels } = ctx.request.body || {};
if (!Array.isArray(channels) || channels.length === 0) {
await ctx.service.nvr.saveSyncResult(id, ctx.state.subjectId, {
serialNumber,
deviceModel,
error: '未选择任何通道',
});
ctx.throw(422, 'channels 不能为空');
}
const data = await ctx.service.camera.batchCreate({
subjectId: ctx.state.subjectId,
nvrId: id,
channels,
});
if (serialNumber !== undefined || deviceModel !== undefined) {
await ctx.service.nvr.saveSyncResult(id, ctx.state.subjectId, {
serialNumber,
deviceModel,
channelCount: data.list.length,
});
}
ctx.logger.info('[web] 主体 %s 导入 NVR %s 的通道 %d 个(新增 %d / 更新 %d)',
ctx.state.subjectId, id, channels.length, data.created, data.updated);
ctx.body = { ok: true, data };
}
}
module.exports = WebNvrController;

View File

@ -0,0 +1,34 @@
'use strict';
const { Controller } = require('egg');
/**
* web 主体端:**运单回放查询**(`GET /api/web/pack-query?code=xxx`)
*
* 给一个运单号,返回:
* - 这个运单在本主体下的所有扫码记录(可能被扫了多次)
* - 每条记录当时的**工作台快照**(录像机 / 摄像头 / 布局 / 录制范围)
* - 每条记录的**回放计划**(拉哪段时间、哪些流)
* - 拍平去重后的 `streams`(桌面端一次拿全,不用二次查询)
*
* 鉴权:`apiAuth` + `subjectAuth`,**范围限定当前主体**(别的主体的运单查不到)。
*/
class WebPackController extends Controller {
/**
* GET /api/web/pack-query?code=运单号
*/
async query() {
const { ctx } = this;
const code = String(ctx.query.code || ctx.query.barcode || '').trim();
if (!code) ctx.throw(422, '缺少运单号(?code=)');
const data = await ctx.service.pack.query({
subjectId: ctx.state.subjectId,
code,
});
ctx.body = { ok: true, data };
}
}
module.exports = WebPackController;

View File

@ -3,32 +3,33 @@
const { Controller } = require('egg');
/**
* web 用户端:**我自己设备的扫码记录**(`/api/web/records`)
* web 主体端:**当前主体的扫码记录**(`/api/web/records`)
*
* 鉴权:`middleware.apiAuth()`;范围限定为「当前用户名下的设备」——
* 先取我的设备 id 列表,再拿它去过滤记录(`service.scan.listRecords({ scannerIds })`)。
* 鉴权:`middleware.apiAuth()` + `middleware.subjectAuth()`;范围限定为「当前主体」,
* 传了 `deviceId` 时还要校验该设备属于当前主体。
*/
class WebRecordController extends Controller {
/**
* GET /api/web/records
* query: `?page=&pageSize=&deviceId=&channelId=&barcode=&startTime=&endTime=`
* - `deviceId` 只能填自己名下的设备(否则 404);不填 = 所有设备
* - `deviceId` 只能填当前主体下的设备(否则 404);不填 = 所有设备
* - `startTime` / `endTime` 支持 `2026-10-16 12:00:00`、10/13 位时间戳
*/
async index() {
const { ctx } = this;
const { page, pageSize, deviceId, channelId, barcode, startTime, endTime } = ctx.query;
const subjectId = ctx.state.subjectId;
const ids = await ctx.service.scanner.idsOfUser(ctx.state.user.id);
const ids = await ctx.service.scanner.idsOfSubject(subjectId);
let scannerIds = ids;
if (deviceId) {
const id = Number(deviceId);
if (!ids.includes(id)) ctx.throw(404, '设备不存在或不属于当前账号');
if (!ids.includes(id)) ctx.throw(404, '设备不存在或不属于当前主体');
scannerIds = [ id ];
}
const data = await ctx.service.scan.listRecords({
page, pageSize, scannerIds, channelId, barcode, startTime, endTime,
page, pageSize, subjectId, scannerIds, channelId, barcode, startTime, endTime,
});
ctx.body = {

View File

@ -3,23 +3,22 @@
const { Controller } = require('egg');
/**
* web 用户端:首页统计(`/api/web/stats`)
* web 主体端:首页统计(`/api/web/stats`)
*
* 只统计**当前用户名下**的数据(设备数 / 通道数 / 扫码记录数 + 最近一条扫码记录),
* 只统计**当前主体**的数据(设备数 / 通道数 / 扫码记录数 + 最近一条扫码记录),
* 与运维视角的统计(`service.user.count()` 那种全站数字)区分开。
*/
class WebStatsController extends Controller {
/** GET /api/web/stats */
/** GET /api/web/stats(需要 apiAuth + subjectAuth) */
async index() {
const { ctx } = this;
const userId = ctx.state.user.id;
const ids = await ctx.service.scanner.idsOfUser(userId);
const subjectId = ctx.state.subjectId;
const [ deviceCount, channelCount, recordCount, latest ] = await Promise.all([
ctx.service.scanner.count({ userId }),
ctx.service.scan.countChannels({ scannerIds: ids }),
ctx.service.scan.countRecords({ scannerIds: ids }),
ctx.service.scan.listRecords({ scannerIds: ids, page: 1, pageSize: 1 }),
ctx.service.scanner.count({ subjectId }),
ctx.service.scan.countChannels({ subjectId }),
ctx.service.scan.countRecords({ subjectId }),
ctx.service.scan.listRecords({ subjectId, page: 1, pageSize: 1 }),
]);
const row = latest.list[0] || null;

View File

@ -0,0 +1,136 @@
'use strict';
const { Controller } = require('egg');
/** 路径参数转正整数,非法返回 null */
function toId(value) {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
}
/**
* web 主体端:主体与成员管理(`/api/web/subjects`)
*
* 鉴权:`middleware.apiAuth()`(只认 header 令牌)。
* **这些接口不需要 `X-Subject-Id`**:主体 id 在路径里,服务层再校验「当前用户是不是这个主体的成员」。
*
* 关键规则:
* - 创建主体:管理员 = 创建人,使用期限默认赠送 7 天(`config.subject.trialDays`)
* - 主体列表:只返回「我是成员」的主体(含角色、成员数、是否过期)
* - 成员:可按姓名快速创建(尚未绑定账号),再用「绑定码」扫码绑定
*/
class WebSubjectController extends Controller {
/** GET /api/web/subjects —— 我可进入的主体列表 */
async index() {
const { ctx } = this;
const list = await ctx.service.subject.listForUser(ctx.state.user.id);
ctx.body = { ok: true, data: { list, trialDays: ctx.service.subject.trialDays } };
}
/** POST /api/web/subjects —— { name, days?, remark? } */
async create() {
const { ctx } = this;
const { name, days, remark } = ctx.request.body || {};
const data = await ctx.service.subject.create({
userId: ctx.state.user.id,
name,
days,
remark,
});
ctx.status = 201;
ctx.body = { ok: true, data };
}
/** GET /api/web/subjects/:id —— 主体详情(含我的角色) */
async show() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { subject, member } = await ctx.service.subject.findForUser(id, ctx.state.user.id);
const memberCount = await ctx.service.subject
.listForUser(ctx.state.user.id)
.then(list => (list.find(item => Number(item.id) === id) || {}).memberCount || 0);
ctx.body = {
ok: true,
data: Object.assign(ctx.service.subject.present(subject), {
role: Number(member.role),
memberName: member.name,
memberCount,
}),
};
}
/** PUT /api/web/subjects/:id —— { name?, remark?, extendDays? }(仅管理员) */
async update() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { name, remark, extendDays } = ctx.request.body || {};
const data = await ctx.service.subject.update(id, ctx.state.user.id, { name, remark, extendDays });
ctx.body = { ok: true, data };
}
/** GET /api/web/subjects/:id/members —— 成员列表 */
async members() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const list = await ctx.service.subject.members(id, ctx.state.user.id);
ctx.body = { ok: true, data: { subjectId: id, list } };
}
/** POST /api/web/subjects/:id/members —— { name } 按姓名快速添加成员 */
async addMember() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { name, role } = ctx.request.body || {};
const data = await ctx.service.subject.addMember({
subjectId: id,
userId: ctx.state.user.id,
name,
role,
});
ctx.status = 201;
ctx.body = { ok: true, data };
}
/** DELETE /api/web/subjects/:id/members/:memberId */
async removeMember() {
const { ctx } = this;
const id = toId(ctx.params.id);
const memberId = toId(ctx.params.memberId);
if (!id || !memberId) ctx.throw(400, 'id 必须是正整数');
const data = await ctx.service.subject.removeMember({
subjectId: id,
operatorUserId: ctx.state.user.id,
memberId,
});
ctx.body = { ok: true, data };
}
/** POST /api/web/subjects/:id/members/:memberId/bind-code —— 生成成员绑定码 */
async memberBindCode() {
const { ctx } = this;
const id = toId(ctx.params.id);
const memberId = toId(ctx.params.memberId);
if (!id || !memberId) ctx.throw(400, 'id 必须是正整数');
const data = await ctx.service.subject.createBindCode({
subjectId: id,
memberId,
operatorUserId: ctx.state.user.id,
});
ctx.body = { ok: true, data };
}
}
module.exports = WebSubjectController;

View File

@ -31,12 +31,14 @@ class WebTestController extends Controller {
firmware: body.firmware,
ip: ctx.ip,
userId: ctx.state.user.id,
subjectId: ctx.state.subjectId,
expiresIn,
});
// 再查一次,拿到带绑定用户信息的完整数据
const detail = await ctx.service.scanner.findById(created.id);
ctx.logger.info('[web-test] 模拟设备扫码登录: %s(确认人 %s)', created.sn, ctx.state.user.id);
ctx.logger.info('[web-test] 模拟设备扫码登录: %s(确认人 %s,主体 %s)',
created.sn, ctx.state.user.id, ctx.state.subjectId);
ctx.body = {
ok: true,

View File

@ -0,0 +1,190 @@
'use strict';
const { Controller } = require('egg');
/** 路径参数转正整数,非法返回 null */
function toId(value) {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
}
/**
* web 用户端:**我的工作台**(`/api/web/workstations`)
*
* 一个工作台可绑定多个摄像头 + 多个扫码通道:
* - `POST /:id/cameras` { cameraIds: number[] } 追加绑定
* - `DELETE /:id/cameras/:cameraId` 解绑
* - `POST /:id/scan-channels` { items: [{ scannerId, channelId, channelName? }] } 追加绑定
* - `DELETE /:id/scan-channels/:linkId` 解绑(按绑定记录 id)
* - `GET /api/web/workstation-scan-channels` 可绑定通道选择器
*/
class WebWorkstationController extends Controller {
/** GET /api/web/workstations?page=&pageSize=&keyword=&status=&wsType= */
async index() {
const { ctx } = this;
const { page, pageSize, keyword, status, wsType } = ctx.query;
const data = await ctx.service.workstation.list({
page,
pageSize,
keyword,
status,
wsType,
subjectId: ctx.state.subjectId,
});
ctx.body = { ok: true, data };
}
/** GET /api/web/workstations/:id —— 详情(含已绑摄像头 / 扫码通道) */
async show() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
ctx.body = { ok: true, data: await ctx.service.workstation.detail(id, ctx.state.subjectId) };
}
/** POST /api/web/workstations —— { name?, wsType?, recordBeforeSec?, recordAfterSec?, recordMaxSec?, remark? } */
async create() {
const { ctx } = this;
const { code, name, wsType, recordBeforeSec, recordAfterSec, recordMaxSec, remark } = ctx.request.body || {};
const data = await ctx.service.workstation.create({
subjectId: ctx.state.subjectId,
userId: ctx.state.user.id,
code,
name,
wsType,
recordBeforeSec,
recordAfterSec,
recordMaxSec,
remark,
});
ctx.status = 201;
ctx.body = { ok: true, data };
}
/** PUT /api/web/workstations/:id */
async update() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { name, wsType, recordBeforeSec, recordAfterSec, recordMaxSec, remark, status } = ctx.request.body || {};
const data = await ctx.service.workstation.update(id, ctx.state.subjectId, {
name, wsType, recordBeforeSec, recordAfterSec, recordMaxSec, remark, status,
});
ctx.body = { ok: true, data };
}
/** DELETE /api/web/workstations/:id */
async destroy() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const data = await ctx.service.workstation.remove(id, ctx.state.subjectId);
ctx.body = { ok: true, data };
}
/** POST /api/web/workstations/:id/cameras —— { cameraIds: [] } 追加绑定 */
async bindCameras() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { cameraIds } = ctx.request.body || {};
const data = await ctx.service.workstation.bindCameras({
workstationId: id,
subjectId: ctx.state.subjectId,
cameraIds,
});
ctx.body = { ok: true, data };
}
/** DELETE /api/web/workstations/:id/cameras/:cameraId */
async unbindCamera() {
const { ctx } = this;
const id = toId(ctx.params.id);
const cameraId = toId(ctx.params.cameraId);
if (!id || !cameraId) ctx.throw(400, 'id / cameraId 必须是正整数');
const data = await ctx.service.workstation.unbindCamera({
workstationId: id,
subjectId: ctx.state.subjectId,
cameraId,
});
ctx.body = { ok: true, data };
}
/**
* PUT /api/web/workstations/:id/cameras/:cameraId/layout
* body: { x?, y?, width?, height?, streamType?, zIndex? }
*
* 合成画面里这块摄像头的矩形(像素,相对 1920×1080 画布)与取流方式。
*/
async updateCameraLayout() {
const { ctx } = this;
const id = toId(ctx.params.id);
const cameraId = toId(ctx.params.cameraId);
if (!id || !cameraId) ctx.throw(400, 'id / cameraId 必须是正整数');
const { x, y, width, height, streamType, zIndex } = ctx.request.body || {};
const data = await ctx.service.workstation.updateCameraLayout({
workstationId: id,
subjectId: ctx.state.subjectId,
cameraId,
patch: { x, y, width, height, streamType, zIndex },
});
ctx.body = { ok: true, data };
}
/** POST /api/web/workstations/:id/scan-channels —— { items: [{ scannerId, channelId, channelName? }] } */
async bindScanChannels() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { items } = ctx.request.body || {};
const data = await ctx.service.workstation.bindScanChannels({
workstationId: id,
subjectId: ctx.state.subjectId,
items,
});
ctx.body = { ok: true, data };
}
/** DELETE /api/web/workstations/:id/scan-channels/:linkId */
async unbindScanChannel() {
const { ctx } = this;
const id = toId(ctx.params.id);
const linkId = toId(ctx.params.linkId);
if (!id || !linkId) ctx.throw(400, 'id / linkId 必须是正整数');
const data = await ctx.service.workstation.unbindScanChannel({
workstationId: id,
subjectId: ctx.state.subjectId,
linkId,
});
ctx.body = { ok: true, data };
}
/** GET /api/web/workstation-scan-channels?keyword= —— 当前用户可绑定的扫码通道 */
async availableScanChannels() {
const { ctx } = this;
const list = await ctx.service.workstation.availableScanChannels({
subjectId: ctx.state.subjectId,
keyword: ctx.query.keyword,
});
ctx.body = { ok: true, data: { list } };
}
}
module.exports = WebWorkstationController;

View File

@ -0,0 +1,86 @@
'use strict';
/**
* 工作台快照(写进 `scan_records.workstation_snapshot`)
*
* 一句话:把扫码那一刻的「工作台 + 录像机 + 摄像头 + 画布布局 + 录制范围」冻成一份 JSON,
* 以后工作台改过/删了,历史运单照样能按**当时**的配置去拉回放。
*
* 为什么单独放一层(不在 service 里):
* - `service/pack` 入库时要用它;`scripts/backfill-snapshot.js` 补历史数据也要用它 ——
* 两边必须是同一份逻辑,否则补出来的快照和实时写入的结构会不一致。
*
* ⚠️ **不含录像机密码**:密码只在本地软件真正登录 NVR 时按需取(本地软件持有用户令牌),
* 后端不把密钥塞进业务数据里。
*/
/** 快照版本(结构变了要升,方便前端/桌面端兼容旧数据) */
const SNAPSHOT_VERSION = 1;
function asInt(value, fallback) {
const num = Number(value);
return Number.isFinite(num) ? num : fallback;
}
/**
* 把一个工作台(含摄像头绑定)压成快照对象
*
* @param {object} workstation 工作台(`cameraLinks[].camera.nvr` 是 sequelize 实例或普通对象都行)
* @param {{channelId?:string, channelName?:string}} [link] 绑定的扫码通道
* @return {object|null} 没有工作台时返回 null
*/
function buildSnapshot(workstation, link) {
if (!workstation) return null;
const cameras = (workstation.cameraLinks || [])
.filter(item => item && item.camera)
.map(item => {
const camera = item.camera;
const nvr = camera.nvr || {};
return {
cameraId: Number(camera.id),
cameraName: camera.name || camera.channelName || `通道${camera.channelNo}`,
channelNo: Number(camera.channelNo) || 0,
streamType: asInt(item.streamType, 0),
nvrId: Number(camera.nvrId) || 0,
nvrName: nvr.name || '',
nvrHost: nvr.host || '',
nvrPort: asInt(nvr.port, 8000),
nvrUsername: nvr.username || 'admin',
layout: {
x: asInt(item.x, 0),
y: asInt(item.y, 0),
width: asInt(item.width, 0),
height: asInt(item.height, 0),
zIndex: asInt(item.zIndex, 0),
sortNo: asInt(item.sortNo, 0),
},
};
})
.sort((a, b) => a.layout.sortNo - b.layout.sortNo || a.cameraId - b.cameraId);
return {
v: SNAPSHOT_VERSION,
capturedAt: new Date(),
channelId: link ? link.channelId : '',
channelName: link ? link.channelName || '' : '',
workstation: {
id: Number(workstation.id),
code: workstation.code,
name: workstation.name || '',
wsType: asInt(workstation.wsType, 1),
recordBeforeSec: asInt(workstation.recordBeforeSec, 60),
recordAfterSec: asInt(workstation.recordAfterSec, 60),
recordMaxSec: asInt(workstation.recordMaxSec, 240),
canvasWidth: asInt(workstation.canvasWidth, 1920),
canvasHeight: asInt(workstation.canvasHeight, 1080),
},
cameras,
};
}
module.exports = {
SNAPSHOT_VERSION,
asInt,
buildSnapshot,
};

View File

@ -39,11 +39,19 @@ module.exports = () => {
ctx.body = { ok: false, status: 'forbidden', message: '账号已被禁用' };
return;
}
// 改密 / 重置密码之后,签发时间更早的旧令牌立即失效(JWT 是无状态的,靠这个时间戳收回)
if (ctx.service.user.isTokenStale(user, payload.iat)) {
ctx.status = 401;
ctx.body = { ok: false, status: 'password_changed', message: '密码已修改,请重新登录' };
return;
}
// 注意:**不碰 session/cookie**,接口鉴权完全基于这一次请求的 header
// 注意:**不碰 session/cookie**,接口鉴权完全基于这一次请求的 header;passwordChangedAt 只内部用,不外传
const safeUser = Object.assign({}, user);
delete safeUser.passwordChangedAt;
ctx.locals = ctx.locals || {};
ctx.locals.user = user;
ctx.state.user = user;
ctx.locals.user = safeUser;
ctx.state.user = safeUser;
await next();
};
};

View File

@ -58,6 +58,12 @@ module.exports = () => {
ctx.body = { ok: false, status: 'forbidden', message: '账号已被禁用' };
return;
}
// 改密 / 重置密码之后,签发时间更早的旧令牌立即失效(与 api_auth 同一套规则)
if (ctx.service.user.isTokenStale(user, payload.iat)) {
ctx.status = 401;
ctx.body = { ok: false, status: 'password_changed', message: '密码已修改,请重新登录' };
return;
}
ctx.state.internal = { via: 'user', user };
ctx.locals = ctx.locals || {};

View File

@ -0,0 +1,95 @@
'use strict';
/**
* 主体上下文(**必须在 apiAuth 之后**)
*
* 用法:`router.get('/api/web/cameras', apiAuth, subjectAuth, controller...)`
*
* 取值顺序:`X-Subject-Id` header > `?subjectId=` > body.subjectId
* (前端 SPA 统一走 header,见 `frontend/src/api/client.ts`)
*
* 通过后写入:
* - `ctx.state.subjectId` / `ctx.locals.subjectId`
* - `ctx.state.subject` / `ctx.locals.subject`(主体实例)
* - `ctx.state.subjectMember`(当前用户在该主体里的成员记录,含姓名 / 角色)
*
* 失败:
* - 缺参数 → 400 `{ status:'subject_required' }`(前端据此提示「请先创建/选择主体」)
* - 不是成员 / 主体不存在 → 404
* - 主体被停用 → 403 `subject_disabled`
* - 主体已过期 → 403 `subject_expired`(带 expireAt,前端据此提示续期)
*/
module.exports = () => {
return async function subjectAuth(ctx, next) {
const raw = pickSubjectId(ctx);
if (!raw) {
ctx.status = 400;
ctx.body = {
ok: false,
status: 'subject_required',
message: '缺少主体 id(请在 header 里带 X-Subject-Id)',
};
return;
}
const subjectId = Number(raw);
if (!Number.isInteger(subjectId) || subjectId <= 0) {
ctx.status = 400;
ctx.body = { ok: false, status: 'subject_required', message: '主体 id 不合法' };
return;
}
const { subject, member } = await ctx.service.subject.findForUser(subjectId, ctx.state.user.id);
if (Number(subject.status) !== 1) {
ctx.status = 403;
ctx.body = { ok: false, status: 'subject_disabled', message: '主体已被停用,请联系管理员' };
return;
}
if (ctx.service.subject.isExpired(subject)) {
ctx.status = 403;
ctx.body = {
ok: false,
status: 'subject_expired',
message: `主体「${subject.name}」使用期限已到(${formatDate(subject.expireAt)}),请联系管理员续期`,
expireAt: subject.expireAt,
};
return;
}
ctx.locals = ctx.locals || {};
ctx.locals.subjectId = subjectId;
ctx.locals.subject = subject;
ctx.locals.subjectMember = member;
ctx.state.subjectId = subjectId;
ctx.state.subject = subject;
ctx.state.subjectMember = member;
await next();
};
};
/** 从 header / query / body 里取主体 id(前端统一用 header) */
function pickSubjectId(ctx) {
const fromHeader = String(ctx.get('x-subject-id') || '').trim();
if (fromHeader) return fromHeader;
const fromQuery = ctx.query && ctx.query.subjectId;
if (fromQuery !== undefined && fromQuery !== null && String(fromQuery).trim() !== '') {
return String(fromQuery).trim();
}
const body = ctx.request && ctx.request.body;
if (body && body.subjectId !== undefined && body.subjectId !== null && String(body.subjectId).trim() !== '') {
return String(body.subjectId).trim();
}
return '';
}
/** yyyy-MM-dd HH:mm(服务器本地时间,仅用于提示文案) */
function formatDate(value) {
if (!value) return '';
const date = new Date(value);
const pad = num => String(num).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

View File

@ -0,0 +1,40 @@
'use strict';
/**
* 摄像头(NVR 通道)表模型(cameras)
*
* 一条记录 = 某台 NVR 上的一个通道。唯一键 `(nvr_id, channel_no)`:
* 同一台 NVR 重复导入同一个通道时做「更新/复活」,不会产生第二条。
*
* `ip` / `port` 是该数字通道对应的前端设备(可能是 ONVIF 摄像机),做展示与排障用。
*/
module.exports = (app) => {
const { BIGINT, STRING, INTEGER, TINYINT, BOOLEAN } = app.Sequelize;
const Camera = app.model.define('camera', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
subjectId: { type: BIGINT.UNSIGNED, comment: '所属主体 subjects.id(跟随 NVR)' },
nvrId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属 NVR(nvrs.id)' },
channelNo: { type: INTEGER.UNSIGNED, allowNull: false, comment: '海康通道号' },
name: { type: STRING(64), allowNull: false, defaultValue: '', comment: '摄像头名称(业务别名)' },
channelName: { type: STRING(64), comment: '设备通道名(ISAPI,拉取时刷新)' },
type: { type: STRING(16), allowNull: false, defaultValue: 'digital', comment: 'analog / digital' },
ip: { type: STRING(45), comment: '前端设备 IP' },
port: { type: INTEGER.UNSIGNED, comment: '前端设备管理端口' },
enabled: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '通道是否已配置' },
hasPtz: { type: BOOLEAN, allowNull: false, defaultValue: false, comment: '是否支持云台(PTZ)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
remark: { type: STRING(255), comment: '备注' },
}, {
tableName: 'cameras',
paranoid: true,
comment: '摄像头(NVR 通道)表',
});
Camera.associate = function() {
app.model.Camera.belongsTo(app.model.Nvr, { foreignKey: 'nvr_id', as: 'nvr' });
app.model.Camera.hasMany(app.model.WorkstationCamera, { foreignKey: 'camera_id', as: 'workstationLinks' });
};
return Camera;
};

44
backend/app/model/nvr.js Normal file
View File

@ -0,0 +1,44 @@
'use strict';
/**
* NVR 录像机表模型(nvrs)
*
* 一台 NVR = 一个地址 + 一个登录账号。密码**只存密文**(`password_enc`,AES-256-GCM),
* 接口层永不返回;需要调用设备时由 service 解密。
*
* `serial_number` / `channel_count` / `last_sync_at` 是「最近一次拉取通道」的回填信息,
* 拉取动作由前端调用**本机软件**(/api/hik/channels)完成,后端只落库。
*/
module.exports = (app) => {
const { BIGINT, STRING, SMALLINT, INTEGER, TINYINT, DATE } = app.Sequelize;
const Nvr = app.model.define('nvr', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
subjectId: { type: BIGINT.UNSIGNED, comment: '所属主体 subjects.id' },
userId: { type: BIGINT.UNSIGNED, comment: '归属用户 users.id' },
name: { type: STRING(64), allowNull: false, defaultValue: '', comment: '名称 / 别名' },
host: { type: STRING(128), allowNull: false, comment: '设备地址(IP 或域名)' },
port: { type: SMALLINT.UNSIGNED, allowNull: false, defaultValue: 8000, comment: 'SDK 服务端口' },
username: { type: STRING(64), allowNull: false, defaultValue: 'admin', comment: '登录账号' },
passwordEnc: { type: STRING(512), comment: '密码密文(AES-256-GCM)' },
serialNumber: { type: STRING(64), comment: '设备序列号' },
// 属性名不用 model,避免和 Sequelize 的 model 概念混淆;字段名仍是 model
deviceModel: { type: STRING(64), field: 'model', comment: '设备型号' },
channelCount: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '最近同步到的通道数' },
lastSyncAt: { type: DATE, comment: '最近一次拉取通道时间' },
lastError: { type: STRING(255), comment: '最近一次失败原因' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0停用' },
remark: { type: STRING(255), comment: '备注' },
}, {
tableName: 'nvrs',
paranoid: true,
comment: 'NVR 录像机表',
});
Nvr.associate = function() {
app.model.Nvr.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
app.model.Nvr.hasMany(app.model.Camera, { foreignKey: 'nvr_id', as: 'cameras' });
};
return Nvr;
};

View File

@ -14,6 +14,7 @@ module.exports = (app) => {
const ScanChannel = app.model.define('scanChannel', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
subjectId: { type: BIGINT.UNSIGNED, comment: '所属主体 subjects.id(跟随中控)' },
scannerId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '上报的中控(= scanners.id)' },
channelId: { type: STRING(64), allowNull: false, comment: '通道 id(中控上报,同一中控内唯一)' },
channelName: { type: STRING(128), allowNull: false, defaultValue: '', comment: '通道名(中控上报)' },

View File

@ -11,15 +11,20 @@
* 需要清理请按时间物理删除。
*/
module.exports = (app) => {
const { BIGINT, STRING, DATE } = app.Sequelize;
const { BIGINT, STRING, DATE, JSON: JSONType } = app.Sequelize;
const ScanRecord = app.model.define('scanRecord', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
subjectId: { type: BIGINT.UNSIGNED, comment: '所属主体 subjects.id(跟随中控)' },
scannerId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '上报的中控(= scanners.id)' },
channelId: { type: STRING(64), allowNull: false, comment: '通道 id' },
barcode: { type: STRING(255), allowNull: false, comment: '条码内容' },
scanTime: { type: DATE, allowNull: false, comment: '扫描时间(中控上报,秒级)' },
reportedAt: { type: DATE, allowNull: false, defaultValue: app.Sequelize.NOW, comment: '服务端接收时间' },
/** 扫码当时绑定的工作台(回放要按「当时」的配置拉流,不能按现在的) */
workstationId: { type: BIGINT.UNSIGNED, comment: '当时的工作台 workstations.id' },
workstationSnapshot: { type: JSONType, comment: '工作台快照(录像机/摄像头/布局/录制范围)' },
}, {
tableName: 'scan_records',
paranoid: false,

View File

@ -12,6 +12,7 @@ module.exports = (app) => {
const Scanner = app.model.define('scanner', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
subjectId: { type: BIGINT.UNSIGNED, comment: '所属主体 subjects.id' },
userId: { type: BIGINT.UNSIGNED, comment: '绑定的用户 id' },
sn: { type: STRING(64), allowNull: false, comment: '扫描器 SN(唯一标识)' },
name: { type: STRING(64), allowNull: false, defaultValue: '', comment: '名称 / 别名' },
@ -24,6 +25,9 @@ module.exports = (app) => {
// 库里不存 JWT 本体,只存当前令牌的 jti:重签令牌会让旧令牌立即失效
tokenJti: { type: STRING(64), comment: '当前 JWT 的 jti' },
tokenExpiresAt: { type: DATE, comment: '令牌过期时间' },
// 刷新令牌:库里只存 sha256,不存原文;每次刷新轮换并顺延过期时间
refreshTokenHash: { type: STRING(128), comment: '刷新令牌 sha256' },
refreshExpiresAt: { type: DATE, comment: '刷新令牌过期时间' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
lastRegisterAt: { type: DATE, comment: '最近注册时间' },
lastLoginAt: { type: DATE, comment: '最近登录时间' },

View File

@ -0,0 +1,34 @@
'use strict';
/**
* 主体表模型(subjects)
*
* 「主体」= 租户 / 公司 / 门店,是本系统所有业务数据的归属单位:
* 设备、NVR、摄像头、工作台、扫码记录都挂在主体下,接口按主体隔离。
*
* - `adminUserId`:管理员(默认就是创建人),只有管理员能改主体信息、加/删成员
* - `expireAt`:使用期限,到期后该主体不可进入(接口返回 403 subject_expired)
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
const Subject = app.model.define('subject', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
name: { type: STRING(64), allowNull: false, comment: '主体名称' },
adminUserId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '管理员 users.id(默认创建人)' },
expireAt: { type: DATE, allowNull: false, comment: '使用期限(到期后不可进入)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
remark: { type: STRING(255), comment: '备注' },
}, {
tableName: 'subjects',
paranoid: true,
comment: '主体表',
});
Subject.associate = function() {
app.model.Subject.belongsTo(app.model.User, { foreignKey: 'admin_user_id', as: 'admin' });
app.model.Subject.hasMany(app.model.SubjectMember, { foreignKey: 'subject_id', as: 'members' });
};
return Subject;
};

View File

@ -0,0 +1,38 @@
'use strict';
/**
* 主体成员表模型(subject_members)
*
* 一行 = 某主体下的一个成员:
* - `name`:姓名(必填,创建成员时先只填姓名也行)
* - `userId`:绑定的账号(可为空 —— 先建成员、之后用绑定码扫码绑定)
* - `role`:1 管理员 / 2 成员
* - `wechatOpenid` / `boundAt`:扫码绑定微信后记录
*
* 同一主体下同一账号只能有一条(DB 唯一索引 `subject_id + user_id`)。
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
const SubjectMember = app.model.define('subject_member', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
subjectId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' },
userId: { type: BIGINT.UNSIGNED, comment: '绑定账号 users.id(未绑定为空)' },
name: { type: STRING(32), allowNull: false, comment: '成员姓名' },
role: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 2, comment: '角色:1管理员 2成员' },
wechatOpenid: { type: STRING(64), comment: '绑定的微信 openid' },
boundAt: { type: DATE, comment: '绑定账号/微信时间' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
}, {
tableName: 'subject_members',
paranoid: true,
comment: '主体成员表',
});
SubjectMember.associate = function() {
app.model.SubjectMember.belongsTo(app.model.Subject, { foreignKey: 'subject_id', as: 'subject' });
app.model.SubjectMember.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
};
return SubjectMember;
};

View File

@ -19,6 +19,8 @@ module.exports = (app) => {
phone: { type: STRING(20), comment: '手机号' },
// 密码哈希(bcrypt),接口与模板都不外泄:查询时会显式 exclude
passwordHash: { type: STRING(100), comment: '密码哈希(bcrypt)' },
// 最近一次设置/重置密码的时间:签发早于它的 user JWT 立即失效(见 middleware/api_auth.js)
passwordChangedAt: { type: DATE, comment: '最近一次设置/重置密码的时间' },
gender: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '性别:0未知 1男 2女' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
remark: { type: STRING(255), comment: '备注' },

View File

@ -0,0 +1,42 @@
'use strict';
/**
* 工作台表模型(workstations)
*
* 一个工作台:绑定若干摄像头(workstation_cameras)+ 若干扫码通道(workstation_scan_channels)。
* `code` 是业务编号(如「1号工作台」),同一用户下唯一。
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, INTEGER } = app.Sequelize;
const Workstation = app.model.define('workstation', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
subjectId: { type: BIGINT.UNSIGNED, comment: '所属主体 subjects.id' },
userId: { type: BIGINT.UNSIGNED, comment: '创建人 users.id' },
code: { type: STRING(64), allowNull: false, comment: '工作台编号' },
name: { type: STRING(64), allowNull: false, defaultValue: '', comment: '工作台名称' }, /** 1 散单工作台 2 团购工作台 */
wsType: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '工作台类型' },
/** 录制范围(团购以扫码时间为基准,散单以任务结束时间为基准) */
recordBeforeSec: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 60, comment: '录制范围:触发点之前秒数' },
recordAfterSec: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 60, comment: '录制范围:触发点之后秒数' },
recordMaxSec: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 240, comment: '最大录制时长(秒)' }, status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
remark: { type: STRING(255), comment: '备注' },
// ↓ 合成画面画布(默认 1920×1080)
canvasWidth: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 1920, comment: '合成画布宽' },
canvasHeight: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 1080, comment: '合成画布高' },
}, {
tableName: 'workstations',
paranoid: true,
comment: '工作台表',
});
Workstation.associate = function() {
app.model.Workstation.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
app.model.Workstation.hasMany(app.model.WorkstationCamera, { foreignKey: 'workstation_id', as: 'cameraLinks' });
app.model.Workstation.hasMany(app.model.WorkstationScanChannel, { foreignKey: 'workstation_id', as: 'scanChannelLinks' });
};
return Workstation;
};

View File

@ -0,0 +1,39 @@
'use strict';
/**
* 工作台 ↔ 摄像头 绑定表(workstation_cameras)
*
* 一个工作台可绑定多个摄像头(一个摄像头也可以出现在多个工作台,绑定关系不独占)。
* 唯一键 `(workstation_id, camera_id)`,解绑是**物理删除**(绑定关系没有保留价值)。
*/
module.exports = (app) => {
const { BIGINT, STRING, INTEGER, TINYINT } = app.Sequelize;
const WorkstationCamera = app.model.define('workstationCamera', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
workstationId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '工作台 id' },
cameraId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '摄像头 id' },
sortNo: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '排序' },
remark: { type: STRING(255), comment: '备注' },
// ↓ 合成画面布局(画布坐标,像素)
x: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '画布左上角 x' },
y: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '画布左上角 y' },
width: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '宽(0=整张画布)' },
height: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '高(0=整张画布)' },
streamType: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '0 主码流 1 子码流' },
zIndex: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '叠放顺序' },
}, {
tableName: 'workstation_cameras',
timestamps: true,
paranoid: false,
comment: '工作台-摄像头绑定表',
});
WorkstationCamera.associate = function() {
app.model.WorkstationCamera.belongsTo(app.model.Workstation, { foreignKey: 'workstation_id', as: 'workstation' });
app.model.WorkstationCamera.belongsTo(app.model.Camera, { foreignKey: 'camera_id', as: 'camera' });
};
return WorkstationCamera;
};

View File

@ -0,0 +1,36 @@
'use strict';
/**
* 工作台 ↔ 扫码通道 绑定表(workstation_scan_channels)
*
* 「扫码通道」本身在中控上(scan_channels 表,键是 scanner_id + channel_id),
* 这里存的是工作台与「某个中控的某个通道」的绑定,并冗余一份通道名快照,
* 避免中控改名/离线时列表显示空白。
*
* 唯一键 `(workstation_id, scanner_id, channel_id)`;解绑是物理删除。
*/
module.exports = (app) => {
const { BIGINT, STRING, INTEGER } = app.Sequelize;
const WorkstationScanChannel = app.model.define('workstationScanChannel', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
workstationId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '工作台 id' },
scannerId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '扫码中控 id(scanners.id)' },
channelId: { type: STRING(64), allowNull: false, comment: '通道 id' },
channelName: { type: STRING(128), allowNull: false, defaultValue: '', comment: '通道名快照' },
sortNo: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '排序' },
remark: { type: STRING(255), comment: '备注' },
}, {
tableName: 'workstation_scan_channels',
timestamps: true,
paranoid: false,
comment: '工作台-扫码通道绑定表',
});
WorkstationScanChannel.associate = function() {
app.model.WorkstationScanChannel.belongsTo(app.model.Workstation, { foreignKey: 'workstation_id', as: 'workstation' });
app.model.WorkstationScanChannel.belongsTo(app.model.Scanner, { foreignKey: 'scanner_id', as: 'scanner' });
};
return WorkstationScanChannel;
};

View File

@ -7,6 +7,7 @@
module.exports = (app) => {
const { router, controller, middleware } = app;
const apiAuth = middleware.apiAuth();
const subjectAuth = middleware.subjectAuth();
const internalAuth = middleware.internalAuth();
const scannerAuth = middleware.scannerAuth();
@ -39,22 +40,79 @@ module.exports = (app) => {
router.put('/api/web/me', apiAuth, controller.web.profile.update);
router.put('/api/web/me/password', apiAuth, controller.web.profile.changePassword);
// 首页统计(只统计当前用户名下的数据)
router.get('/api/web/stats', apiAuth, controller.web.stats.index);
// ---------- 主体(租户):不输主体 id,靠「当前用户是否是成员」判定 ----------
// 除这几个以外的业务接口都要额外带 `X-Subject-Id`(middleware/subjectAuth)
router.get('/api/web/subjects', apiAuth, controller.web.subject.index);
router.post('/api/web/subjects', apiAuth, controller.web.subject.create);
router.get('/api/web/subjects/:id', apiAuth, controller.web.subject.show);
router.put('/api/web/subjects/:id', apiAuth, controller.web.subject.update);
router.get('/api/web/subjects/:id/members', apiAuth, controller.web.subject.members);
router.post('/api/web/subjects/:id/members', apiAuth, controller.web.subject.addMember);
router.delete('/api/web/subjects/:id/members/:memberId', apiAuth, controller.web.subject.removeMember);
// 给未绑定账号/微信的成员生成绑定码(手机扫码后绑定)
router.post('/api/web/subjects/:id/members/:memberId/bind-code', apiAuth, controller.web.subject.memberBindCode);
// 我的设备:列表 / 详情 / 通道 / 解绑 / 删除(越权访问一律 404)
router.get('/api/web/devices', apiAuth, controller.web.device.index);
router.get('/api/web/devices/:id', apiAuth, controller.web.device.show);
router.get('/api/web/devices/:id/channels', apiAuth, controller.web.device.channels);
router.post('/api/web/devices/:id/unbind', apiAuth, controller.web.device.unbind);
router.delete('/api/web/devices/:id', apiAuth, controller.web.device.destroy);
// 成员绑定:手机扫码页(公开查状态)+ 登录后确认绑定
router.get('/api/subject/member-bind', controller.auth.memberBind.status);
router.post('/api/subject/member-bind/confirm', apiAuth, controller.auth.memberBind.confirm);
// 我的扫码记录(范围限定在当前用户名下的设备)
router.get('/api/web/records', apiAuth, controller.web.record.index);
// 首页统计(只统计当前主体的数据)
router.get('/api/web/stats', apiAuth, subjectAuth, controller.web.stats.index);
// 本主体设备:列表 / 详情 / 通道 / 解绑 / 删除(越权访问一律 404)
// ⚠️ /devices/active 与 /devices/activate 必须在 /devices/:id 之前
router.get('/api/web/devices', apiAuth, subjectAuth, controller.web.device.index);
router.get('/api/web/devices/active', apiAuth, subjectAuth, controller.web.device.active);
router.post('/api/web/devices/activate', apiAuth, subjectAuth, controller.web.device.activate);
router.get('/api/web/devices/:id', apiAuth, subjectAuth, controller.web.device.show);
router.get('/api/web/devices/:id/channels', apiAuth, subjectAuth, controller.web.device.channels);
router.post('/api/web/devices/:id/unbind', apiAuth, subjectAuth, controller.web.device.unbind);
router.post('/api/web/devices/:id/logout', apiAuth, subjectAuth, controller.web.device.logout);
router.delete('/api/web/devices/:id', apiAuth, subjectAuth, controller.web.device.destroy);
// 本主体扫码记录(范围限定在当前主体的设备)
router.get('/api/web/records', apiAuth, subjectAuth, controller.web.record.index);
// 运单回放查询:运单号 → 当时的工位快照(录像机/摄像头/布局)+ 要拉的回放区间
// 桌面端拿到后按 streams 去各 NVR 拉那段录像(凭据走 /api/web/nvrs/:id/credential)
router.get('/api/web/pack-query', apiAuth, subjectAuth, controller.web.pack.query);
// ---------- 视频接入:NVR / 摄像头 / 工作台(只碰本主体的数据)----------
// 拉取通道 = 前端调本机软件(localhost:17300/api/hik/channels)→ 勾选 → POST /nvrs/:id/channels 落库
router.get('/api/web/nvrs', apiAuth, subjectAuth, controller.web.nvr.index);
router.post('/api/web/nvrs', apiAuth, subjectAuth, controller.web.nvr.create);
router.get('/api/web/nvrs/:id', apiAuth, subjectAuth, controller.web.nvr.show);
router.put('/api/web/nvrs/:id', apiAuth, subjectAuth, controller.web.nvr.update);
router.delete('/api/web/nvrs/:id', apiAuth, subjectAuth, controller.web.nvr.destroy);
router.get('/api/web/nvrs/:id/channels', apiAuth, subjectAuth, controller.web.nvr.cameras);
router.post('/api/web/nvrs/:id/channels', apiAuth, subjectAuth, controller.web.nvr.syncChannels);
router.get('/api/web/nvrs/:id/credential', apiAuth, subjectAuth, controller.web.nvr.credential);
// 摄像头:/options、/batch-delete 必须在 /:id 之前注册,否则会被当成 id
router.get('/api/web/cameras/options', apiAuth, subjectAuth, controller.web.camera.options);
router.post('/api/web/cameras/batch-delete', apiAuth, subjectAuth, controller.web.camera.batchDestroy);
router.get('/api/web/cameras', apiAuth, subjectAuth, controller.web.camera.index);
router.get('/api/web/cameras/:id', apiAuth, subjectAuth, controller.web.camera.show);
router.put('/api/web/cameras/:id', apiAuth, subjectAuth, controller.web.camera.update);
router.delete('/api/web/cameras/:id', apiAuth, subjectAuth, controller.web.camera.destroy);
// 工作台:CRUD + 绑定摄像头 + 绑定扫码通道
router.get('/api/web/workstation-scan-channels', apiAuth, subjectAuth, controller.web.workstation.availableScanChannels);
router.get('/api/web/workstations', apiAuth, subjectAuth, controller.web.workstation.index);
router.post('/api/web/workstations', apiAuth, subjectAuth, controller.web.workstation.create);
router.get('/api/web/workstations/:id', apiAuth, subjectAuth, controller.web.workstation.show);
router.put('/api/web/workstations/:id', apiAuth, subjectAuth, controller.web.workstation.update);
router.delete('/api/web/workstations/:id', apiAuth, subjectAuth, controller.web.workstation.destroy);
router.post('/api/web/workstations/:id/cameras', apiAuth, subjectAuth, controller.web.workstation.bindCameras);
router.delete('/api/web/workstations/:id/cameras/:cameraId', apiAuth, subjectAuth, controller.web.workstation.unbindCamera);
// 合成画面布局(拖拽/缩放后保存)
router.put('/api/web/workstations/:id/cameras/:cameraId/layout', apiAuth, subjectAuth, controller.web.workstation.updateCameraLayout);
router.post('/api/web/workstations/:id/scan-channels', apiAuth, subjectAuth, controller.web.workstation.bindScanChannels);
router.delete('/api/web/workstations/:id/scan-channels/:linkId', apiAuth, subjectAuth, controller.web.workstation.unbindScanChannel);
// 前端「测试页」的模拟接口(模拟设备扫码登录 / 模拟中控上报),与真机走同一套 service
router.post('/api/web/test/device-login', apiAuth, controller.web.test.deviceLogin);
router.post('/api/web/test/scan', apiAuth, controller.web.test.scan);
router.post('/api/web/test/device-login', apiAuth, subjectAuth, controller.web.test.deviceLogin);
router.post('/api/web/test/scan', apiAuth, subjectAuth, controller.web.test.scan);
// ---------- 运维/内部(脚本、后台系统;**需内部令牌**,见 middleware/internal_auth.js)----------
router.get('/api/users', internalAuth, controller.internal.user.index);
@ -87,6 +145,8 @@ module.exports = (app) => {
// ---------- 公开的登录接口(auth)----------
// 登录码二维码(SVG,本地生成;前端登录页直接 img 引用)
router.get('/api/wechat/qrcode.svg', controller.auth.wechat.qrcode);
// 同一张二维码的 GIF 版(桌面端 WPF 不能渲染 SVG)
router.get('/api/wechat/qrcode.gif', controller.auth.wechat.qrcodeGif);
// 扫码登录(前端/客户端接口):不带参数发串码,带 ?code=&wait= 长轮询并拿用户 JWT
router.get('/api/wechat/login', controller.auth.wechat.login);
// 查登录码状态(无需登录)
@ -95,6 +155,8 @@ module.exports = (app) => {
router.get('/api/wechat/callback', controller.auth.wechat.callback);
// 设备发码 + 长轮询:**这一步才注册/绑定**并直接拿到长期 JWT(发码不需要任何凭据)
router.get('/api/device/login', controller.device.auth.login);
// 刷新访问令牌:凭据是刷新令牌本身(访问令牌可能已过期,所以不能挂 scannerAuth)
router.post('/api/device/refresh', controller.device.auth.refresh);
// ---------- 用户态(client):小程序 / Win 客户端 / SPA ----------
// 用登录码触发登录(**不认 cookie**:header 带 Authorization: Bearer <user JWT> 就行)

View File

@ -81,8 +81,10 @@ class AuthService extends Service {
return false;
}
await user.update({ passwordHash: await this.hashPassword(newPassword) });
this.ctx.logger.info('[auth] 密码已修改, userId=%s', userId);
await user.update({ passwordHash: await this.hashPassword(newPassword), passwordChangedAt: new Date() });
// 该用户详情有缓存(/api/users/:id),顺手失效
await this.ctx.service.cache.del(`user:${userId}`).catch(() => {});
this.ctx.logger.info('[auth] 密码已修改, userId=%s(旧令牌立即失效)', userId);
return true;
}
}

View File

@ -0,0 +1,282 @@
'use strict';
const { Service } = require('egg');
const { Op } = require('sequelize');
/**
* 摄像头(NVR 通道)service
*
* 关键点:
* - 归属看**主体 `subject_id`**(跟随所属 NVR),别的主体的摄像头一律 404
* - 唯一键 `(nvr_id, channel_no)`:同一通道重复添加走「更新 / 复活」,不产生重复行
* - 批量添加用事务,最后回填 NVR 的通道数与同步时间
*/
const NVR_ATTRIBUTES = [ 'id', 'name', 'host', 'port', 'serialNumber', 'subjectId', 'userId' ];
class CameraService extends Service {
get Camera() {
return this.app.model.Camera;
}
get Nvr() {
return this.app.model.Nvr;
}
/** 分页列表:可按 NVR、状态过滤,keyword 匹配名称 / IP / 通道号 */
async list({ page = 1, pageSize = 20, keyword, nvrId, status, subjectId } = {}) {
const size = Math.min(Number(pageSize) || 20, 100);
const current = Math.max(Number(page) || 1, 1);
// 只查属于当前主体的 NVR 下的摄像头
const nvrWhere = { subjectId: Number(subjectId) };
if (nvrId) nvrWhere.id = Number(nvrId);
const where = {};
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
if (keyword) {
where[Op.or] = [
{ name: { [Op.like]: `%${keyword}%` } },
{ ip: { [Op.like]: `%${keyword}%` } },
];
const asNumber = Number(keyword);
if (Number.isInteger(asNumber)) where[Op.or].push({ channelNo: asNumber });
}
const { rows, count } = await this.Camera.findAndCountAll({
where,
include: [{
model: this.Nvr,
as: 'nvr',
required: true,
where: nvrWhere,
attributes: NVR_ATTRIBUTES,
}],
limit: size,
offset: (current - 1) * size,
order: [[ 'nvr_id', 'ASC' ], [ 'channel_no', 'ASC' ]],
});
return {
list: rows.map(row => row.toJSON()),
total: count,
page: current,
pageSize: size,
};
}
/** 某台 NVR 下的全部摄像头(不分页,绑定时用) */
async listByNvr(nvrId, subjectId) {
const nvr = await this.ctx.service.nvr.findOwned(nvrId, subjectId);
const rows = await this.Camera.findAll({
where: { nvrId: nvr.id },
order: [[ 'channel_no', 'ASC' ]],
});
return rows.map(row => row.toJSON());
}
/** 取单个摄像头(含所属 NVR),归属校验失败 → 404 */
async findOwned(id, subjectId) {
const camera = await this.Camera.findByPk(id, {
include: [{ model: this.Nvr, as: 'nvr', required: true, attributes: NVR_ATTRIBUTES }],
});
if (!camera || Number(camera.subjectId) !== Number(subjectId)) {
this.ctx.throw(404, '摄像头不存在或不属于当前主体');
}
return camera;
}
/**
* 批量添加摄像头(前端从本机软件拉到通道后,勾选提交)
*
* @param {object} params
* @param {number} params.subjectId 当前主体
* @param {number} params.nvrId 所属 NVR
* @param {Array} params.channels [{ channel|channelNo, type?, name?, ip?, port?, enabled? }]
* @returns {Promise<object>} { created, updated, list, nvr }
*/
async batchCreate({ subjectId, nvrId, channels = [] } = {}) {
if (!Array.isArray(channels) || channels.length === 0) this.ctx.throw(422, 'channels 不能为空');
const nvr = await this.ctx.service.nvr.findOwned(nvrId, subjectId);
const normalized = [];
const seen = new Set();
for (const raw of channels) {
const channelNo = Number(raw && (raw.channel !== undefined ? raw.channel : raw.channelNo));
if (!Number.isInteger(channelNo) || channelNo <= 0) this.ctx.throw(422, '通道号必须是正整数');
if (seen.has(channelNo)) continue;
seen.add(channelNo);
normalized.push({
channelNo,
name: String(raw.name || '').trim() || `${nvr.name || 'NVR'}-${channelNo}`,
// 设备原始通道名单独存一份,业务名改了也不丢
channelName: String(raw.name || '').trim() || null,
type: raw.type === 'analog' ? 'analog' : 'digital',
ip: raw.ip ? String(raw.ip).slice(0, 45) : null,
port: raw.port ? Number(raw.port) : null,
enabled: raw.enabled === false || raw.enabled === 0 ? 0 : 1,
});
}
let created = 0;
let updated = 0;
const transaction = await this.app.model.transaction();
try {
for (const item of normalized) {
const existing = await this.Camera.findOne({
where: { nvrId: nvr.id, channelNo: item.channelNo },
paranoid: false,
transaction,
});
if (existing) {
if (existing.deletedAt) await existing.restore({ transaction });
// 名称保护:用户改过名的不要被「重新拉取通道」覆盖,只更新设备侧字段
const defaultName = `${nvr.name || 'NVR'}-${item.channelNo}`;
const keepName = existing.name && existing.name !== defaultName;
const patch = Object.assign({}, item, { nvrId: nvr.id, subjectId: Number(subjectId) });
if (keepName) delete patch.name;
await existing.update(patch, { transaction });
updated += 1;
} else {
await this.Camera.create(Object.assign({}, item, { nvrId: nvr.id, subjectId: Number(subjectId) }), { transaction });
created += 1;
}
}
await nvr.update({
channelCount: await this.Camera.count({ where: { nvrId: nvr.id }, transaction }),
lastSyncAt: new Date(),
lastError: null,
}, { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
this.ctx.logger.info('[camera] 主体 %s 从 NVR %s 导入通道:新增 %d,更新 %d',
subjectId, nvr.id, created, updated);
const list = await this.listByNvr(nvr.id, subjectId);
return { created, updated, list, nvr: await this.ctx.service.nvr.findOwned(nvr.id, subjectId) };
}
/** 更新摄像头(名称 / 状态 / 备注 / 是否带云台) */
async update(id, subjectId, patch = {}) {
const camera = await this.findOwned(id, subjectId);
const fields = {};
if (patch.name !== undefined) fields.name = String(patch.name || '').trim();
if (patch.remark !== undefined) fields.remark = patch.remark;
if (patch.status !== undefined) fields.status = Number(patch.status) === 0 ? 0 : 1;
if (patch.hasPtz !== undefined) fields.hasPtz = Boolean(Number(patch.hasPtz));
await camera.update(fields);
return this.findOwned(id, subjectId);
}
/** 删除摄像头(软删除 + 解除工作台绑定) */
async remove(id, subjectId) {
const camera = await this.findOwned(id, subjectId);
await this.app.model.WorkstationCamera.destroy({ where: { cameraId: camera.id } });
await camera.destroy();
await this.syncNvrChannelCount(camera.nvrId);
this.ctx.logger.info('[camera] 主体 %s 删除摄像头 %s', subjectId, camera.id);
return { id: camera.id };
}
/**
* 批量删除(只删除属于当前主体的)
*
* @param {number[]} ids 摄像头 id
* @returns {Promise<{ removed: number, skipped: number }>} skipped = 不属于当前主体/不存在的数量
*/
async batchRemove({ subjectId, ids = [] } = {}) {
const list = Array.isArray(ids) ? [ ...new Set(ids.map(Number).filter(item => Number.isInteger(item) && item > 0)) ] : [];
if (!list.length) this.ctx.throw(422, 'ids 不能为空');
const nvrs = await this.Nvr.findAll({ attributes: [ 'id' ], where: { subjectId: Number(subjectId) }, raw: true });
const nvrIds = nvrs.map(item => item.id);
const owned = nvrIds.length
? await this.Camera.findAll({ attributes: [ 'id' ], where: { id: { [Op.in]: list }, nvrId: { [Op.in]: nvrIds } }, raw: true })
: [];
const ownedIds = owned.map(item => item.id);
if (!ownedIds.length) return { removed: 0, skipped: list.length };
// 先记下涉及的 NVR,删完回填计数
const rows = await this.Camera.findAll({ attributes: [ 'nvrId' ], where: { id: { [Op.in]: ownedIds } }, raw: true });
const affectedNvrIds = [ ...new Set(rows.map(item => Number(item.nvrId))) ];
await this.app.model.WorkstationCamera.destroy({ where: { cameraId: { [Op.in]: ownedIds } } });
const removed = await this.Camera.destroy({ where: { id: { [Op.in]: ownedIds } } });
await Promise.all(affectedNvrIds.map(nvrId => this.syncNvrChannelCount(nvrId)));
this.ctx.logger.info('[camera] 主体 %s 批量删除摄像头 %s', subjectId, ownedIds.join(','));
return { removed, skipped: list.length - ownedIds.length };
}
/** 回填 NVR 的「已导入通道数」(增删摄像头后保持一致) */
async syncNvrChannelCount(nvrId) {
if (!nvrId) return;
const count = await this.Camera.count({ where: { nvrId } });
await this.Nvr.update({ channelCount: count }, { where: { id: nvrId } });
}
/** 某主体可用的全部摄像头(工作台绑定选择器用) */
/**
* 工作台选择器用:当前主体的摄像头 + 「已被哪个工作台绑定」(null = 还可以绑)
*/
async optionsOfUser(subjectId) {
const list = await this.listOfUser(subjectId);
if (!list.length) return [];
const cameraIds = list.map(item => Number(item.id));
const links = await this.app.model.WorkstationCamera.findAll({
where: { cameraId: { [Op.in]: cameraIds } },
include: [{
model: this.app.model.Workstation,
as: 'workstation',
required: false,
attributes: [ 'id', 'code', 'name' ],
}],
});
const boundBy = new Map();
for (const link of links) {
boundBy.set(Number(link.cameraId), link.workstation ? link.workstation.toJSON() : null);
}
return list.map(item => ({
...item,
boundWorkstation: boundBy.get(Number(item.id)) || null,
}));
}
async listOfUser(subjectId) {
const nvrs = await this.Nvr.findAll({ attributes: [ 'id' ], where: { subjectId: Number(subjectId) }, raw: true });
if (!nvrs.length) return [];
const rows = await this.Camera.findAll({
where: { nvrId: { [Op.in]: nvrs.map(item => item.id) }, status: 1 },
include: [{ model: this.Nvr, as: 'nvr', attributes: NVR_ATTRIBUTES }],
order: [[ 'nvr_id', 'ASC' ], [ 'channel_no', 'ASC' ]],
});
return rows.map(row => row.toJSON());
}
}
module.exports = CameraService;

272
backend/app/service/nvr.js Normal file
View File

@ -0,0 +1,272 @@
'use strict';
const { Service } = require('egg');
const { Op } = require('sequelize');
const crypto = require('crypto');
/**
* NVR 录像机 service
*
* 职责:
* - NVR 的增删改查(**按主体 `subject_id` 隔离**,别的主体的一律 404)
* - 登录密码的**加解密**:库里只存密文(AES-256-GCM),接口永不返回
* - 拉取通道后回填序列号 / 通道数 / 最近同步时间
*
* 密钥来源:`NVR_SECRET` 环境变量 > `config.keys`(同一部署内稳定即可;
* 换密钥会导致已存的密文解不开,表现为「密码需要重新填写」)。
*/
/** 列表/详情默认不返回密码密文 */
const SAFE_ATTRIBUTES = { exclude: [ 'passwordEnc' ] };
const CIPHER_PREFIX = 'v1';
function deriveKey(secret) {
return crypto.createHash('sha256').update(`nvr-credential:${secret}`).digest();
}
function encryptPassword(plain, secret) {
if (!plain) return null;
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', deriveKey(secret), iv);
const encrypted = Buffer.concat([ cipher.update(String(plain), 'utf8'), cipher.final() ]);
const tag = cipher.getAuthTag();
return [ CIPHER_PREFIX, iv.toString('base64'), tag.toString('base64'), encrypted.toString('base64') ].join(':');
}
function decryptPassword(payload, secret) {
if (!payload) return '';
const parts = String(payload).split(':');
if (parts.length !== 4 || parts[0] !== CIPHER_PREFIX) return '';
try {
const iv = Buffer.from(parts[1], 'base64');
const tag = Buffer.from(parts[2], 'base64');
const data = Buffer.from(parts[3], 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', deriveKey(secret), iv);
decipher.setAuthTag(tag);
return Buffer.concat([ decipher.update(data), decipher.final() ]).toString('utf8');
} catch (err) {
return '';
}
}
class NvrService extends Service {
get Nvr() {
return this.app.model.Nvr;
}
get secret() {
return process.env.NVR_SECRET || this.app.config.keys;
}
/** 密码加密(供 create/update 用) */
encrypt(plain) {
return encryptPassword(plain, this.secret);
}
/** 解密设备密码(内部使用,绝不直接返回给前端) */
passwordOf(nvr) {
return decryptPassword(nvr && nvr.passwordEnc, this.secret);
}
/**
* 取「拉取通道」所需的登录凭据(含**明文**密码)
*
* 仅限 NVR 所有者调用;返回给前端后会立即随请求传给本机软件,
* 服务端不做任何缓存。列表/详情接口依然**不返回**密码。
*/
async credentialOf(id, subjectId) {
const nvr = await this.Nvr.findByPk(id, { attributes: { include: [ 'passwordEnc' ] } });
if (!nvr || Number(nvr.subjectId) !== Number(subjectId)) {
this.ctx.throw(404, 'NVR 不存在或不属于当前主体');
}
return {
id: nvr.id,
name: nvr.name,
host: nvr.host,
port: nvr.port,
username: nvr.username,
password: this.passwordOf(nvr),
hasPassword: Boolean(nvr.passwordEnc),
};
}
/** 取「当前主体」的 NVR;不存在或不属于当前主体 → 404 */
async findOwned(id, subjectId) {
const nvr = await this.Nvr.findByPk(id, { attributes: SAFE_ATTRIBUTES });
if (!nvr || Number(nvr.subjectId) !== Number(subjectId)) {
this.ctx.throw(404, 'NVR 不存在或不属于当前主体');
}
return nvr;
}
/** 分页列表:keyword 模糊匹配名称 / 地址 / 序列号 */
async list({ page = 1, pageSize = 20, keyword, status, subjectId } = {}) {
const size = Math.min(Number(pageSize) || 20, 100);
const current = Math.max(Number(page) || 1, 1);
const where = {};
if (subjectId) where.subjectId = Number(subjectId);
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
if (keyword) {
where[Op.or] = [
{ name: { [Op.like]: `%${keyword}%` } },
{ host: { [Op.like]: `%${keyword}%` } },
{ serialNumber: { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await this.Nvr.findAndCountAll({
where,
attributes: SAFE_ATTRIBUTES,
limit: size,
offset: (current - 1) * size,
order: [[ 'id', 'DESC' ]],
});
return {
list: rows.map(row => row.toJSON()),
total: count,
page: current,
pageSize: size,
};
}
/**
* 新增 NVR
*
* 同一 `host + port + username` 全局唯一(唯一索引):重复添加时
* - 已被其他主体占用 → 409
* - 自己之前删过 → 复活并更新
* - 当前主体已存在 → 更新(覆盖密码等信息)
*
* @param {object} params { subjectId 当前主体, userId 创建人, name, host, port, username, password, serialNumber?, deviceModel?, remark? }
*/
async create({ subjectId, userId, name, host, port = 8000, username = 'admin', password, serialNumber, deviceModel, remark } = {}) {
if (!subjectId) this.ctx.throw(400, '缺少主体');
const finalHost = String(host || '').trim();
if (!finalHost) this.ctx.throw(422, 'host 不能为空');
const finalPort = Number(port) || 8000;
if (finalPort < 1 || finalPort > 65535) this.ctx.throw(422, 'port 必须在 1~65535 之间');
const finalUser = String(username || '').trim() || 'admin';
if (!password) this.ctx.throw(422, 'password 不能为空');
// 带已删除的一起查:软删的行仍占着唯一键
const existing = await this.Nvr.findOne({
where: { host: finalHost, port: finalPort, username: finalUser },
attributes: { include: [ 'passwordEnc' ] },
paranoid: false,
});
if (existing) {
if (existing.subjectId && Number(existing.subjectId) !== Number(subjectId)) {
this.ctx.throw(409, `NVR ${finalHost}:${finalPort} 已被其他主体添加`);
}
if (existing.deletedAt) await existing.restore();
await existing.update({
subjectId: Number(subjectId),
userId: Number(userId),
name: name === undefined ? existing.name : String(name || '').trim(),
passwordEnc: this.encrypt(password),
serialNumber: serialNumber || existing.serialNumber,
deviceModel: deviceModel || existing.deviceModel,
remark: remark === undefined ? existing.remark : remark,
status: 1,
lastError: null,
});
return this.findOwned(existing.id, subjectId);
}
const created = await this.Nvr.create({
subjectId: Number(subjectId),
userId: Number(userId),
name: String(name || '').trim(),
host: finalHost,
port: finalPort,
username: finalUser,
passwordEnc: this.encrypt(password),
serialNumber: serialNumber || null,
deviceModel: deviceModel || null,
remark: remark || null,
status: 1,
});
this.ctx.logger.info('[nvr] 主体 %s 新增 NVR %s(%s:%s)', subjectId, created.name, finalHost, finalPort);
return this.findOwned(created.id, subjectId);
}
/**
* 更新 NVR(`password` 不传 = 保持原密码)
* @param {object} patch { name?, host?, port?, username?, password?, remark?, status? }
*/
async update(id, subjectId, patch = {}) {
const nvr = await this.Nvr.findByPk(id, { attributes: { include: [ 'passwordEnc' ] } });
if (!nvr || Number(nvr.subjectId) !== Number(subjectId)) this.ctx.throw(404, 'NVR 不存在或不属于当前主体');
const fields = {};
if (patch.name !== undefined) fields.name = String(patch.name || '').trim();
if (patch.remark !== undefined) fields.remark = patch.remark;
if (patch.status !== undefined) fields.status = Number(patch.status) === 0 ? 0 : 1;
if (patch.host !== undefined) fields.host = String(patch.host || '').trim() || nvr.host;
if (patch.port !== undefined) {
const nextPort = Number(patch.port);
if (!nextPort || nextPort < 1 || nextPort > 65535) this.ctx.throw(422, 'port 必须在 1~65535 之间');
fields.port = nextPort;
}
if (patch.username !== undefined) fields.username = String(patch.username || '').trim() || nvr.username;
if (patch.password) fields.passwordEnc = this.encrypt(patch.password);
try {
await nvr.update(fields);
} catch (err) {
if (err && err.name === 'SequelizeUniqueConstraintError') {
this.ctx.throw(409, '该地址 + 账号的 NVR 已存在');
}
throw err;
}
return this.findOwned(id, subjectId);
}
/**
* 删除 NVR(软删除)
*
* 级联处理:该 NVR 下的摄像头一并软删除,并解除它们与工作台的绑定,
* 避免工作台里残留「指向已删除 NVR 的摄像头」。
*/
async remove(id, subjectId) {
const nvr = await this.findOwned(id, subjectId);
const { Camera, WorkstationCamera } = this.app.model;
const cameras = await Camera.findAll({ attributes: [ 'id' ], where: { nvrId: nvr.id }, raw: true });
const cameraIds = cameras.map(item => item.id);
if (cameraIds.length) {
await WorkstationCamera.destroy({ where: { cameraId: { [Op.in]: cameraIds } } });
await Camera.destroy({ where: { id: { [Op.in]: cameraIds } } });
}
await nvr.destroy();
this.ctx.logger.info('[nvr] 主体 %s 删除 NVR %s(连带 %d 个摄像头)', subjectId, nvr.id, cameraIds.length);
return { id: nvr.id, removedCameras: cameraIds.length };
}
/** 前端拉取成功/失败后回填同步结果 */
async saveSyncResult(id, subjectId, { serialNumber, deviceModel, channelCount, error } = {}) {
const nvr = await this.findOwned(id, subjectId);
const fields = { lastSyncAt: new Date() };
if (serialNumber !== undefined) fields.serialNumber = serialNumber || nvr.serialNumber;
if (deviceModel !== undefined) fields.deviceModel = deviceModel || nvr.deviceModel;
if (channelCount !== undefined) fields.channelCount = Number(channelCount) || 0;
fields.lastError = error ? String(error).slice(0, 255) : null;
await nvr.update(fields);
return this.findOwned(id, subjectId);
}
}
module.exports = NvrService;

353
backend/app/service/pack.js Normal file
View File

@ -0,0 +1,353 @@
'use strict';
const { Service } = require('egg');
const { Op } = require('sequelize');
const { asInt, buildSnapshot } = require('../lib/workstation-snapshot');
/** 单次查询最多返回多少条扫码记录(同一运单被反复扫的情况兜底) */
const MAX_RECORDS = 50;
function plusSeconds(date, seconds) {
return new Date(date.getTime() + seconds * 1000);
}
function secondsBetween(from, to) {
return Math.round((to.getTime() - from.getTime()) / 1000);
}
/**
* 运单回放查询(`GET /api/web/pack-query?code=xxx`)
*
* 一句话:给一个运单号,告诉桌面端「去哪些录像机的哪些通道、拉哪一段时间、画面怎么摆」。
*
* 关键设计:
* 1. **用扫码当时的快照**,不是现在的工作台配置 —— 工作台后来改过/删掉了,
* 历史运单也要能按当年的布局查回放;老记录没有快照时回落到「当前绑定」并打 `snapshotMiss`。
* 2. **两种工作台的录制区间不一样**:
* - 团购(wsType=2):以**扫码时间**为基准,前 `recordBeforeSec` / 后 `recordAfterSec`;
* - 散单(wsType=1):扫码代表一次打包任务的**开始**,**下一次扫码**才是这次任务的结束
* (所以要把「下一个打包开始时间」和当前开始时间对比),区间长度不超过 `recordMaxSec`;
* 没有下一条时按 `scanTime + recordMaxSec` 兜底。
* 两边都再往前后各留一点余量(`recordBeforeSec` / `recordAfterSec`),
* 给「按开始/结束各留延迟」的现场习惯用。
* 3. 同一运单可能被扫多次(不同工作台/重复扫),**每条记录都出一份回放计划**,
* 并把所有流拍平到 `streams` 里,桌面端一次拿全、不用二次查询。
*/
class PackService extends Service {
get ScanRecord() {
return this.app.model.ScanRecord;
}
get WorkstationScanChannel() {
return this.app.model.WorkstationScanChannel;
}
/**
* 批量构造工作台快照(入库时用)
*
* @param {Array<{scannerId:number, channelId:string}>} pairs 本批扫码涉及的 (中控, 通道)
* @return {Promise<Map<string, object>>} key = `${scannerId}|${channelId}`
*/
async snapshotMap(pairs) {
const map = new Map();
if (!Array.isArray(pairs) || !pairs.length) return map;
const scannerIds = [ ...new Set(pairs.map(item => Number(item.scannerId)).filter(Boolean)) ];
const channelIds = [ ...new Set(pairs.map(item => String(item.channelId || '')).filter(Boolean)) ];
if (!scannerIds.length || !channelIds.length) return map;
const links = await this.WorkstationScanChannel.findAll({
where: { scannerId: { [Op.in]: scannerIds }, channelId: { [Op.in]: channelIds } },
include: [{
model: this.app.model.Workstation,
as: 'workstation',
required: true,
include: [{
model: this.app.model.WorkstationCamera,
as: 'cameraLinks',
required: false,
include: [{
model: this.app.model.Camera,
as: 'camera',
required: false,
include: [{ model: this.app.model.Nvr, as: 'nvr', required: false }],
}],
}],
}],
order: [[ 'workstation_id', 'ASC' ], [ 'id', 'ASC' ]],
});
for (const link of links) {
const key = `${link.scannerId}|${link.channelId}`;
// 一个通道被绑到多个工作台时,取 id 最小的那个(与工作台列表的默认排序一致)
if (map.has(key)) continue;
const snapshot = this.buildSnapshot(link.workstation, link);
if (snapshot) map.set(key, snapshot);
}
return map;
}
/** 单个 (中控, 通道) 的快照(取不到返回 null) */
async snapshotFor(scannerId, channelId) {
const map = await this.snapshotMap([{ scannerId, channelId }]);
return map.get(`${scannerId}|${channelId}`) || null;
}
/**
* 把一个工作台(含摄像头绑定)压成快照对象。
*
* 实现在 `app/lib/workstation-snapshot.js` —— 补历史数据的脚本要用同一份逻辑,
* 放这里会被 `scripts/backfill-snapshot.js` 复用不了(service 需要 egg ctx)。
*/
buildSnapshot(workstation, link) {
return buildSnapshot(workstation, link);
}
/**
* 按运单号查回放计划
*
* @param {object} params
* @param {number} params.subjectId 当前主体(**只能查到本主体的运单**)
* @param {string} params.code 运单号(精确匹配)
* @return {Promise<object>} { code, found, reason, hints, records:[], streams:[] }
* - `reason`: ok / not-found(本主体没扫过)/ foreign(运单存在但属于别的主体)
* - `hints`: 给人看的说明(通道没绑工作台 / 工作台没绑摄像头 / 运单不属于本主体…)
*/
async query({ subjectId, code }) {
const barcode = String(code || '').trim();
if (!barcode) this.ctx.throw(422, '缺少运单号');
if (!subjectId) this.ctx.throw(400, '缺少主体');
const rows = await this.ScanRecord.findAll({
where: { subjectId: Number(subjectId), barcode },
include: [{ model: this.app.model.Scanner, as: 'scanner', required: false, attributes: [ 'id', 'sn', 'name' ] }],
order: [[ 'scanTime', 'ASC' ], [ 'id', 'ASC' ]],
limit: MAX_RECORDS,
});
// 老记录(没有快照)回落「当前绑定」:一次性批量取,避免逐条查询
const fallbackPairs = rows
.filter(row => !row.workstationSnapshot)
.map(row => ({ scannerId: row.scannerId, channelId: row.channelId }));
const fallbackMap = fallbackPairs.length ? await this.snapshotMap(fallbackPairs) : new Map();
const records = [];
const skipped = [];
const streams = [];
const hints = [];
for (const row of rows) {
const snapshot = row.workstationSnapshot
|| fallbackMap.get(`${row.scannerId}|${row.channelId}`)
|| null;
const snapshotMiss = !row.workstationSnapshot;
const record = row.toJSON();
// 没有工作台快照就没法算区间 → 不用去查「上/下一次扫码」(省两条 SQL)
const neighbors = snapshot ? await this.neighbors(row) : { next: null, prev: null };
const plan = this.buildPlan({
scanTime: row.scanTime,
snapshot,
nextScanTime: neighbors.next,
prevScanTime: neighbors.prev,
});
const item = {
id: Number(record.id),
barcode: record.barcode,
scanTime: record.scanTime,
reportedAt: record.reportedAt,
scannerId: Number(record.scannerId),
deviceSn: record.scanner ? record.scanner.sn : null,
deviceName: record.scanner ? record.scanner.name : null,
channelId: record.channelId,
channelName: snapshot ? snapshot.channelName : '',
workstationId: record.workstationId || (snapshot ? snapshot.workstation.id : null),
snapshotMiss,
prevScanTime: neighbors.prev,
nextScanTime: neighbors.next,
snapshot,
plan,
};
// 该通道当时没绑工作台(典型:本机在查询框里手动回车也会记一条 `DESKTOP` 记录)
// → **不进回放结果**,单独放 skipped;只要时间,其它字段对「查回放」没用
if (plan.kind === 'unknown') {
skipped.push({ scanTime: item.scanTime });
continue;
}
records.push(item);
// 给桌面端一句能直接弹给人看的说明(比只返回空数组好排查)
if (!(snapshot.cameras || []).length) {
hints.push(`记录 #${item.id} 的工作台「${snapshot.workstation.name}」没有绑定摄像头,没有可拉的回放流`);
}
for (const stream of (plan.streams || [])) streams.push(stream);
}
// `found` = 本主体扫过这个运单;`playback` = 能不能真的拉到回放
// (全部记录都没绑工作台时 found=true / playback=false,前端要区别对待)
let reason = records.length ? 'ok' : (rows.length ? 'no-workstation' : 'not-found');
if (rows.length && !records.length) {
// 只有「全都没绑工作台」才需要一句话说明,零星几条不用逐条啰嗦
hints.push('这些扫码记录当时都没有绑定工作台,无法确定要拉哪路视频');
}
if (!rows.length) {
const other = await this.ScanRecord.findOne({
where: { barcode },
attributes: [ 'id' ],
});
if (other) {
reason = 'foreign';
hints.push('这个运单号存在,但不属于当前主体,换个主体再查');
} else {
hints.push('没有任何扫码记录;确认这个运单号是不是本系统扫出来的');
}
}
return {
code: barcode,
found: rows.length > 0,
playback: records.length > 0,
reason,
hints,
records,
// 扫过但当时没绑工作台(无法计算回放区间),只回时间,桌面端直接显示「工作台:无」
skipped,
// 拍平 + 去重(同一摄像头在多次记录里会重复)
streams: this.dedupStreams(streams),
};
}
/** 同通道(同中控)相邻的扫码时间 —— 散单要用来卡「下一次打包开始时间」 */
async neighbors(row) {
const base = { scannerId: row.scannerId, channelId: row.channelId };
const [ next ] = await this.ScanRecord.findAll({
where: { ...base, scanTime: { [Op.gt]: row.scanTime } },
order: [[ 'scanTime', 'ASC' ], [ 'id', 'ASC' ]],
limit: 1,
attributes: [ 'scanTime' ],
});
const [ prev ] = await this.ScanRecord.findAll({
where: { ...base, scanTime: { [Op.lt]: row.scanTime } },
order: [[ 'scanTime', 'DESC' ], [ 'id', 'DESC' ]],
limit: 1,
attributes: [ 'scanTime' ],
});
return {
next: next ? next.scanTime : null,
prev: prev ? prev.scanTime : null,
};
}
/**
* 算这一条扫码要查的回放区间
*
* - 团购:`[scanTime - before, scanTime + after]`
* - 散单:`[scanTime - before, min(nextScanTime, scanTime + maxSec) + after]`
* (扫码 = 本次任务开始;下一次扫码 = 本次任务结束;没有下一条就按最大时长兜底)
*/
buildPlan({ scanTime, snapshot, nextScanTime, prevScanTime }) {
if (!snapshot || !snapshot.workstation) {
return {
kind: 'unknown',
reason: '这条扫码记录没有关联工作台(当时该通道没绑定工作台),无法确定要拉哪路视频',
startTime: null,
endTime: null,
durationSec: 0,
streams: [],
};
}
const ws = snapshot.workstation;
const before = asInt(ws.recordBeforeSec, 60);
const after = asInt(ws.recordAfterSec, 60);
const maxSec = Math.max(asInt(ws.recordMaxSec, 240), 1);
let kind;
let taskStart;
let taskEnd;
if (asInt(ws.wsType, 1) === 2) {
kind = 'group';
taskStart = plusSeconds(scanTime, -before);
taskEnd = plusSeconds(scanTime, after);
} else {
kind = 'scatter';
taskStart = scanTime;
// 下一次打包开始 = 本次任务结束;没有就按最大录制时长兜底
taskEnd = nextScanTime && nextScanTime > scanTime
? nextScanTime
: plusSeconds(scanTime, maxSec);
// 「下一个打包开始时间 - 当前开始时间」超过最大录制时长就截断
if (secondsBetween(taskStart, taskEnd) > maxSec) {
taskEnd = plusSeconds(taskStart, maxSec);
}
// 前后各留现场配置的延迟/余量
taskStart = plusSeconds(taskStart, -before);
taskEnd = plusSeconds(taskEnd, after);
}
const durationSec = Math.max(secondsBetween(taskStart, taskEnd), 0);
const streams = (snapshot.cameras || []).map(camera => ({
nvrId: camera.nvrId,
nvrName: camera.nvrName,
nvrHost: camera.nvrHost,
nvrPort: camera.nvrPort,
nvrUsername: camera.nvrUsername,
channelNo: camera.channelNo,
cameraId: camera.cameraId,
cameraName: camera.cameraName,
streamType: camera.streamType,
layout: camera.layout,
// 画布尺寸跟着走:多路下载后要合并时,按这个尺寸 + layout 摆位置
canvasWidth: ws.canvasWidth,
canvasHeight: ws.canvasHeight,
startTime: taskStart,
endTime: taskEnd,
durationSec,
}));
return {
kind,
startTime: taskStart,
endTime: taskEnd,
durationSec,
recordBeforeSec: before,
recordAfterSec: after,
recordMaxSec: maxSec,
prevScanTime: prevScanTime || null,
nextScanTime: nextScanTime || null,
canvasWidth: ws.canvasWidth,
canvasHeight: ws.canvasHeight,
streams,
};
}
/** 同一路流(同录像机 + 同通道 + 同时间段)只留一份,避免重复拉 */
dedupStreams(streams) {
const map = new Map();
for (const stream of streams) {
const key = [
stream.nvrId, stream.channelNo, stream.streamType,
stream.startTime instanceof Date ? stream.startTime.getTime() : stream.startTime,
stream.endTime instanceof Date ? stream.endTime.getTime() : stream.endTime,
].join('|');
if (!map.has(key)) map.set(key, stream);
}
return [ ...map.values() ];
}
}
module.exports = PackService;

View File

@ -49,13 +49,13 @@ class PasswordResetService extends Service {
/** Redis 不可用时给友好提示,而不是让页面 500 */
unavailable() {
return { ok: false, message: '重置密码服务暂不可用(Redis 未就绪),请稍后再试' };
return { ok: false, reason: 'unavailable', message: '重置密码服务暂不可用(Redis 未就绪),请稍后再试' };
}
/**
* 生成重置链接并发送邮件(同一个用户只保留最新一条链接,旧链接立即失效)
* @param {object} user 用户实例(需要 id / email)
* @param {string} origin 站点地址(如 http://127.0.0.1:7001)
* @param {string} origin 站点地址(如 http://127.0.0.1:7300)
* @return {Promise<{ok:boolean, message?:string, devMode?:boolean, url?:string}>}
*/
async send(user, origin) {
@ -68,7 +68,11 @@ class PasswordResetService extends Service {
// 重发节流:同一用户 resendInterval 秒内只发一次
locked = await this.redis.set(this.sentKey(user.id), '1', 'EX', this.cfg.resendInterval, 'NX');
if (locked !== 'OK') {
return { ok: false, message: `重置链接已发送,请 ${this.cfg.resendInterval} 秒后再试` };
return {
ok: false,
reason: 'throttled',
message: `重置链接已发送,请 ${this.cfg.resendInterval} 秒后再试`,
};
}
// 先把旧链接作废,再写新链接
@ -87,7 +91,7 @@ class PasswordResetService extends Service {
if (mail.failed) {
// 发信失败:把令牌撤掉并放开节流位,用户改完邮箱/稍后可立即重试
await this.redis.del(this.tokenKey(token), this.userKey(user.id), this.sentKey(user.id)).catch(() => {});
return { ok: false, message: '邮件发送失败,请稍后再试' };
return { ok: false, reason: 'mail', message: '邮件发送失败,请稍后再试' };
}
this.ctx.logger.info('[reset] 重置链接已生成 user=%s email=%s', user.id, user.email);

View File

@ -10,12 +10,39 @@ const MAX_CHANNEL_ID = 64;
const MAX_CHANNEL_NAME = 128;
const MAX_BARCODE = 255;
/**
* 同一个运单号的**合并窗口**(现场要求:24 小时)。
*
* 现场场景:面单在扫码器上停留很久(操作员还没把面单贴到包裹上),
* 连续扫描模式会反复扫到同一个码。以前是「首次扫描即上报、24 小时内再扫直接丢弃」,
* 结果回放时间取的是**第一次**扫到的时间,包裹真正离开扫码器的时间反而丢了。
*
* 现在的规则:同一运单 24 小时内**只保留一条记录**(跨通道也算),
* 后面上报的扫描时间如果更新,就**覆盖**这条记录的 `scan_time` 与工作台快照;
* 只有比库里更旧的上报(乱序/重试)才忽略。超过 24 小时再扫,算一次新的上报。
*/
const REPEAT_WINDOW_MS = 24 * 60 * 60 * 1000;
/** 去掉首尾空白并把非字符串转成字符串 */
function text(value) {
if (value === undefined || value === null) return '';
return String(value).trim();
}
/**
* 条码清洗:去首尾空白,再削掉首尾**非字母数字**的垃圾字符。
*
* 现场踩过:设备每 ~0.7s 推一帧 `04 D0 00 00 FF 2C`,最后一个字节 0x2C 是 `,`,
* 会粘在紧接着的条码前面,落库就成了 `,6901028011778`。
* 条码本体不会以逗号/空格开头结尾,所以首尾非字母数字一律削掉(**中间的不动**,
* GS1 里 `(01)`、`-`、`/` 这些还可能出现在内部)。
*/
function cleanBarcode(value) {
const raw = text(value);
if (!raw) return '';
return raw.replace(/^[^0-9A-Za-z]+/, '').replace(/[^0-9A-Za-z]+$/, '');
}
/**
* 解析扫描时间,统一截断到秒(去重键的一部分)
*
@ -150,6 +177,7 @@ class ScanService extends Service {
} else {
const instance = await this.ScanChannel.create({
scannerId: scanner.id,
subjectId: scanner.subjectId || null,
channelId: row.channelId,
channelName: row.channelName,
lastReportAt: now,
@ -174,13 +202,17 @@ class ScanService extends Service {
/**
* 中控上报扫码结果:条码 + 扫描时间 + 通道 id
*
* 去重:同一中控 + 同一通道 + 同一时间(秒) + 同一条码 只入库一次,
* 重复上报不报错,返回 { inserted, duplicated }。
* 去重分两层:
* 1. 完全相同的上报(同一中控 + 通道 + 时间(秒) + 条码)只入库一次 → 计入 `duplicated`;
* 2. **同一运单号 24 小时内只保留一条**(跨通道也算):
* - 本次扫描时间比库里那条新 → **覆盖** `scan_time` / 工作台快照 / 通道 → 计入 `updated`;
* - 本次扫描时间比库里那条旧(乱序/重试)→ 忽略 → 计入 `suppressed`。
* 重复上报不报错。
* 顺带:刷新通道的最近上报时间(未知通道自动补一条,通道名留空)、刷新中控心跳。
*
* @param {object} scanner 中控(扫描器实例)
* @param {Array} records 形如 [{ barcode, scanTime, channelId }]
* @return {Promise<object>} { received, inserted, duplicated, invalid, errors, unknownChannels }
* @return {Promise<object>} { received, inserted, updated, duplicated, suppressed, invalid, errors, unknownChannels }
*/
async ingest(scanner, records) {
const list = Array.isArray(records) ? records : [];
@ -194,7 +226,7 @@ class ScanService extends Service {
list.forEach((raw, index) => {
const item = raw && typeof raw === 'object' ? raw : {};
const barcode = text(item.barcode || item.code);
const barcode = cleanBarcode(item.barcode || item.code);
const channelId = text(item.channelId || item.channel_id);
const scanTime = parseScanTime(item.scanTime || item.scan_time || item.time);
@ -219,7 +251,7 @@ class ScanService extends Service {
return;
}
const row = { scannerId: scanner.id, channelId, barcode, scanTime, reportedAt: now };
const row = { scannerId: scanner.id, subjectId: scanner.subjectId || null, channelId, barcode, scanTime, reportedAt: now };
// 同一批里完全相同的上报只留一条
const key = dedupKey(row);
if (seen.has(key)) return;
@ -230,16 +262,48 @@ class ScanService extends Service {
const result = {
received: list.length,
inserted: 0,
duplicated: list.length - errors.length - rows.length, // 同一批内的重复条数
// 同一运单已有记录,本次扫描时间更新 → 覆盖那条记录
updated: 0,
// 同一批内完全相同的上报
duplicated: list.length - errors.length - rows.length,
// 比库里已有记录更旧的重复上报(乱序/重试),不覆盖
suppressed: 0,
invalid: errors.length,
errors,
unknownChannels: [],
};
if (!rows.length) return result;
const fresh = await this.filterExisting(rows);
let fresh = await this.filterExisting(rows);
result.duplicated += rows.length - fresh.length;
// 入库/覆盖前把「当时的工作台」冻成快照:回放要按当时的录像机/摄像头/布局/录制范围拉流,
// 工作台后来被改过、删掉了,历史运单照样能查回来。
if (fresh.length) {
try {
const pairs = fresh.map(row => ({ scannerId: row.scannerId, channelId: row.channelId }));
const snapshots = await this.ctx.service.pack.snapshotMap(pairs);
for (const row of fresh) {
const snapshot = snapshots.get(`${row.scannerId}|${row.channelId}`);
if (!snapshot) continue;
row.workstationId = snapshot.workstation.id;
row.workstationSnapshot = snapshot;
}
} catch (err) {
// 快照失败不能影响扫码入库本身(少个快照顶多查回放时提示"没有工作台信息")
this.ctx.logger.warn('[scan] 生成工作台快照失败:%s', err.message);
}
}
// 24 小时合并规则:同一运单只留一条,时间以**最后一次扫描**为准
if (fresh.length) {
const merged = await this.mergeExisting(fresh, scanner);
result.updated += merged.updated;
result.suppressed += merged.stale;
fresh = merged.kept;
}
if (fresh.length) {
try {
await this.ScanRecord.bulkCreate(fresh);
@ -265,8 +329,8 @@ class ScanService extends Service {
await this.ctx.service.scanner.heartbeat(scanner, this.ctx.ip);
this.ctx.logger.info(
'[scan] 扫码上报 %s: 收到 %d / 入库 %d / 去重 %d / 非法 %d',
scanner.sn, result.received, result.inserted, result.duplicated, result.invalid,
'[scan] 扫码上报 %s: 收到 %d / 入库 %d / 覆盖 %d / 去重 %d / 旧上报 %d / 非法 %d',
scanner.sn, result.received, result.inserted, result.updated, result.duplicated, result.suppressed, result.invalid,
);
if (result.unknownChannels.length) {
this.ctx.logger.warn('[scan] %s 上报了未登记的通道: %s', scanner.sn, result.unknownChannels.join(', '));
@ -301,6 +365,108 @@ class ScanService extends Service {
return rows.filter(row => !existingKeys.has(dedupKey(row)));
}
/**
* 同一运单 24 小时内只保留一条记录,时间以**最后一次扫描**为准。
*
* 规则:
* - 同一运单号(**主体内**,跨中控/通道都算)24 小时内只留一条;
* - 库里已有记录、且本次扫描时间更新 → **覆盖** `scan_time` / 通道 / 工作台快照 → 计入 `updated`;
* - 本次扫描时间比库里那条旧(乱序上报、重试)→ 忽略,避免把时间改回过去 → 计入 `stale`;
* - 同一批里同一运单出现多次 → 只留**最晚**的一条,其余忽略;
* - 距上一条超过 24 小时 → 算新的上报,正常入库。
*
* @param {Array} rows 已通过精确去重、且已带好工作台快照的待入库行
* @param {object} scanner 当前中控
* @return {Promise<{ kept: Array, updated: number, stale: number }>}
*/
async mergeExisting(rows, scanner) {
if (!rows.length) return { kept: rows, updated: 0, stale: 0 };
const barcodes = [ ...new Set(rows.map(row => row.barcode)) ];
const times = rows.map(row => row.scanTime.getTime());
const from = new Date(Math.min(...times) - REPEAT_WINDOW_MS);
const to = new Date(Math.max(...times) + REPEAT_WINDOW_MS);
// 主体内按运单号判断;老数据没有 subject_id 时退回「同一中控」
const scope = scanner.subjectId
? { subjectId: Number(scanner.subjectId) }
: { scannerId: Number(scanner.id) };
const existing = await this.ScanRecord.findAll({
attributes: [ 'id', 'barcode', 'scanTime' ],
where: Object.assign({}, scope, {
barcode: { [Op.in]: barcodes },
scanTime: { [Op.between]: [ from, to ] },
}),
raw: true,
});
// barcode -> 库里最近的一条 { id, at }
const latest = new Map();
for (const row of existing) {
const at = new Date(row.scanTime).getTime();
const current = latest.get(row.barcode);
if (!current || at > current.at) latest.set(row.barcode, { id: Number(row.id), at });
}
// 同一批里同一运单只保留最晚的一条
const groups = new Map();
for (const row of rows) {
if (!groups.has(row.barcode)) groups.set(row.barcode, []);
groups.get(row.barcode).push(row);
}
const kept = [];
let updated = 0;
let stale = 0;
for (const [ barcode, list ] of groups) {
list.sort((a, b) => a.scanTime.getTime() - b.scanTime.getTime());
const last = list[list.length - 1];
const hit = latest.get(barcode);
if (!hit) {
// 库里没有:只入库最晚的一条,同批更早的扫描被它覆盖
kept.push(last);
stale += list.length - 1;
continue;
}
if (last.scanTime.getTime() <= hit.at) {
// 比库里已有的还旧:不回退扫描时间
stale += list.length;
continue;
}
const fields = {
scannerId: last.scannerId,
channelId: last.channelId,
scanTime: last.scanTime,
reportedAt: last.reportedAt,
};
// 快照/主体取得到才覆盖,取不到就保留库里原来的(别因为临时解绑把历史回放弄丢)
if (last.subjectId) fields.subjectId = last.subjectId;
if (last.workstationId) fields.workstationId = last.workstationId;
if (last.workstationSnapshot) fields.workstationSnapshot = last.workstationSnapshot;
try {
await this.ScanRecord.update(fields, { where: { id: hit.id } });
hit.at = last.scanTime.getTime();
updated++;
stale += list.length - 1;
} catch (err) {
if (!isDuplicateError(err)) throw err;
// 并发的另一条上报先把唯一键占住了:以已存在的那条为准
stale += list.length;
}
}
if (updated) {
this.ctx.logger.info('[scan] %s 有 %d 条扫码把已有记录覆盖为最新扫描时间', scanner.sn, updated);
}
return { kept, updated, stale };
}
/**
* 刷新通道的最近上报时间;未登记的通道自动补一条(通道名留空)
* @return {Promise<Array<string>>} 自动补建的通道 id
@ -336,12 +502,14 @@ class ScanService extends Service {
}
/** 通道列表(分页;可按中控 / 关键字过滤),带所属中控 */
async listChannels({ page = 1, pageSize = 20, scannerId, keyword, status } = {}) {
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 200);
async listChannels({ page = 1, pageSize = 20, scannerId, scannerIds, subjectId, keyword, status } = {}) {
const size = Math.min(Number(pageSize) || 20, 100);
const current = Math.max(Number(page) || 1, 1);
const where = {};
if (scannerId) where.scannerId = Number(scannerId);
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
if (subjectId) where.subjectId = Number(subjectId);
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
if (keyword) {
where[Op.or] = [
@ -371,13 +539,14 @@ class ScanService extends Service {
* @param {object} params { page, pageSize, scannerId 单个中控, scannerIds 多个中控(用户端按「我的设备」过滤用),
* channelId, barcode, startTime, endTime }
*/
async listRecords({ page = 1, pageSize = 20, scannerId, scannerIds, channelId, barcode, startTime, endTime } = {}) {
async listRecords({ page = 1, pageSize = 20, scannerId, scannerIds, subjectId, channelId, barcode, startTime, endTime } = {}) {
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 200);
const current = Math.max(Number(page) || 1, 1);
const where = {};
if (scannerId) where.scannerId = Number(scannerId);
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
if (subjectId) where.subjectId = Number(subjectId);
if (channelId) where.channelId = channelId;
if (barcode) where.barcode = { [Op.like]: `%${barcode}%` };
@ -409,14 +578,16 @@ class ScanService extends Service {
* 通道数(首页统计用)
* @param {object} where 普通条件;或 `{ scannerIds: [1,2] }` 限定这几个中控(用户端统计用)
*/
async countChannels({ scannerIds, ...where } = {}) {
async countChannels({ scannerIds, subjectId, ...where } = {}) {
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
if (subjectId) where.subjectId = Number(subjectId);
return this.ScanChannel.count({ where });
}
/** 扫码记录数(首页统计用;`{ scannerIds }` 限定中控,同 countChannels) */
async countRecords({ scannerIds, ...where } = {}) {
async countRecords({ scannerIds, subjectId, ...where } = {}) {
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
if (subjectId) where.subjectId = Number(subjectId);
return this.ScanRecord.count({ where });
}

View File

@ -13,8 +13,8 @@ const crypto = require('crypto');
* 不再有「sn + secret 注册 / 登录」那套入口(`secret_hash` 列作为历史字段保留,不再写入)。
*/
/** 列表/详情默认不返回历史密钥字段与令牌标识 */
const SAFE_ATTRIBUTES = { exclude: [ 'secretHash', 'tokenJti' ] };
/** 列表/详情默认不返回历史密钥字段、令牌标识与刷新令牌摘要 */
const SAFE_ATTRIBUTES = { exclude: [ 'secretHash', 'tokenJti', 'refreshTokenHash' ] };
/** 关联用户时只带这几个展示字段 */
const USER_ATTRIBUTES = [ 'id', 'username', 'nickname' ];
@ -24,10 +24,13 @@ const USER_ATTRIBUTES = [ 'id', 'username', 'nickname' ];
*/
function sanitize(row) {
if (!row) return row;
const { secretHash, tokenJti, ...rest } = row;
const { secretHash, tokenJti, refreshTokenHash, refreshExpiresAt, ...rest } = row;
return rest;
}
/** 刷新令牌只存摘要(不存原文) */
function sha256(text) {
return crypto.createHash('sha256').update(String(text)).digest('hex');
}
class ScannerService extends Service {
get Scanner() {
return this.app.model.Scanner;
@ -48,9 +51,23 @@ class ScannerService extends Service {
* userId 确认登录的用户, ip?, expiresIn? 令牌有效期(秒数,不传用 config.jwt.deviceExpiresIn) }
* @return {Promise<object>} 扫描器信息 + token(JWT) + firstTime(本次是否新建记录)
*/
async loginByScan({ sn, name, vendor, model, firmware, userId, ip, expiresIn } = {}) {
async loginByScan({ sn, name, vendor, model, firmware, userId, subjectId, ip, expiresIn } = {}) {
if (!userId) this.ctx.throw(401, '缺少确认登录的用户');
// 设备没有「当前主体」概念:调用方不指定时,用它所属用户的默认主体
let finalSubjectId = subjectId ? Number(subjectId) : null;
if (finalSubjectId) {
// 指定的主体必须「确认人是成员」,否则退回默认主体(不报错,免得设备卡死)
const allowed = await this.ctx.service.subject
.findForUser(finalSubjectId, userId)
.then(() => true)
.catch(() => false);
if (!allowed) finalSubjectId = null;
}
if (!finalSubjectId) {
finalSubjectId = await this.ctx.service.subject.defaultSubjectId(userId);
}
const finalSn = String(sn || '').trim() || `DEV-${crypto.randomBytes(6).toString('hex').toUpperCase()}`;
const include = [{ model: this.app.model.User, as: 'user', required: false, attributes: USER_ATTRIBUTES }];
@ -63,6 +80,7 @@ class ScannerService extends Service {
});
const payload = { userId: Number(userId), lastLoginAt: new Date(), lastSeenAt: new Date() };
if (finalSubjectId) payload.subjectId = Number(finalSubjectId);
if (ip) payload.ip = ip;
if (name) payload.name = name;
if (vendor) payload.vendor = vendor;
@ -78,6 +96,8 @@ class ScannerService extends Service {
this.ctx.logger.warn('[scanner] %s 已被用户 %s 绑定,拒绝用户 %s 的扫码登录', finalSn, existing.userId, userId);
this.ctx.throw(403, `扫描器 ${finalSn} 已绑定到其他账号,请先在原账号里解绑`);
}
// 设备已在其他主体里(且本次没指定主体):保持原主体,不跟着确认人乱跳
if (existing.subjectId && !subjectId) delete payload.subjectId;
if (Number(existing.status) !== 1) this.ctx.throw(403, '扫描器已被禁用');
if (existing.deletedAt) await existing.restore(); // 曾被删除 → 复活
@ -93,16 +113,118 @@ class ScannerService extends Service {
}
const token = await this.issueToken(scanner, { expiresIn });
const refresh = await this.issueRefresh(scanner);
this.ctx.logger.info('[scanner] %s 扫码登录成功(%s,归属用户 %s)',
finalSn, firstTime ? '首次注册' : '已存在', userId);
return Object.assign(sanitize(scanner.toJSON()), {
token,
tokenType: 'Bearer',
refreshToken: refresh.token,
refreshExpiresIn: refresh.expiresIn,
refreshExpiresAt: refresh.expiresAt,
firstTime,
});
}
/**
* 桌面端「开启设备服务」:把本机注册成当前主体**唯一**的一台设备
*
* - **一个主体只允许一台设备在线**:同主体下的其他设备一律「踢下线」(轮换 jti → 旧 JWT 立即 401)
* - 同一个 SN 重复开启只是换发令牌(不是新建记录)
* - 调用方(controller)负责先校验「当前用户是该主体管理员」
*
* @param {object} params { subjectId, userId, sn?, name?, vendor?, model? }
* @return {Promise<object>} { device, token, tokenType, expiresIn, kicked }
*/
async activateForSubject({ subjectId, userId, sn, name, vendor, model } = {}) {
if (!subjectId) this.ctx.throw(400, '缺少主体');
if (!userId) this.ctx.throw(401, '缺少用户身份');
const finalSn = String(sn || '').trim() || `PC-${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
// ① 踢掉同主体下的其他设备:轮换 jti,旧令牌立刻失效
const others = await this.Scanner.findAll({
attributes: [ 'id', 'sn', 'name' ],
where: { subjectId: Number(subjectId), sn: { [Op.ne]: finalSn } },
raw: true,
});
for (const row of others) {
await this.Scanner.update({
tokenJti: crypto.randomUUID(),
refreshTokenHash: null,
refreshExpiresAt: null,
}, { where: { id: row.id } });
}
// ② 本机设备:同 SN 复用(含软删的),否则新建
const existing = await this.Scanner.findOne({
where: { sn: finalSn },
attributes: SAFE_ATTRIBUTES,
paranoid: false,
});
const fields = {
subjectId: Number(subjectId),
userId: Number(userId),
lastLoginAt: new Date(),
lastSeenAt: new Date(),
status: 1,
};
if (name) fields.name = String(name).slice(0, 64);
if (vendor) fields.vendor = String(vendor).slice(0, 64);
if (model) fields.model = String(model).slice(0, 64);
let scanner;
let firstTime = false;
if (existing) {
if (existing.deletedAt) await existing.restore();
await existing.update(fields);
scanner = existing;
} else {
firstTime = true;
scanner = await this.Scanner.create(Object.assign({}, fields, {
sn: finalSn,
lastRegisterAt: new Date(),
}));
}
const token = await this.issueToken(scanner);
const refresh = await this.issueRefresh(scanner);
this.ctx.logger.info('[scanner] 主体 %s 开启设备服务:%s(%s),踢下线 %d 台',
subjectId, finalSn, firstTime ? '新建' : '复用', others.length);
return Object.assign(sanitize(scanner.toJSON()), {
token,
tokenType: 'Bearer',
refreshToken: refresh.token,
refreshExpiresIn: refresh.expiresIn,
refreshExpiresAt: refresh.expiresAt,
firstTime,
expiresIn: this.app.config.jwt.deviceExpiresIn,
kicked: others.map(row => ({ id: Number(row.id), sn: row.sn, name: row.name })),
});
}
/**
* 关闭设备服务 / 让某个设备的令牌立刻失效(轮换 jti)
* @return {Promise<boolean>} 是否命中记录
*/
async revokeToken(scannerId) {
const scanner = await this.Scanner.findByPk(scannerId);
if (!scanner) return false;
await scanner.update({
tokenJti: crypto.randomUUID(),
refreshTokenHash: null,
refreshExpiresAt: null,
lastSeenAt: new Date(),
});
this.ctx.logger.info('[scanner] 设备 %s 令牌已作废(关闭设备服务)', scanner.sn);
return true;
}
/**
* 签发长期 JWT 并把 jti 写库
* 库里不保存令牌本体,靠 jti 比对实现撤销:重签后旧令牌立即失效
@ -128,6 +250,73 @@ class ScannerService extends Service {
return this.Scanner.findByPk(id, { attributes: { include: [ 'tokenJti' ] } });
}
/**
* 签发刷新令牌(不透明随机串,库里只存 sha256)
*
* 每次签发都会轮换旧值;调用方(激活 / 刷新)负责把明文返回给设备端保存。
* @param {object} scanner 扫描器实例
* @return {Promise<{token:string, expiresIn:string|number, expiresAt:Date}>}
*/
async issueRefresh(scanner) {
const token = crypto.randomBytes(32).toString('base64url');
const spec = this.app.config.jwt.deviceRefreshExpiresIn || '730d';
const seconds = this.ctx.service.jwt.parseDuration(spec) || 63072000; // 兜底 730 天
const expiresAt = new Date(Date.now() + seconds * 1000);
await scanner.update({
refreshTokenHash: sha256(token),
refreshExpiresAt: expiresAt,
});
return { token, expiresIn: spec, expiresAt };
}
/**
* 用刷新令牌换新的访问令牌(并轮换刷新令牌)
*
* 不需要访问令牌(它可能已经过期);刷新令牌本身就是凭据。
* 校验:hash 反查记录 → 未删除 / status=1 / 刷新令牌未过期 / SN 可选比对。
* 成功后:`jti` 轮换(旧访问令牌立即失效)+ 刷新令牌轮换(旧刷新令牌立即失效)。
*
* @param {object} params { refreshToken 明文, sn? 额外校验, ip? }
* @return {Promise<object>} { sn, token, tokenType, expiresIn, refreshToken, refreshExpiresIn, refreshExpiresAt }
*/
async refreshToken({ refreshToken, sn, ip } = {}) {
const plain = String(refreshToken || '').trim();
if (!plain) this.ctx.throw(400, '缺少 refreshToken');
const scanner = await this.Scanner.findOne({
where: { refreshTokenHash: sha256(plain) },
paranoid: false,
});
if (!scanner) this.ctx.throw(401, '刷新令牌无效');
if (scanner.deletedAt) this.ctx.throw(401, '扫描器已被删除');
if (Number(scanner.status) !== 1) this.ctx.throw(403, '扫描器已被禁用');
if (sn && String(sn).trim() && scanner.sn !== String(sn).trim()) {
this.ctx.throw(401, '刷新令牌与 SN 不匹配');
}
if (!scanner.refreshExpiresAt || new Date(scanner.refreshExpiresAt).getTime() < Date.now()) {
this.ctx.throw(401, '刷新令牌已过期,请重新开启设备服务');
}
const token = await this.issueToken(scanner);
const refresh = await this.issueRefresh(scanner);
await scanner.update(Object.assign({ lastSeenAt: new Date() }, ip ? { ip } : {}));
this.ctx.logger.info('[scanner] %s 刷新令牌成功(jti 已轮换)', scanner.sn);
return {
sn: scanner.sn,
token,
tokenType: 'Bearer',
expiresIn: this.app.config.jwt.deviceExpiresIn,
refreshToken: refresh.token,
refreshExpiresIn: refresh.expiresIn,
refreshExpiresAt: refresh.expiresAt,
};
}
/**
* 用长期 JWT 换设备实例(校验链路与 `middleware/scanner_auth.js` 完全一致,实现在这里)
*
@ -200,13 +389,14 @@ class ScannerService extends Service {
return scanner ? sanitize(scanner.toJSON()) : null;
}
/** 分页列表:keyword 模糊匹配 SN / 名称 / 型号 */
async list({ page = 1, pageSize = 20, keyword, userId, status } = {}) {
/** 分页列表:keyword 模糊匹配 SN / 名称 / 型号(可按主体 / 用户过滤) */
async list({ page = 1, pageSize = 20, keyword, userId, subjectId, status } = {}) {
const size = Math.min(Number(pageSize) || 20, 100);
const current = Math.max(Number(page) || 1, 1);
const where = {};
if (userId) where.userId = Number(userId);
if (subjectId) where.subjectId = Number(subjectId);
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
if (keyword) {
where[Op.or] = [
@ -245,7 +435,21 @@ class ScannerService extends Service {
}
/**
* 某用户名下的设备 id 列表(用户端查「我的通道 / 我的记录 / 我的统计」时用来限定范围)
* 某主体下的设备 id 列表(主体端查「通道 / 记录 / 统计」时用来限定范围)
* @return {Promise<number[]>}
*/
async idsOfSubject(subjectId) {
if (!subjectId) return [];
const rows = await this.Scanner.findAll({
attributes: [ 'id' ],
where: { subjectId: Number(subjectId) },
raw: true,
});
return rows.map(row => Number(row.id));
}
/**
* 某用户名下的设备 id 列表(历史接口,主体体系上线后主体端应改用 `idsOfSubject`)
* @return {Promise<number[]>}
*/
async idsOfUser(userId) {

View File

@ -0,0 +1,484 @@
'use strict';
const { Service } = require('egg');
const crypto = require('crypto');
const { Op } = require('sequelize');
/** 绑定码字符集(去掉容易看错的 0/O/1/I) */
const CODE_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
/** 新建主体默认赠送天数(可通过 config.subject.trialDays 覆盖) */
const DEFAULT_TRIAL_DAYS = 7;
/** 成员绑定码默认有效期(秒) */
const BIND_TTL = 600;
function randomCode(length = 6) {
let out = '';
for (let i = 0; i < length; i++) {
out += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
}
return out;
}
const USER_ATTRIBUTES = [ 'id', 'username', 'nickname', 'avatar' ];
/**
* 主体(租户)service
*
* 职责:
* - 主体列表 / 创建(默认赠送 N 天)/ 修改(管理员)
* - 成员管理:列表、按姓名快速添加、删除
* - 成员微信绑定码:发码 → 手机扫码 → 登录用户确认 → 绑定该成员
* - 供中间件用的「当前用户是否属于该主体 / 主体是否过期」判断
*/
class SubjectService extends Service {
get Subject() {
return this.app.model.Subject;
}
get Member() {
return this.app.model.SubjectMember;
}
get trialDays() {
const cfg = this.app.config.subject || {};
return Number(cfg.trialDays || DEFAULT_TRIAL_DAYS);
}
get prefix() {
return (this.app.config.cache && this.app.config.cache.prefix) || 'packs:';
}
bindKey(code) {
return `${this.prefix}member:bind:${code}`;
}
/** 是否已过期(含稍后到期判断,统一用服务器时间) */
isExpired(subject) {
if (!subject || !subject.expireAt) return false;
return new Date(subject.expireAt).getTime() <= Date.now();
}
/** 主体的基础展示字段(固定输出 camelCase,避免驼峰/下划线混排) */
present(subject, extra = {}) {
return Object.assign({
id: Number(subject.id),
name: subject.name,
adminUserId: Number(subject.adminUserId),
expireAt: subject.expireAt,
status: Number(subject.status),
remark: subject.remark || null,
createdAt: subject.createdAt,
expired: this.isExpired(subject),
}, extra);
}
/**
* 当前用户能进的主体列表(含自己的角色/姓名、成员数、是否过期)
* @param {number} userId 当前登录用户
*/
async listForUser(userId) {
const members = await this.Member.findAll({
where: { userId: Number(userId), status: 1 },
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (!members.length) return [];
const ids = members.map(item => Number(item.subjectId));
const subjects = await this.Subject.findAll({
where: { id: { [Op.in]: ids } },
order: [[ 'id', 'ASC' ]],
});
const byId = new Map(subjects.map(row => [ Number(row.id), row ]));
const counts = await this.Member.count({
where: { subjectId: { [Op.in]: ids }, status: 1 },
group: [ 'subject_id' ],
raw: true,
}).catch(() => []);
const countMap = new Map((counts || []).map(row => [ Number(row.subjectId || row.subject_id), row.count ]));
const list = [];
for (const member of members) {
const subject = byId.get(Number(member.subjectId));
if (!subject) continue; // 主体被删除
list.push(this.present(subject, {
role: Number(member.role),
memberName: member.name,
memberId: Number(member.id),
memberCount: countMap.get(Number(subject.id)) || 0,
}));
}
// 可用的主体排前面,同组按 id
list.sort((a, b) => (a.expired === b.expired ? a.id - b.id : (a.expired ? 1 : -1)));
return list;
}
/** 该用户在主体里的成员记录(没加入返回 null) */
async memberOf(subjectId, userId) {
if (!subjectId || !userId) return null;
return this.Member.findOne({
where: { subjectId: Number(subjectId), userId: Number(userId), status: 1 },
});
}
/**
* 取「当前用户可用」的主体(不存在 / 不是成员 → 404)
* 中间件也用它做范围校验
*/
async findForUser(subjectId, userId) {
const id = Number(subjectId);
if (!Number.isInteger(id) || id <= 0) this.ctx.throw(400, '缺少主体 id');
const member = await this.memberOf(id, userId);
if (!member) this.ctx.throw(404, '主体不存在或你不是该主体的成员');
const subject = await this.Subject.findByPk(id);
if (!subject) this.ctx.throw(404, '主体不存在或你不是该主体的成员');
return { subject, member };
}
/** 管理员校验(只有主体管理员能改主体信息 / 增删成员) */
async ensureAdmin(subjectId, userId) {
const found = await this.findForUser(subjectId, userId);
const isAdmin = Number(found.subject.adminUserId) === Number(userId) || Number(found.member.role) === 1;
if (!isAdmin) this.ctx.throw(403, '只有主体管理员可以执行该操作');
return found;
}
/**
* 创建主体
*
* - 管理员默认就是创建人
* - 使用期限默认**赠送 7 天**(`config.subject.trialDays`)
* - 创建人自动成为管理员成员(姓名取昵称 / 用户名)
*
* @param {object} params { userId, name, days?, remark? }
*/
async create({ userId, name, days, remark } = {}) {
if (!userId) this.ctx.throw(401, '缺少用户身份');
const finalName = String(name || '').trim();
if (!finalName) this.ctx.throw(422, '主体名称不能为空');
if (finalName.length > 64) this.ctx.throw(422, '主体名称不能超过 64 个字符');
const grantDays = days === undefined || days === null || days === ''
? this.trialDays
: Number(days);
if (!Number.isFinite(grantDays) || grantDays <= 0 || grantDays > 3650) {
this.ctx.throw(422, '使用天数必须在 1~3650 之间');
}
const expireAt = new Date(Date.now() + Math.round(grantDays) * 24 * 3600 * 1000);
const subject = await this.Subject.create({
name: finalName,
adminUserId: Number(userId),
expireAt,
status: 1,
remark: remark || null,
});
const user = await this.app.model.User.findByPk(Number(userId), { attributes: USER_ATTRIBUTES });
const memberName = (user && (user.nickname || user.username)) || `用户${userId}`;
await this.Member.create({
subjectId: Number(subject.id),
userId: Number(userId),
name: String(memberName).slice(0, 32),
role: 1,
boundAt: new Date(),
status: 1,
});
this.ctx.logger.info('[subject] 用户 %s 创建主体 %s(%s,到期 %s)',
userId, subject.id, finalName, expireAt.toISOString());
return this.present(subject, {
role: 1,
memberName,
memberCount: 1,
});
}
/**
* 修改主体(管理员):名称 / 备注 / 续期
* @param {object} patch { name?, remark?, extendDays? }
*/
async update(subjectId, userId, patch = {}) {
const { subject } = await this.ensureAdmin(subjectId, userId);
const fields = {};
if (patch.name !== undefined) {
const next = String(patch.name || '').trim();
if (!next) this.ctx.throw(422, '主体名称不能为空');
fields.name = next.slice(0, 64);
}
if (patch.remark !== undefined) fields.remark = patch.remark;
if (patch.status !== undefined) fields.status = Number(patch.status) === 0 ? 0 : 1;
if (patch.extendDays !== undefined && patch.extendDays !== null && patch.extendDays !== '') {
const days = Number(patch.extendDays);
if (!Number.isFinite(days) || days <= 0 || days > 3650) this.ctx.throw(422, '续期天数必须在 1~3650 之间');
// 已过期:从现在开始算;未过期:在原到期时间上顺延
const base = this.isExpired(subject) ? Date.now() : new Date(subject.expireAt).getTime();
fields.expireAt = new Date(base + Math.round(days) * 24 * 3600 * 1000);
}
await subject.update(fields);
const member = await this.memberOf(subject.id, userId);
return this.present(subject, {
role: member ? Number(member.role) : 2,
memberName: member ? member.name : null,
});
}
/** 成员列表(带账号信息) */
async members(subjectId, userId) {
await this.findForUser(subjectId, userId);
const rows = await this.Member.findAll({
where: { subjectId: Number(subjectId) },
order: [[ 'role', 'ASC' ], [ 'id', 'ASC' ]],
include: [{ model: this.app.model.User, as: 'user', required: false, attributes: USER_ATTRIBUTES }],
});
return rows.map(row => {
const data = row.toJSON();
return {
id: Number(data.id),
name: data.name,
role: Number(data.role),
status: Number(data.status),
userId: data.userId ? Number(data.userId) : null,
boundAt: data.boundAt,
wechatBound: Boolean(data.wechatOpenid),
user: data.user || null,
createdAt: data.createdAt,
};
});
}
/**
* 按姓名快速添加成员(先只建成员,账号/微信稍后用绑定码绑定)
* @param {object} params { subjectId, userId 操作人, name, role? }
*/
async addMember({ subjectId, userId, name, role } = {}) {
await this.findForUser(subjectId, userId);
const finalName = String(name || '').trim();
if (!finalName) this.ctx.throw(422, '成员姓名不能为空');
if (finalName.length > 32) this.ctx.throw(422, '成员姓名不能超过 32 个字符');
const duplicated = await this.Member.findOne({
where: { subjectId: Number(subjectId), name: finalName, userId: null },
});
if (duplicated) this.ctx.throw(409, `已存在同名且未绑定的成员「${finalName}」`);
const created = await this.Member.create({
subjectId: Number(subjectId),
userId: null,
name: finalName,
role: Number(role) === 1 ? 1 : 2,
status: 1,
});
this.ctx.logger.info('[subject] 用户 %s 在主体 %s 添加成员「%s」', userId, subjectId, finalName);
return {
id: Number(created.id),
name: created.name,
role: Number(created.role),
status: Number(created.status),
userId: null,
boundAt: null,
wechatBound: false,
user: null,
createdAt: created.createdAt,
};
}
/** 删除成员(不能删管理员,也不能删自己) */
async removeMember({ subjectId, operatorUserId, memberId } = {}) {
await this.findForUser(subjectId, operatorUserId);
const member = await this.Member.findOne({
where: { id: Number(memberId), subjectId: Number(subjectId) },
});
if (!member) this.ctx.throw(404, '成员不存在');
const subject = await this.Subject.findByPk(Number(subjectId));
if (subject && Number(subject.adminUserId) === Number(member.userId)) {
this.ctx.throw(422, '不能删除主体管理员');
}
if (Number(member.userId) === Number(operatorUserId)) {
this.ctx.throw(422, '不能删除自己');
}
await member.destroy();
this.ctx.logger.info('[subject] 用户 %s 从主体 %s 移除成员「%s」', operatorUserId, subjectId, member.name);
return { id: Number(member.id) };
}
/**
* 给「未绑定账号/微信」的成员生成绑定码
*
* 手机扫码后打开前端 `/wechat?bind=<码>`,已登录的账号点确认即可完成绑定。
* @return {Promise<object>} { code, bindUrl, qrUrl, expiresIn }
*/
async createBindCode({ subjectId, memberId, operatorUserId } = {}) {
const { subject } = await this.findForUser(subjectId, operatorUserId);
const member = await this.Member.findOne({
where: { id: Number(memberId), subjectId: Number(subjectId) },
});
if (!member) this.ctx.throw(404, '成员不存在');
if (member.userId) this.ctx.throw(409, '该成员已绑定账号,如需换绑请先解绑');
const code = randomCode(6);
const payload = JSON.stringify({
status: 'pending',
subjectId: Number(subjectId),
subjectName: subject.name,
memberId: Number(memberId),
name: member.name,
});
await this.app.redis.setex(this.bindKey(code), BIND_TTL, payload);
const origin = this.app.config.email.siteUrl || this.ctx.origin;
const bindUrl = `${String(origin).replace(/\/+$/, '')}/wechat?bind=${encodeURIComponent(code)}`;
return {
code,
memberId: Number(memberId),
memberName: member.name,
bindUrl,
qrUrl: `/api/wechat/qrcode.svg?code=${encodeURIComponent(code)}&mode=member`,
expiresIn: BIND_TTL,
};
}
/** 绑定码状态(扫码页轮询) */
async bindStatus(code) {
const normalized = String(code || '').trim().toUpperCase();
if (!normalized) return { status: 'bad_format' };
const raw = await this.app.redis.get(this.bindKey(normalized));
if (!raw) return { status: 'expired' };
let data = null;
try {
data = JSON.parse(raw);
} catch (err) {
return { status: 'expired' };
}
return {
status: data.status || 'pending',
code: normalized,
subjectId: data.subjectId,
memberId: data.memberId,
memberName: data.name,
subjectName: data.subjectName,
boundName: data.boundName,
};
}
/**
* 手机侧确认绑定:把当前登录账号绑到该成员上
*
* @param {string} code 绑定码
* @param {number} userId 当前登录用户(手机端已登录)
*/
async confirmBind(code, userId) {
const normalized = String(code || '').trim().toUpperCase();
if (!normalized || !userId) {
return { ok: false, reason: 'bad_param', message: '参数不完整' };
}
const raw = await this.app.redis.get(this.bindKey(normalized));
if (!raw) return { ok: false, reason: 'expired', message: '绑定码已失效,请让管理员重新生成' };
let data = null;
try {
data = JSON.parse(raw);
} catch (err) {
return { ok: false, reason: 'expired', message: '绑定码已失效,请让管理员重新生成' };
}
if (data.status === 'confirmed') return { ok: false, reason: 'used', message: '该绑定码已被使用' };
const subject = await this.Subject.findByPk(Number(data.subjectId));
if (!subject) return { ok: false, reason: 'expired', message: '主体已不存在' };
const member = await this.Member.findByPk(Number(data.memberId));
if (!member) return { ok: false, reason: 'expired', message: '成员已不存在' };
if (member.userId && Number(member.userId) !== Number(userId)) {
return { ok: false, reason: 'bound', message: '该成员已绑定其他账号' };
}
// 同一主体下,一个账号只能有一条成员记录
const mine = await this.memberOf(subject.id, userId);
if (mine && Number(mine.id) !== Number(member.id)) {
return { ok: false, reason: 'joined', message: '你已经是该主体的成员了' };
}
let openid = null;
try {
const wechat = await this.app.model.WechatOauth.findOne({
where: { userId: Number(userId) },
order: [[ 'id', 'DESC' ]],
attributes: [ 'openid' ],
});
openid = wechat ? wechat.openid : null;
} catch (err) {
openid = null;
}
await member.update({
userId: Number(userId),
wechatOpenid: openid,
boundAt: new Date(),
status: 1,
});
const user = await this.app.model.User.findByPk(Number(userId), { attributes: USER_ATTRIBUTES });
const boundName = (user && (user.nickname || user.username)) || `用户${userId}`;
await this.app.redis.setex(this.bindKey(normalized), BIND_TTL, JSON.stringify({
status: 'confirmed',
subjectId: Number(subject.id),
memberId: Number(member.id),
name: member.name,
subjectName: subject.name,
boundName,
}));
this.ctx.logger.info('[subject] 主体 %s 成员「%s」绑定到用户 %s(%s)',
subject.id, member.name, userId, boundName);
return {
ok: true,
status: 'confirmed',
subjectId: Number(subject.id),
subjectName: subject.name,
memberId: Number(member.id),
memberName: member.name,
boundName,
};
}
/**
* 该用户可进入的第一个主体(设备扫码登录时用:设备没有「当前主体」概念)
* @return {Promise<number|null>}
*/
async defaultSubjectId(userId) {
try {
const list = await this.listForUser(userId);
const usable = list.find(item => !item.expired && Number(item.status) === 1);
return usable ? Number(usable.id) : (list.length ? Number(list[0].id) : null);
} catch (err) {
// 早期部署/单测里可能没有主体数据,设备登录不应因此失败
this.ctx.logger.warn('[subject] 读取默认主体失败: %s', err.message);
return null;
}
}
}
module.exports = SubjectService;

View File

@ -46,15 +46,29 @@ class UserService extends Service {
});
}
/** 写入密码哈希(哈希在 auth service 里生成) */
/** 写入密码哈希(哈希在 auth service 里生成);顺手记下改密时间,让旧 JWT 立即失效 */
async setPassword(id, passwordHash) {
const user = await this.User.findByPk(id);
if (!user) return false;
await user.update({ passwordHash });
await user.update({ passwordHash, passwordChangedAt: new Date() });
return true;
}
/**
* 令牌是不是在「设置/重置密码」之前签发的(是 → 旧令牌,应当 401)
*
* JWT 的 `iat` 只有秒级精度,所以用严格小于比较:改密那一秒内新签发的令牌仍然有效。
* `passwordChangedAt` 为空(老数据)→ 不限制。
* @param {object} user 用户(需含 passwordChangedAt)
* @param {number} iatSec JWT payload 里的 iat(秒)
*/
isTokenStale(user, iatSec) {
if (!user || !user.passwordChangedAt) return false;
const changedSec = Math.floor(new Date(user.passwordChangedAt).getTime() / 1000);
return Number(iatSec || 0) < changedSec;
}
/**
* 按主键查询并带出密码哈希(仅改密码等鉴权场景内部使用,不要外传)
* @return {Promise<object|null>} Sequelize 实例

View File

@ -392,6 +392,21 @@ class WechatLoginService extends Service {
});
}
/**
* 同一个内容画成 **GIF 图片字节**(桌面端 WPF 不能渲染 SVG,只能吃位图)
* @param {string} content 编码内容
* @return {Buffer} GIF 字节
*/
qrGif(content) {
const cellSize = this.cfg.qrCellSize;
const qr = qrcode(0, 'M');
qr.addData(String(content));
qr.make();
const dataUrl = qr.createDataURL(cellSize, this.cfg.qrMargin * cellSize);
const base64 = String(dataUrl).split(',').pop() || '';
return Buffer.from(base64, 'base64');
}
/** 用 code 换 openid(只有配好 appid/secret 才会走到这里) */
async exchangeCode(code) {
const apiBase = String(this.cfg.apiBase || 'https://api.weixin.qq.com').replace(/\/+$/, '');

View File

@ -0,0 +1,503 @@
'use strict';
const { Service } = require('egg');
const { Op } = require('sequelize');
/**
* 工作台 service
*
* 一个工作台可以绑定:
* - 多个**摄像头**(workstation_cameras,多对多)
* - 多个**扫码通道**(workstation_scan_channels,通道来自中控 scan_channels)
*
* 归属判定:工作台有自己的 `user_id`;绑定时还要校验「摄像头所属 NVR」和
* 「中控」都属于当前用户,防止把别人的设备挂到自己工作台上。
*/
class WorkstationService extends Service {
get Workstation() {
return this.app.model.Workstation;
}
get LinkCamera() {
return this.app.model.WorkstationCamera;
}
get LinkScanChannel() {
return this.app.model.WorkstationScanChannel;
}
/** 分页列表(附带摄像头数 / 扫码通道数) */
async list({ page = 1, pageSize = 20, keyword, status, wsType, subjectId } = {}) {
const size = Math.min(Number(pageSize) || 20, 100);
const current = Math.max(Number(page) || 1, 1);
const where = { subjectId: Number(subjectId) };
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
if (wsType !== undefined && wsType !== '' && wsType !== null) where.wsType = Number(wsType) === 2 ? 2 : 1;
if (keyword) {
where[Op.or] = [
{ code: { [Op.like]: `%${keyword}%` } },
{ name: { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await this.Workstation.findAndCountAll({
where,
limit: size,
offset: (current - 1) * size,
order: [[ 'id', 'DESC' ]],
});
const ids = rows.map(row => row.id);
const [ cameraCounts, scanCounts ] = ids.length
? await Promise.all([
this.LinkCamera.count({ where: { workstationId: { [Op.in]: ids } }, group: [ 'workstationId' ], raw: true }),
this.LinkScanChannel.count({ where: { workstationId: { [Op.in]: ids } }, group: [ 'workstationId' ], raw: true }),
])
: [ [], [] ];
const cameraMap = new Map(cameraCounts.map(item => [ Number(item.workstationId), item.count ]));
const scanMap = new Map(scanCounts.map(item => [ Number(item.workstationId), item.count ]));
const list = rows.map(row => Object.assign(row.toJSON(), {
cameraCount: cameraMap.get(Number(row.id)) || 0,
scanChannelCount: scanMap.get(Number(row.id)) || 0,
}));
return { list, total: count, page: current, pageSize: size };
}
/** 取「我的」工作台;不存在或不属于当前用户 → 404 */
async findOwned(id, subjectId) {
const workstation = await this.Workstation.findByPk(id);
if (!workstation || Number(workstation.subjectId) !== Number(subjectId)) {
this.ctx.throw(404, '工作台不存在或不属于当前账号');
}
return workstation;
}
/** 详情:工作台 + 已绑摄像头 + 已绑扫码通道 */
async detail(id, subjectId) {
const workstation = await this.findOwned(id, subjectId);
const [ cameraLinks, scanLinks ] = await Promise.all([
this.LinkCamera.findAll({
where: { workstationId: workstation.id },
include: [{
model: this.app.model.Camera,
as: 'camera',
required: true,
include: [{ model: this.app.model.Nvr, as: 'nvr', attributes: [ 'id', 'name', 'host', 'port' ] }],
}],
order: [[ 'sort_no', 'ASC' ], [ 'id', 'ASC' ]],
}),
this.LinkScanChannel.findAll({
where: { workstationId: workstation.id },
include: [{
model: this.app.model.Scanner,
as: 'scanner',
required: false,
attributes: [ 'id', 'sn', 'name', 'status' ],
}],
order: [[ 'sort_no', 'ASC' ], [ 'id', 'ASC' ]],
}),
]);
return Object.assign(workstation.toJSON(), {
cameras: cameraLinks.map(link => {
const data = link.toJSON();
return Object.assign(data, {
camera: data.camera ? Object.assign(data.camera, {
displayName: `${data.camera.nvr ? data.camera.nvr.name || data.camera.nvr.host : 'NVR'}-${data.camera.channelNo}`,
}) : null,
});
}),
scanChannels: scanLinks.map(link => link.toJSON()),
});
}
/** 新增工作台(同一主体下 code 唯一;软删过的会被复活并更新) */
async create({ subjectId, userId, code, name, wsType, recordBeforeSec, recordAfterSec, recordMaxSec, remark } = {}) {
const finalCode = String(code || '').trim() || `WS-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`;
const finalType = Number(wsType) === 2 ? 2 : 1;
const range = this._recordRange({
recordBeforeSec,
recordAfterSec,
recordMaxSec: finalType === 2 ? undefined : recordMaxSec,
});
const existing = await this.Workstation.findOne({
where: { subjectId: Number(subjectId), code: finalCode },
paranoid: false,
});
if (existing) {
if (existing.deletedAt) await existing.restore();
const nextType = wsType === undefined ? (Number(existing.wsType) === 2 ? 2 : 1) : finalType;
const before = range.recordBeforeSec ?? Number(existing.recordBeforeSec ?? 60);
const after = range.recordAfterSec ?? Number(existing.recordAfterSec ?? 60);
await existing.update({
name: name === undefined ? existing.name : String(name || '').trim(),
wsType: nextType,
recordBeforeSec: before,
recordAfterSec: after,
recordMaxSec: this._maxSec(nextType, before, after, range.recordMaxSec, existing.recordMaxSec),
remark: remark === undefined ? existing.remark : remark,
status: 1,
});
return this.findOwned(existing.id, subjectId);
}
const before = range.recordBeforeSec ?? 60;
const after = range.recordAfterSec ?? 60;
const created = await this.Workstation.create({
subjectId: Number(subjectId),
userId: userId ? Number(userId) : null,
code: finalCode,
name: String(name || '').trim() || '未命名工作台',
wsType: finalType,
recordBeforeSec: before,
recordAfterSec: after,
recordMaxSec: this._maxSec(finalType, before, after, range.recordMaxSec, 240),
remark: remark || null,
status: 1,
});
this.ctx.logger.info('[workstation] 主体 %s 新增工作台 %s', subjectId, finalCode);
return this.findOwned(created.id, subjectId);
}
/**
* 录制范围校验(秒)
*
* - before / after:0~3600
* - max:10~7200(缺省 240)
* 不传的字段返回 undefined,交给 create/update 决定是否覆盖。
*/
_recordRange({ recordBeforeSec, recordAfterSec, recordMaxSec } = {}) {
const clampInt = (value, min, max, label) => {
const num = Number(value);
if (!Number.isFinite(num)) this.ctx.throw(422, `${label}必须是数字`);
const int = Math.round(num);
if (int < min || int > max) this.ctx.throw(422, `${label}必须在 ${min}~${max} 秒之间`);
return int;
};
return {
recordBeforeSec: recordBeforeSec === undefined || recordBeforeSec === null || recordBeforeSec === ''
? undefined
: clampInt(recordBeforeSec, 0, 3600, '录制范围(前)'),
recordAfterSec: recordAfterSec === undefined || recordAfterSec === null || recordAfterSec === ''
? undefined
: clampInt(recordAfterSec, 0, 3600, '录制范围(后)'),
recordMaxSec: recordMaxSec === undefined || recordMaxSec === null || recordMaxSec === ''
? undefined
: clampInt(recordMaxSec, 10, 7200, '最大录制时长'),
};
}
/**
* 最大录制时长
*
* - 散单:用户可设(不传则沿用旧值 / 默认 240)
* - 团购:以扫码时间为基准,前 + 后就是总时长,没有额外上限(不返回/忽略前端传的值)
*/
_maxSec(wsType, before, after, incoming, fallback) {
if (Number(wsType) === 2) return Number(before) + Number(after);
if (incoming !== undefined && incoming !== null) return incoming;
return Number(fallback ?? 240);
}
/** 更新工作台(code 不开放修改;类型 / 录制范围可改) */
async update(id, subjectId, patch = {}) {
const workstation = await this.findOwned(id, subjectId);
const fields = {};
if (patch.name !== undefined) fields.name = String(patch.name || '').trim();
if (patch.wsType !== undefined) fields.wsType = Number(patch.wsType) === 2 ? 2 : 1;
const nextType = fields.wsType !== undefined
? fields.wsType
: (Number(workstation.wsType) === 2 ? 2 : 1);
// 团购没有「最大录制时长」(= 扫码前 + 扫码后),不校验也不收前端传的值
const range = this._recordRange({
recordBeforeSec: patch.recordBeforeSec,
recordAfterSec: patch.recordAfterSec,
recordMaxSec: nextType === 2 ? undefined : patch.recordMaxSec,
});
const before = range.recordBeforeSec ?? Number(workstation.recordBeforeSec ?? 60);
const after = range.recordAfterSec ?? Number(workstation.recordAfterSec ?? 60);
fields.recordBeforeSec = before;
fields.recordAfterSec = after;
fields.recordMaxSec = this._maxSec(nextType, before, after, range.recordMaxSec, workstation.recordMaxSec);
if (patch.remark !== undefined) fields.remark = patch.remark;
if (patch.status !== undefined) fields.status = Number(patch.status) === 0 ? 0 : 1;
await workstation.update(fields);
return this.findOwned(id, subjectId);
}
/** 删除工作台(连带解除所有绑定,工作台本体软删除) */
async remove(id, subjectId) {
const workstation = await this.findOwned(id, subjectId);
await Promise.all([
this.LinkCamera.destroy({ where: { workstationId: workstation.id } }),
this.LinkScanChannel.destroy({ where: { workstationId: workstation.id } }),
]);
await workstation.destroy();
this.ctx.logger.info('[workstation] 主体 %s 删除工作台 %s', subjectId, workstation.id);
return { id: workstation.id };
}
/**
* 绑定摄像头(追加,重复的自动忽略)
* @param {Array<number>} cameraIds 必须是当前用户 NVR 下的摄像头
*/
async bindCameras({ workstationId, subjectId, cameraIds = [] } = {}) {
const workstation = await this.findOwned(workstationId, subjectId);
const ids = Array.isArray(cameraIds)
? [ ...new Set(cameraIds.map(Number).filter(item => Number.isInteger(item) && item > 0)) ]
: [];
if (!ids.length) this.ctx.throw(422, 'cameraIds 不能为空');
const owned = await this.ctx.service.camera.listOfUser(subjectId);
const ownedIds = new Set(owned.map(item => Number(item.id)));
const invalid = ids.filter(item => !ownedIds.has(item));
if (invalid.length) this.ctx.throw(422, `摄像头不存在或不属于当前账号:${invalid.join(',')}`);
// 一个摄像头只能属于**一个**工作台:已被其他工作台绑定的直接拒绝(返回具体是哪个工作台)
const conflicts = await this.LinkCamera.findAll({
where: { cameraId: { [Op.in]: ids }, workstationId: { [Op.ne]: workstation.id } },
include: [{
model: this.Workstation,
as: 'workstation',
required: false,
attributes: [ 'id', 'code', 'name' ],
}],
});
if (conflicts.length) {
const details = conflicts.map(link => {
const camera = owned.find(item => Number(item.id) === Number(link.cameraId));
const label = (camera && camera.name) || `通道${camera ? camera.channelNo : link.cameraId}`;
const target = link.workstation && (link.workstation.name || link.workstation.code);
return `「${label}」已被工作台「${target || link.workstationId}」绑定,请先在该工作台解绑`;
});
this.ctx.throw(409, details.join(';'));
}
const maxSort = await this.LinkCamera.max('sortNo', { where: { workstationId: workstation.id } }) || 0;
// 默认布局:第 1 个铺满画布(1920×1080);第 2 个 720 宽放右上角;后面的依次叠左下角
const canvasW = Number(workstation.canvasWidth) || 1920;
const canvasH = Number(workstation.canvasHeight) || 1080;
const existing = await this.LinkCamera.count({ where: { workstationId: workstation.id } });
const rows = ids.map((cameraId, index) => {
const slot = existing + index;
let layout;
if (slot === 0) {
layout = { x: 0, y: 0, width: canvasW, height: canvasH, zIndex: 0 };
} else if (slot === 1) {
const width = Math.min(720, canvasW);
const height = Math.round(width * canvasH / canvasW);
layout = { x: canvasW - width, y: 0, width, height, zIndex: 1 };
} else {
const width = Math.min(480, canvasW);
const height = Math.round(width * canvasH / canvasW);
layout = { x: 0, y: canvasH - height, width, height, zIndex: slot };
}
return {
workstationId: workstation.id,
cameraId,
sortNo: Number(maxSort) + index + 1,
streamType: 0,
...layout,
};
});
await this.LinkCamera.bulkCreate(rows, { ignoreDuplicates: true });
this.ctx.logger.info('[workstation] 工作台 %s 绑定摄像头 %s', workstation.id, ids.join(','));
return this.detail(workstation.id, subjectId);
}
/** 解绑摄像头 */
async unbindCamera({ workstationId, subjectId, cameraId } = {}) {
const workstation = await this.findOwned(workstationId, subjectId);
await this.LinkCamera.destroy({ where: { workstationId: workstation.id, cameraId: Number(cameraId) } });
return this.detail(workstation.id, subjectId);
}
/**
* 修改某条绑定在合成画布上的位置 / 大小 / 码流
*
* patch: { x?, y?, width?, height?, streamType?, zIndex? }
* 全部按画布范围夹住,避免存进去一个跑到画布外面的矩形。
*/
async updateCameraLayout({ workstationId, subjectId, cameraId, patch = {} } = {}) {
const workstation = await this.findOwned(workstationId, subjectId);
const link = await this.LinkCamera.findOne({
where: { workstationId: workstation.id, cameraId: Number(cameraId) },
});
if (!link) this.ctx.throw(404, '该摄像头没有绑定到这个工作台');
const canvasW = Number(workstation.canvasWidth) || 1920;
const canvasH = Number(workstation.canvasHeight) || 1080;
const clamp = (value, min, max) => Math.min(Math.max(Math.round(Number(value) || 0), min), max);
const fields = {};
const width = patch.width !== undefined ? clamp(patch.width, 160, canvasW) : Number(link.width) || canvasW;
const height = patch.height !== undefined ? clamp(patch.height, 90, canvasH) : Number(link.height) || canvasH;
if (patch.width !== undefined) fields.width = width;
if (patch.height !== undefined) fields.height = height;
if (patch.x !== undefined) fields.x = clamp(patch.x, 0, Math.max(canvasW - width, 0));
if (patch.y !== undefined) fields.y = clamp(patch.y, 0, Math.max(canvasH - height, 0));
if (patch.streamType !== undefined) fields.streamType = Number(patch.streamType) === 1 ? 1 : 0;
if (patch.zIndex !== undefined) fields.zIndex = clamp(patch.zIndex, 0, 9999);
if (Object.keys(fields).length) await link.update(fields);
return this.detail(workstation.id, subjectId);
}
/**
* 绑定扫码通道(追加,重复的自动忽略)
*
* @param {Array} items [{ scannerId, channelId, channelName? }]
* channelName 不传则取 scan_channels 里的当前名字
*/
async bindScanChannels({ workstationId, subjectId, items = [] } = {}) {
const workstation = await this.findOwned(workstationId, subjectId);
if (!Array.isArray(items) || items.length === 0) this.ctx.throw(422, 'items 不能为空');
const scannerIds = await this.ctx.service.scanner.idsOfSubject(subjectId);
const allowed = new Set(scannerIds.map(Number));
const normalized = [];
const seen = new Set();
for (const raw of items) {
const scannerId = Number(raw && raw.scannerId);
const channelId = String((raw && raw.channelId) || '').trim();
if (!allowed.has(scannerId)) this.ctx.throw(422, `中控不存在或不属于当前账号:${raw && raw.scannerId}`);
if (!channelId) this.ctx.throw(422, 'channelId 不能为空');
const key = `${scannerId}:${channelId}`;
if (seen.has(key)) continue;
seen.add(key);
let channelName = String((raw && raw.channelName) || '').trim();
if (!channelName) {
const channel = await this.app.model.ScanChannel.findOne({
where: { scannerId, channelId },
attributes: [ 'channelName' ],
});
channelName = (channel && channel.channelName) || '';
}
normalized.push({ workstationId: workstation.id, scannerId, channelId, channelName: channelName.slice(0, 128) });
}
const maxSort = await this.LinkScanChannel.max('sortNo', { where: { workstationId: workstation.id } }) || 0;
normalized.forEach((row, index) => { row.sortNo = Number(maxSort) + index + 1; });
// 一个扫码通道也只能属于**一个**工作台
const conflicts = await this.LinkScanChannel.findAll({
where: {
workstationId: { [Op.ne]: workstation.id },
[Op.or]: normalized.map(row => ({ scannerId: row.scannerId, channelId: row.channelId })),
},
include: [{
model: this.Workstation,
as: 'workstation',
required: false,
attributes: [ 'id', 'code', 'name' ],
}],
});
if (conflicts.length) {
const details = conflicts.map(link => {
const row = normalized.find(item => item.scannerId === Number(link.scannerId) && item.channelId === link.channelId);
const label = (row && row.channelName) || link.channelId;
const target = link.workstation && (link.workstation.name || link.workstation.code);
return `扫码通道「${label}」已被工作台「${target || link.workstationId}」绑定,请先在该工作台解绑`;
});
this.ctx.throw(409, [ ...new Set(details) ].join(';'));
}
await this.LinkScanChannel.bulkCreate(normalized, { ignoreDuplicates: true });
this.ctx.logger.info('[workstation] 工作台 %s 绑定扫码通道 %d 个', workstation.id, normalized.length);
return this.detail(workstation.id, subjectId);
}
/** 解绑扫码通道(按绑定记录 id) */
async unbindScanChannel({ workstationId, subjectId, linkId } = {}) {
const workstation = await this.findOwned(workstationId, subjectId);
await this.LinkScanChannel.destroy({ where: { id: Number(linkId), workstationId: workstation.id } });
return this.detail(workstation.id, subjectId);
}
/**
* 当前用户**可绑定**的扫码通道(工作台选择器用)
* 来源:自己的中控(scanners)上报的通道(scan_channels)
*/
async availableScanChannels({ subjectId, keyword } = {}) {
const scannerIds = await this.ctx.service.scanner.idsOfSubject(subjectId);
if (!scannerIds.length) return [];
const where = { scannerId: { [Op.in]: scannerIds } };
if (keyword) {
where[Op.or] = [
{ channelId: { [Op.like]: `%${keyword}%` } },
{ channelName: { [Op.like]: `%${keyword}%` } },
];
}
const rows = await this.app.model.ScanChannel.findAll({
where,
include: [{
model: this.app.model.Scanner,
as: 'scanner',
required: false,
attributes: [ 'id', 'sn', 'name', 'status' ],
}],
order: [[ 'scanner_id', 'ASC' ], [ 'channel_id', 'ASC' ]],
});
// 带上「已被哪个工作台绑定」(null = 还可以绑)
const links = await this.LinkScanChannel.findAll({
where: { scannerId: { [Op.in]: scannerIds } },
include: [{
model: this.Workstation,
as: 'workstation',
required: false,
attributes: [ 'id', 'code', 'name' ],
}],
});
const boundBy = new Map();
for (const link of links) {
boundBy.set(`${link.scannerId}:${link.channelId}`, link.workstation ? link.workstation.toJSON() : null);
}
return rows.map(row => {
const item = row.toJSON();
item.boundWorkstation = boundBy.get(`${item.scannerId}:${item.channelId}`) || null;
return item;
});
}
}
module.exports = WorkstationService;

View File

@ -59,8 +59,13 @@ module.exports = (appInfo) => {
.filter(id => Number.isInteger(id) && id > 0),
};
// ==================== 服务端口 ====================
// 本地默认 **7300**(曾用 7001;避免与别的项目撞,也方便和前端 7301 排在一起)
// ==================== 主体(租户)====================
// 新建主体默认赠送的试用天数(app/service/subject.js 用)
config.subject = {
trialDays: Number(env.SUBJECT_TRIAL_DAYS || 7),
};
// ==================== 服务端口 ==================== // 本地默认 **7300**(曾用 7001;避免与别的项目撞,也方便和前端 7301 排在一起)
// 临时换口:PORT=7400 npm run dev(PowerShell:$env:PORT=7400; npm run dev)
config.cluster = {
listen: {
@ -139,6 +144,9 @@ module.exports = (appInfo) => {
// 设备扫码登录(GET /api/device/login)下发令牌的**默认时长,同时也是上限**:
// 设备可以用 ?expiresIn=30d 申请更短的,但不能比它长(要整体放宽就改这个)
deviceExpiresIn: env.DEVICE_JWT_EXPIRES || env.SCANNER_JWT_EXPIRES || '365d',
// 刷新令牌有效期(不透明随机串,库里只存 sha256)。每次刷新都会轮换并顺延;
// 默认 2 年:只要服务在跑就会持续续期,停用超过这个时间才需要重新激活。
deviceRefreshExpiresIn: env.DEVICE_REFRESH_EXPIRES || '730d',
// 用户令牌有效期(扫码登录 / 前端接口用的 JWT)
userExpiresIn: env.USER_JWT_EXPIRES || '7d',
};

View File

@ -46,7 +46,7 @@ async function main() {
console.log(`[user:pass] 已重置密码: ${user.username || user.phone || user.email} (id=${user.id})`);
} else {
const [result] = await conn.query(
'insert into users (username, nickname, password_hash, status) values (?, ?, ?, 1)',
'insert into users (username, nickname, password_hash, password_changed_at, status) values (?, ?, ?, now(), 1)',
[ account, nickname || account, hash ],
);
console.log(`[user:pass] 已创建用户: ${account} (id=${result.insertId}),昵称: ${nickname || account}`);