packServer/backend/app/service/workstation.js
liufumingren 2ed4fa8483 feat(workstation): 一台工作台支持多路面单摄像头 + 绑定管理可改画布尺寸
- 面单摄像头不再限制一台工作台一路:设置新的不清旧标记,取消最后一路时才清理虚拟通道
- 面单识别配置按 工作台+摄像头 逐路下发,多路共用上报通道;多路时虚拟通道名改用工作台名
- 绑定管理新增画布尺寸(宽×高)编辑:160~7680、自动取偶数;改尺寸时已摆放摄像头按比例缩放
- 画布组件在宽度变化时重新计算等比缩放,避免新画布溢出或缩不满
- 补充后端单测与相关文档

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-08 23:45:25 +08:00

776 lines
32 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Service } = require('egg');
const { Op } = require('sequelize');
const { virtualChannelIdOf, isVirtualChannelId, VIRTUAL_CHANNEL_PREFIX } = require('../lib/virtual-channel');
/** 不活跃自动下线:默认秒数(团购 1 小时 / 散单 30 分钟) */
const IDLE_TIMEOUT_GROUP_SEC = 3600;
const IDLE_TIMEOUT_SINGLE_SEC = 1800;
/** 允许配置的范围:1 分钟 ~ 24 小时 */
const IDLE_TIMEOUT_MIN_SEC = 60;
const IDLE_TIMEOUT_MAX_SEC = 24 * 3600;
/** 合成画布尺寸范围(像素);合成输出走 ffmpeg,宽高取偶数更稳 */
const CANVAS_MIN = 160;
const CANVAS_MAX = 7680;
/**
* 工作台 service
*
* 一个工作台可以绑定:
* - 多个**摄像头**(workstation_cameras,多对多)
* - 多个**扫码通道**(workstation_scan_channels,通道来自中控 scan_channels)
*
* 归属判定:工作台有自己的 `user_id`;绑定时还要校验「摄像头所属 NVR」和
* 「中控」都属于当前用户,防止把别人的设备挂到自己工作台上。
*
* 另外一台工作台还带:
* - `lastActiveAt` / `idleTimeoutSec`:最后活跃时间与「多久不活跃自动下线所有成员」。
*
* ⚠️ 现场扫码登入不再用「工作台上贴一张固定的登录码」:改为按需生成一张**一次性**
* 微信扫码二维码(`createLoginQr`,走微信登录网关),见 `service/wx_gateway.js`。
*/
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 => Number(row.id));
const [ cameraCounts, scanCounts ] = rows.length
? await Promise.all([
this.LinkCamera.count({ where: { workstationId: { [Op.in]: ids } }, group: [ 'workstationId' ], raw: true }),
// 虚拟通道(面单摄像头自己用)不算「绑定的扫码通道」
this.LinkScanChannel.count({
where: { workstationId: { [Op.in]: ids }, channelId: { [Op.notLike]: `${VIRTUAL_CHANNEL_PREFIX}%` } },
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 => Object.assign(link.toJSON(), {
// 虚拟通道 = 面单摄像头自己占的通道(`CAM-<工作台id>`),由服务端自动维护,前端不给解绑
virtual: isVirtualChannelId(link.channelId),
})),
});
}
/** 新增工作台(同一主体下 code 唯一;软删过的会被复活并更新) */
async create({ subjectId, userId, code, name, wsType, recordBeforeSec, recordAfterSec, recordMaxSec, idleTimeoutSec, 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 timeout = this._idleTimeout(idleTimeoutSec);
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),
idleTimeoutSec: timeout
?? (Number(existing.idleTimeoutSec) || this._defaultIdleTimeout(nextType)),
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),
idleTimeoutSec: timeout ?? this._defaultIdleTimeout(finalType),
remark: remark || null,
status: 1,
});
this.ctx.logger.info('[workstation] 主体 %s 新增工作台 %s', subjectId, finalCode);
return this.findOwned(created.id, subjectId);
}
/** 不活跃自动下线:团购 1 小时 / 散单 30 分钟 */
_defaultIdleTimeout(wsType) {
return Number(wsType) === 2 ? IDLE_TIMEOUT_GROUP_SEC : IDLE_TIMEOUT_SINGLE_SEC;
}
/** 不活跃秒数校验(不传返回 undefined,交给调用方决定用旧值还是默认值) */
_idleTimeout(value) {
if (value === undefined || value === null || value === '') return undefined;
const num = Number(value);
if (!Number.isFinite(num)) this.ctx.throw(422, '不活跃自动下线时间必须是数字');
const int = Math.round(num);
if (int < IDLE_TIMEOUT_MIN_SEC || int > IDLE_TIMEOUT_MAX_SEC) {
this.ctx.throw(422, `不活跃自动下线时间必须在 ${IDLE_TIMEOUT_MIN_SEC}~${IDLE_TIMEOUT_MAX_SEC} 秒之间`);
}
return int;
}
/**
* 画布尺寸校验(像素)
*
* 不传返回 undefined(调用方沿用旧值)。宽高限制在 160~7680,并四舍五入到偶数
* (合成输出走 ffmpeg,yuv420p 对奇数宽高不友好)。
*/
_canvasSize(value, label) {
if (value === undefined || value === null || value === '') return undefined;
const num = Number(value);
if (!Number.isFinite(num)) this.ctx.throw(422, `${label}必须是数字`);
let int = Math.round(num);
if (int < CANVAS_MIN || int > CANVAS_MAX) {
this.ctx.throw(422, `${label}必须在 ${CANVAS_MIN}~${CANVAS_MAX} 像素之间`);
}
if (int % 2 !== 0) int -= 1;
return int;
}
/**
* 画布尺寸变了 → 把每路摄像头的矩形按比例缩放,保持原来的合成构图
*
* 宽/高为 0 的旧数据按「整张旧画布」算;缩放后夹在新画布范围内。
* @return {Promise<number>} 实际更新的绑定行数
*/
async _rescaleCameraLayouts(workstationId, oldW, oldH, newW, newH) {
const scaleX = newW / oldW;
const scaleY = newH / oldH;
const links = await this.LinkCamera.findAll({ where: { workstationId } });
let changed = 0;
for (const link of links) {
const width = Math.min(Math.max(Math.round((Number(link.width) || oldW) * scaleX), 160), newW);
const height = Math.min(Math.max(Math.round((Number(link.height) || oldH) * scaleY), 90), newH);
const x = Math.min(Math.max(Math.round((Number(link.x) || 0) * scaleX), 0), newW - width);
const y = Math.min(Math.max(Math.round((Number(link.y) || 0) * scaleY), 0), newH - height);
if (x !== Number(link.x) || y !== Number(link.y)
|| width !== Number(link.width) || height !== Number(link.height)) {
await link.update({ x, y, width, height });
changed++;
}
}
return changed;
}
/**
* 录制范围校验(秒)
*
* - 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)
* - 团购:**没有**最大时长(web 也不提供配置),总时长就是 前 + 后;
* 这里落库为 0(= 不限制),不再写成 before+after 的派生值,
* 避免库里出现一个像“限制 30 秒”的数字被误读
*/
_maxSec(wsType, before, after, incoming, fallback) {
if (Number(wsType) === 2) return 0;
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);
// 不活跃下线时间:显式传了就按传入值;只切类型没传 → 用新类型的默认值
const timeout = this._idleTimeout(patch.idleTimeoutSec);
if (timeout !== undefined) {
fields.idleTimeoutSec = timeout;
} else if (fields.wsType !== undefined && fields.wsType !== (Number(workstation.wsType) === 2 ? 2 : 1)) {
fields.idleTimeoutSec = this._defaultIdleTimeout(fields.wsType);
}
if (patch.remark !== undefined) fields.remark = patch.remark;
if (patch.status !== undefined) fields.status = Number(patch.status) === 0 ? 0 : 1;
// 合成画布尺寸:允许改;已有摄像头的矩形按比例缩放,保持原来的合成构图
const oldCanvasW = Number(workstation.canvasWidth) || 1920;
const oldCanvasH = Number(workstation.canvasHeight) || 1080;
const canvasW = this._canvasSize(patch.canvasWidth, '画布宽');
const canvasH = this._canvasSize(patch.canvasHeight, '画布高');
const nextCanvasW = canvasW ?? oldCanvasW;
const nextCanvasH = canvasH ?? oldCanvasH;
if (nextCanvasW !== oldCanvasW || nextCanvasH !== oldCanvasH) {
fields.canvasWidth = nextCanvasW;
fields.canvasHeight = nextCanvasH;
}
await workstation.update(fields);
if (fields.canvasWidth !== undefined) {
const rescaled = await this._rescaleCameraLayouts(
workstation.id, oldCanvasW, oldCanvasH, nextCanvasW, nextCanvasH,
);
this.ctx.logger.info(
'[workstation] 工作台 %s 画布 %dx%d → %dx%d(按比例缩放 %d 路摄像头布局)',
workstation.id, oldCanvasW, oldCanvasH, nextCanvasW, nextCanvasH, rescaled,
);
}
// 名称/类型/启用状态都会改变下发给设备的面单配置(wsType 决定记录规则)→ 叫醒设备重拉
await this._notifyLabelScan(subjectId);
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 this.releaseVirtualChannel(workstation.id);
const offline = await this.ctx.service.workstationLogin
.offlineAll(workstation.id, 'workstation_deleted');
await workstation.destroy();
this.ctx.logger.info('[workstation] 主体 %s 删除工作台 %s(下线成员 %d 人)', subjectId, workstation.id, offline);
// 工作台没了,它名下的面单识别任务也要停 → 叫醒设备重拉
await this._notifyLabelScan(subjectId);
return { id: workstation.id, offline };
}
/**
* 面单识别配置受这次变更影响 → 叫醒本主体在线设备立刻重拉
*
* 失败不抛:配置已经落库,下次兜底轮询(设备端 1 分钟)也会补上,
* 不能因为「通知」把工作台的正常操作搞失败。
*/
async _notifyLabelScan(subjectId) {
try {
await this.ctx.service.labelScan.notifyChanged(subjectId);
} catch (err) {
this.ctx.logger.warn('[workstation] 通知设备重拉面单配置失败:%s', err.message);
}
}
/**
* 把该工作台**所有在线成员下线**(成员弹窗的「全部下线」)
* @return {Promise<object>} { id, offline }
*/
async offlineAllMembers(id, subjectId) {
const workstation = await this.findOwned(id, subjectId);
const offline = await this.ctx.service.workstationLogin
.offlineAll(workstation.id, 'offline_all');
this.ctx.logger.info('[workstation] 主体 %s 一键下线工作台 %s 成员 %d 人', subjectId, workstation.id, offline);
return { id: Number(workstation.id), offline };
}
/**
* 生成「扫码登入本工作台」的二维码(微信登录网关)
*
* 二维码内容 = 网关的授权页地址(临时码,一次有效),用户用微信扫码确认后
* 网关回调本服务(`/api/wechat-gateway/notify`)→ 写一条工作台登录记录。
*
* @return {Promise<object>} { state, qrUrl, pageUrl, expiresIn }
*/
async createLoginQr(id, subjectId) {
const workstation = await this.findOwned(id, subjectId);
if (Number(workstation.status) !== 1) this.ctx.throw(403, '工作台已停用,请先启用');
const state = await this.ctx.service.subjectState.get(Number(workstation.subjectId));
if (!state) this.ctx.throw(404, '工作台不存在或不属于当前账号');
if (state.disabled) this.ctx.throw(403, '所属主体已被停用,请联系管理员');
if (state.expired) this.ctx.throw(403, `主体「${state.name}」使用期限已到,请联系管理员续期`);
const session = await this.ctx.service.wxGateway.openSession({
purpose: 'workstation',
scene: 'login',
payload: { workstationId: Number(workstation.id), subjectId: Number(workstation.subjectId) },
});
return {
workstationId: Number(workstation.id),
state: session.state,
pageUrl: session.pageUrl,
qrUrl: `/api/wechat-gateway/qrcode.svg?state=${encodeURIComponent(session.state)}`,
expiresIn: session.expiresIn,
};
}
/**
* 绑定摄像头(追加,重复的自动忽略)
* @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) } });
// 解绑的可能正是面单摄像头 → 设备端要立刻重拉配置
await this._notifyLabelScan(subjectId);
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);
}
/**
* 设置 / 取消「面单摄像头」
*
* 散单和团购工作台都可以设(区别在设备端的记录规则:散单取第一次、团购取最后一次,
* 见设备端下发里的 `wsType`)。**一台工作台可以设多路**:每路都单独识别,
* 识别结果都按本工作台的上报通道(真实通道或虚拟通道 `CAM-<id>`)上报。
* `isLabelCamera` 不传按「设置」处理。
*/
async setLabelCamera({ workstationId, subjectId, cameraId, isLabelCamera } = {}) {
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 label = isLabelCamera === undefined || isLabelCamera === null
? true
: !(isLabelCamera === false || isLabelCamera === 0 || isLabelCamera === '0' || isLabelCamera === 'false');
await link.update({ isLabelCamera: label ? 1 : 0 });
// 取消面单摄像头:工作台已经没有任何面单摄像头了,虚拟通道(`CAM-<id>`)才没用了;
// 还有别的面单摄像头在用就保留(多路共用同一条上报通道)
if (!label) {
const remaining = await this.LinkCamera.count({
where: { workstationId: workstation.id, isLabelCamera: 1 },
});
if (!remaining) await this.releaseVirtualChannel(workstation.id);
}
this.ctx.logger.info(
'[workstation] 工作台 %s %s面单摄像头(camera %s)',
workstation.id, label ? '设置' : '取消', cameraId,
);
// 面单摄像头变了 → 叫醒设备立刻重拉(否则要等 5 分钟兜底轮询)
await this._notifyLabelScan(subjectId);
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 });
// 绑上真实扫码通道后,摄像头虚拟通道就多余了(不然回放定位可能落到 CAM- 上)
await this.releaseVirtualChannel(workstation.id);
this.ctx.logger.info('[workstation] 工作台 %s 绑定扫码通道 %d 个', workstation.id, normalized.length);
// 上报通道变了 → 面单识别结果的落点也变了,设备端要重拉
await this._notifyLabelScan(subjectId);
return this.detail(workstation.id, subjectId);
}
/**
* 清理工作台的虚拟扫码通道(`CAM-<工作台id>`)
*
* 虚拟通道由服务端按需创建(`service/label_scan.ensureVirtualChannel`),所以下面几种情况要清掉:
* 取消**最后一路**面单摄像头、绑上真实扫码通道、删除工作台。
* 历史扫码记录里的工作台快照是**入库时冻结**的,删掉通道不影响老记录回放。
*
* @return {Promise<number>} 解绑的绑定行数
*/
async releaseVirtualChannel(workstationId) {
const id = Number(workstationId);
if (!id) return 0;
const channelId = virtualChannelIdOf(id);
const removed = await this.LinkScanChannel.destroy({ where: { workstationId: id, channelId } });
// 通道行只在没被任何工作台绑定时才删(正常情况下一台工作台独占自己的虚拟通道)
const stillUsed = await this.LinkScanChannel.count({ where: { channelId } });
if (!stillUsed) {
await this.app.model.ScanChannel.destroy({ where: { channelId } });
}
if (removed) {
this.ctx.logger.info('[workstation] 工作台 %s 清理虚拟通道 %s(解绑 %d)', id, channelId, removed);
}
return removed;
}
/** 解绑扫码通道(按绑定记录 id) */
async unbindScanChannel({ workstationId, subjectId, linkId } = {}) { const workstation = await this.findOwned(workstationId, subjectId);
await this.LinkScanChannel.destroy({ where: { id: Number(linkId), workstationId: workstation.id } });
// 上报通道变了 → 设备端要重拉(没有真实通道时服务端会改用虚拟通道)
await this._notifyLabelScan(subjectId);
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 } };
// 虚拟通道(`CAM-<工作台id>`,面单摄像头自己用)不给人工绑定
where.channelId = { [Op.notLike]: `${VIRTUAL_CHANNEL_PREFIX}%` };
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;