- 工作台成员扫码登入: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>
367 lines
14 KiB
JavaScript
367 lines
14 KiB
JavaScript
'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`: 给人看的说明(通道没绑工作台 / 工作台没绑摄像头 / 运单不属于本主体…)
|
||
* - `records[].packers`: 该次扫码时还在线的人(来自 `workstation_login_records`,可能多人)
|
||
*/
|
||
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);
|
||
}
|
||
|
||
// 每条记录「当时谁在工作台上」(打包人员,可能多人):按工作台 + 扫码时间批量查一次
|
||
if (records.length) {
|
||
const packers = await this.ctx.service.workstationLogin.packersMap(records.map(item => ({
|
||
key: Number(item.id),
|
||
workstationId: item.workstationId,
|
||
scanTime: item.scanTime,
|
||
})));
|
||
for (const item of records) {
|
||
item.packers = packers.get(Number(item.id)) || [];
|
||
}
|
||
}
|
||
|
||
// `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;
|