- 工作台成员扫码登入:workstation_login_records 记录谁在什么时候登入/下线了哪台工作台, 超时(团购 1h / 散单 30min)由 schedule/workstation_idle_offline 自动下线; 运单查询的 packers 取当时的登入成员 - 面单摄像头识别:workstation_cameras.is_label_camera + service/label_scan 下发本机该跑的识别配置, 设备端(桌面端 LabelScan 工作线程)按配置做面单识别并上报 - 虚拟通道 CAM-<工作台id>:工作台没接扫码枪时,面单摄像头那一路顶替扫码枪上报,records 规则按 ws_type 区分 - 桌面端:新增 LabelScanMonitor/LabelScanWorker/ScanDeviceKind 与面单预览页,扫描通道支持改名,静默窗口 5s Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
702 lines
29 KiB
JavaScript
702 lines
29 KiB
JavaScript
'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;
|
||
|
||
/**
|
||
* 工作台 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;
|
||
}
|
||
|
||
/**
|
||
* 录制范围校验(秒)
|
||
*
|
||
* - 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;
|
||
|
||
await workstation.update(fields);
|
||
|
||
// 名称/类型/启用状态都会改变下发给设备的面单配置(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`);一台工作台最多一路,设新的会先把旧的取消掉。
|
||
* `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');
|
||
|
||
if (label) {
|
||
await this.LinkCamera.update(
|
||
{ isLabelCamera: 0 },
|
||
{ where: { workstationId: workstation.id, isLabelCamera: 1 } },
|
||
);
|
||
}
|
||
await link.update({ isLabelCamera: label ? 1 : 0 });
|
||
|
||
// 取消面单摄像头:这台工作台的虚拟通道(`CAM-<id>`)没用了,顺手清掉
|
||
if (!label) 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;
|