diff --git a/electron/hikvision-live.js b/electron/hikvision-live.js new file mode 100644 index 0000000..8e81e69 --- /dev/null +++ b/electron/hikvision-live.js @@ -0,0 +1,528 @@ +/** + * WMS 内置海康取流服务(HTTP 快照模式,监听 127.0.0.1:17320) + * + * 协议与 printServer(打印电脑服务)的 live-stream 一致,但端口独立: + * printServer 用 17311(被占时回退 17312/17313),WMS 用 17320,互不冲突。 + * 前端 src/api/camera.ts 的 getLiveStreamUrl() 固定请求 + * http://localhost:17320/api/hikvision/live-stream,因此 WMS exe 单机即可 + * 预览退件摄像头,无需另装 printServer。 + * + * 端口策略:仅绑定 127.0.0.1 回环(不暴露局域网);17320 被占用时放弃并告警。 + * + * 仅使用 Node 标准库(http/net/crypto),无第三方依赖,兼容 + * electron-builder "dependencies 为空、不打 node_modules" 的打包配置。 + */ + +'use strict' + +const http = require('http') +const net = require('net') +const crypto = require('crypto') + +const PORT = 17320 +const SNAPSHOT_INTERVAL_MS = 200 +const LOGIN_CACHE_TTL_MS = 20 * 60 * 1000 +const REQ_TIMEOUT_MS = 10000 + +/** printServer 无 ffmpeg 时的兜底错误图(1x1 JPEG),保持 502 行为与之一致 */ +const FALLBACK_JPEG = Buffer.from( + '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBAUEBAYFBQUGBgYHCQ4JCQgICRINDgoRFWGBEXFBUWFhcbHR8lJx4eHiAhIyUoKSkrLC0tHyE3NTcoNSooKSv/2wBDAQcHBwkJCRYJCQ0XFhUWFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxf/wAARCAABAAEDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACf/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AKwA//9k=', + 'base64' +) + +/** 简单 XML 文本提取(海康 ISAPI XML 字段,支持命名空间前缀,大小写敏感与 printServer 一致) */ +function xmlText(xml, tag) { + if (!xml) return '' + const re = new RegExp( + '<(?:[\\w.-]+:)?' + tag + '(?:\\s[^>]*)?>([\\s\\S]*?)<\\/(?:[\\w.-]+:)?' + tag + '\\s*>' + ) + const m = xml.match(re) + return m ? m[1].trim() : '' +} + +function sha256Hex(text) { + return crypto.createHash('sha256').update(text, 'utf-8').digest('hex') +} + +function sendJson(res, code, obj) { + const body = Buffer.from(JSON.stringify(obj), 'utf-8') + res.writeHead(code, { + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': body.length, + 'Access-Control-Allow-Origin': '*', + 'Cache-Control': 'no-cache', + }) + res.end(body) +} + +/** 创建海康认证/请求服务实例(含登录缓存与并发锁) */ +function createHikvisionService() { + const loginCache = new Map() // key `${ip}:${port}` -> { ts, httpBase, cookieJar, sessionTag } + const loginLocks = new Map() // key -> Promise + + /** 通用 HTTP 请求(复刻 printServer services/hikvision.js _req) */ + function _req(method, url, body, headers, cookieJar, binary = false, agent = null) { + const u = new URL(url) + const bodyBuf = body ? Buffer.from(typeof body === 'string' ? body : body, 'utf-8') : null + const cookies = Object.entries(cookieJar || {}) + .map(([k, v]) => `${k}=${v}`) + .join('; ') + const hdrs = { Accept: '*/*', 'User-Agent': 'Mozilla/5.0', ...headers } + if (cookies) hdrs['Cookie'] = cookies + if (bodyBuf) hdrs['Content-Length'] = bodyBuf.length + + return new Promise((resolve, reject) => { + const reqOpts = { + hostname: u.hostname, + port: u.port || 80, + path: u.pathname + u.search, + method, + headers: hdrs, + timeout: REQ_TIMEOUT_MS, + } + if (agent) reqOpts.agent = agent + const req = http.request(reqOpts, (res) => { + const chunks = [] + res.on('data', (c) => chunks.push(c)) + res.on('end', () => { + const raw = Buffer.concat(chunks) + const bodyOut = binary ? raw : raw.toString('utf-8') + if (res.headers['set-cookie'] && cookieJar) { + const list = Array.isArray(res.headers['set-cookie']) + ? res.headers['set-cookie'] + : [res.headers['set-cookie']] + list.forEach((sc) => { + const m = sc.match(/^([^=;]+)=([^;]*)/) + if (m) cookieJar[m[1]] = m[2] + }) + } + resolve({ statusCode: res.statusCode, headers: res.headers, body: bodyOut }) + }) + }) + req.on('error', reject) + req.on('timeout', () => { + req.destroy() + reject(new Error('请求超时')) + }) + if (bodyBuf) req.write(bodyBuf) + req.end() + }) + } + + /** 获取一次性 token(需要已有 session) */ + async function _getToken(httpBase, sessionTag, cookieJar) { + const tokenHeaders = sessionTag ? { SessionTag: sessionTag } : {} + const tokenRes = await _req( + 'GET', + `${httpBase}/ISAPI/Security/token?format=json`, + null, + tokenHeaders, + cookieJar + ) + if (!String(tokenRes.body || '').includes('"Token"')) { + throw new Error(`Token获取失败(session失效,status=${tokenRes.statusCode})`) + } + try { + return JSON.parse(tokenRes.body).Token.value + } catch (e) { + throw new Error(`Token解析失败(status=${tokenRes.statusCode})`) + } + } + + /** 完整 digest 登录(复刻 printServer _doLogin,XML 解析用正则替代 @xmldom) */ + async function _doLogin(ip, httpPort, user, pass) { + const httpBase = `http://${ip}:${httpPort}` + const cookieJar = {} + + const capsUrl = `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${encodeURIComponent(user)}&random:${String(Date.now()).slice(-8)}` + const capsRes = await _req('GET', capsUrl, null, {}, cookieJar) + if (capsRes.statusCode !== 200) { + throw Object.assign(new Error(`获取登录能力失败: HTTP ${capsRes.statusCode}`), { + statusCode: capsRes.statusCode, + }) + } + const capsBody = String(capsRes.body || '') + const sid = xmlText(capsBody, 'sessionID') + const challenge = xmlText(capsBody, 'challenge') + const salt = xmlText(capsBody, 'salt') + const itr = parseInt(xmlText(capsBody, 'iterations')) || 1 + const ver = xmlText(capsBody, 'sessionIDVersion') || '1' + const vl = xmlText(capsBody, 'isSessionIDValidLongTerm') || 'false' + const st = xmlText(capsBody, 'isSupportSessionTag') || 'false' + const irreversible = xmlText(capsBody, 'isIrreversible') === 'true' + + let digest + if (irreversible) { + digest = sha256Hex(user + salt + pass) + digest = sha256Hex(digest + challenge) + for (let i = 2; i < itr; i++) digest = sha256Hex(digest) + } else { + digest = sha256Hex(pass + challenge) + for (let i = 1; i < itr; i++) digest = sha256Hex(digest) + } + + let loginXml + if (ver === '2') { + loginXml = `${user}${digest}${sid}${vl}2${st}` + } else { + loginXml = `${user}${digest}${sid}` + } + const loginRes = await _req( + 'POST', + `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, + loginXml, + { 'Content-Type': 'text/plain;charset=UTF-8' }, + cookieJar + ) + if (loginRes.statusCode !== 200) { + throw Object.assign(new Error(`登录失败: HTTP ${loginRes.statusCode}`), { + statusCode: loginRes.statusCode, + }) + } + + const sessionTag = xmlText(String(loginRes.body || ''), 'sessionTag') + const token = await _getToken(httpBase, sessionTag, cookieJar) + return { token, cookieJar, sessionTag, httpBase } + } + + /** 登录(带 20 分钟 session 缓存与并发锁) */ + async function login(ip, httpPort, user, pass) { + const key = `${ip}:${httpPort}` + + const cached = loginCache.get(key) + if (cached && Date.now() - cached.ts < LOGIN_CACHE_TTL_MS) { + try { + const token = await _getToken(cached.httpBase, cached.sessionTag, cached.cookieJar) + return { token, cookieJar: cached.cookieJar, sessionTag: cached.sessionTag, httpBase: cached.httpBase } + } catch (e) { + console.log('[hik-live] 缓存 session 取 token 失败,清除缓存重新登录:', e.message) + loginCache.delete(key) + } + } + + if (loginLocks.has(key)) { + return loginLocks.get(key) + } + + const promise = _doLogin(ip, httpPort, user, pass) + loginLocks.set(key, promise) + try { + const result = await promise + loginCache.set(key, { + cookieJar: result.cookieJar, + sessionTag: result.sessionTag, + httpBase: result.httpBase, + ts: Date.now(), + }) + return result + } finally { + loginLocks.delete(key) + } + } + + return { login } +} + +/** 发送 502 兜底错误图(与 printServer 无 ffmpeg 时行为一致,触发前端公网回退逻辑) */ +function sendErrorImage(res) { + res.writeHead(502, { + 'Content-Type': 'image/jpeg', + 'Content-Length': FALLBACK_JPEG.length, + 'Access-Control-Allow-Origin': '*', + 'Cache-Control': 'no-cache', + }) + res.end(FALLBACK_JPEG) +} + +/** + * GET /api/hikvision/live-stream —— HTTP 快照轮询模式 MJPEG + * 复刻 printServer _handleHikvisionLiveStreamHttp(仅保留 HTTP 快照分支) + */ +async function handleLiveStream(svc, res, params) { + const ip = params.get('ip') + const user = params.get('user') + const pass = params.get('pass') + const channel = parseInt(params.get('channel')) || 33 + const rawStreamType = parseInt(params.get('streamType')) + const streamType = Number.isNaN(rawStreamType) ? 1 : rawStreamType + const interval = Number.isFinite(parseInt(params.get('interval'))) + ? Math.max(0, parseInt(params.get('interval'))) + : SNAPSHOT_INTERVAL_MS + + if (!ip || !user || !pass) { + sendJson(res, 400, { success: false, message: '缺少参数: ip, user, pass' }) + return + } + // 海康通道号 = 100*channel + 流后缀(1=主码流/2=子码流)。 + // 前端 streamType: 0/1 均按主码流(101),2 按子码流(102)—— + // 直接用 100*channel+0 会得到无效通道(100),NVR 返回 503 statusCode 2。 + // 与 printServer RTSP 分支的 rtspStreamType 映射保持一致。 + const streamSuffix = streamType === 2 ? 2 : 1 + const channelCode = 100 * channel + streamSuffix + + // 端口候选回退:httpPort -> port -> 80。 + // 前端 getLiveStreamUrl 透传的 port 是 NVR 端口(常为 RTSP 554), + // 而 ISAPI HTTP 服务通常在 80 端口;554 上发 HTTP 会秒拒,登录失败自动回退。 + const explicitHttpPort = parseInt(params.get('httpPort')) + const portParam = parseInt(params.get('port')) + const portCandidates = [] + for (const p of [explicitHttpPort, portParam, 80]) { + if (Number.isFinite(p) && p > 0 && p < 65536 && !portCandidates.includes(p)) { + portCandidates.push(p) + } + } + + let closed = false + let cookieJar = {} + let sessionTag = '' + let usedHttpPort = null + let agent = null + let lastPictureErrLog = 0 + + const doCleanup = () => { + if (closed) return + closed = true + if (agent) { + try { + agent.destroy() + } catch {} + } + if (!res.writableEnded) { + try { + res.end() + } catch {} + } + } + + res.on('close', doCleanup) + res.on('error', doCleanup) + + // Step 1: 登录(候选端口逐个尝试,单端口限时 3.5s;NVR 的 RTSP 端口对 HTTP + // 请求可能挂住不响应,限时后快速回退到下一候选) + const CANDIDATE_LOGIN_TIMEOUT_MS = 3500 + let loginResult = null + for (const candidate of portCandidates) { + try { + loginResult = await Promise.race([ + svc.login(ip, candidate, user, pass), + new Promise((_, reject) => + setTimeout(() => reject(new Error('登录超时')), CANDIDATE_LOGIN_TIMEOUT_MS) + ), + ]) + usedHttpPort = candidate + break + } catch (e) { + console.log('[hik-live] 端口 %d 登录失败(%s),尝试下一候选', candidate, e.message) + } + } + if (!loginResult || !usedHttpPort) { + console.error('[hik-live] live-stream 登录失败(所有候选端口):', ip) + sendErrorImage(res) + doCleanup() + return + } + cookieJar = loginResult.cookieJar + sessionTag = loginResult.sessionTag + + try { + // 连接复用:避免每帧 TCP 握手开销 + agent = new http.Agent({ keepAlive: true, maxSockets: 2 }) + + // Step 2: 发送 MJPEG 响应头 + res.writeHead(200, { + 'Content-Type': 'multipart/x-mixed-replace; boundary=snapshot', + 'Cache-Control': 'no-cache, no-store, must-revalidate', + Pragma: 'no-cache', + Expires: '0', + Connection: 'keep-alive', + 'Access-Control-Allow-Origin': '*', + }) + // 关键:首帧到达前没有任何 body 写入时,Node 不会把响应头发出去, + // 必须显式 flush,否则前端 fetch 探测一直挂起(表现为本地服务未启动)。 + res.flushHeaders() + + const snapshotUrl = `http://${ip}:${usedHttpPort}/ISAPI/Streaming/channels/${channelCode}/picture` + + // Step 3: 单路轮询(均匀节奏,避免并发乱序导致的画面跳帧) + const fetchFrame = async () => { + try { + const hdrs = sessionTag ? { SessionTag: sessionTag } : {} + const result = await _reqWithAgent('GET', snapshotUrl, null, hdrs, cookieJar, agent) + if (result.statusCode !== 200) { + // 节流日志:同一流上 picture 失败(503 Device Busy 等)每 10 秒最多一条 + if (Date.now() - lastPictureErrLog > 10000) { + lastPictureErrLog = Date.now() + console.log( + '[hik-live] picture 非 200:', + result.statusCode, + result.body.toString('utf-8').replace(/\s+/g, ' ').slice(0, 220) + ) + } + } + if (result.statusCode === 200 && result.body && result.body.length > 500) { + return result.body + } + if (result.statusCode === 401) { + // Session 过期,重新登录(login 内部有锁) + const relogin = await svc.login(ip, usedHttpPort, user, pass) + cookieJar = relogin.cookieJar + sessionTag = relogin.sessionTag + } + } catch (e) { + // 单次失败忽略 + } + return null + } + + const writeFrame = (jpeg) => { + if (!jpeg || closed || res.destroyed) return + // 背压保护:客户端消费慢(如预览窗最小化)时丢帧,避免内存持续增长 + if (res.writableLength < 512 * 1024) { + res.write(`--snapshot\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`) + res.write(jpeg) + res.write('\r\n') + } + } + + while (!closed) { + const loopStart = Date.now() + const jpeg = await fetchFrame() + writeFrame(jpeg) + if (interval > 0) { + const delay = Math.max(0, interval - (Date.now() - loopStart)) + if (delay > 0) await new Promise((r) => setTimeout(r, delay)) + } + } + } catch (err) { + console.error('[hik-live] live-stream 启动失败:', err.message) + if (!res.headersSent) { + sendErrorImage(res) + } + doCleanup() + } +} + +/** 与 fetchFrame 复用的二进制请求(复用 agent) */ +function _reqWithAgent(method, url, body, headers, cookieJar, agent) { + return new Promise((resolve, reject) => { + const u = new URL(url) + const cookies = Object.entries(cookieJar || {}) + .map(([k, v]) => `${k}=${v}`) + .join('; ') + const hdrs = { Accept: '*/*', 'User-Agent': 'Mozilla/5.0', ...headers } + if (cookies) hdrs['Cookie'] = cookies + const req = http.request( + { + hostname: u.hostname, + port: u.port || 80, + path: u.pathname + u.search, + method, + headers: hdrs, + timeout: REQ_TIMEOUT_MS, + agent, + }, + (res) => { + const chunks = [] + res.on('data', (c) => chunks.push(c)) + res.on('end', () => { + const raw = Buffer.concat(chunks) + resolve({ + statusCode: res.statusCode, + headers: res.headers, + body: raw, // 快照接口返回二进制 JPEG + }) + }) + } + ) + req.on('error', reject) + req.on('timeout', () => { + req.destroy() + reject(new Error('请求超时')) + }) + req.end() + }) +} + +function handleRequest(svc, req, res) { + const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`) + const pathname = url.pathname + + if (pathname === '/api/hikvision/live-stream' && req.method === 'GET') { + return handleLiveStream(svc, res, url.searchParams) + } + if (pathname === '/api/hikvision/status' && req.method === 'GET') { + return sendJson(res, 200, { success: true, source: 'wms-worker-station' }) + } + if (pathname === '/api/hikvision/config' && req.method === 'GET') { + return sendJson(res, 200, { success: true, hikvision: {} }) + } + return sendJson(res, 404, { success: false, message: 'Not Found' }) +} + +/** 探测端口是否有监听:true=被占用 / false=空闲 */ +function probePort(port = PORT) { + return new Promise((resolve) => { + const sock = net.createConnection({ host: '127.0.0.1', port }) + let settled = false + const finish = (result) => { + if (settled) return + settled = true + try { + sock.destroy() + } catch {} + resolve(result) + } + sock.setTimeout(1200) + sock.once('connect', () => finish(true)) + sock.once('timeout', () => finish(false)) + sock.once('error', () => finish(false)) + }) +} + +let activeServer = null + +/** + * 启动内置取流服务。 + * 返回 { mode: 'builtin' | 'blocked' | 'error', ... } + * port 仅测试用,生产默认 17320(前端 URL 固定)。 + */ +async function startHikvisionLiveServer(port = PORT) { + if (activeServer) { + return { mode: 'builtin', port } + } + + const occupied = await probePort(port) + if (occupied) { + console.warn(`[hik-live] ${port} 被占用,放弃启动内置取流服务`) + return { mode: 'blocked', port } + } + + return new Promise((resolve) => { + const svc = createHikvisionService() + const server = http.createServer((req, res) => handleRequest(svc, req, res)) + server.on('error', (err) => { + if (err.code === 'EADDRINUSE') { + console.warn(`[hik-live] 监听 ${port} 失败(竞态占用)`) + resolve({ mode: 'blocked', port }) + return + } + resolve({ mode: 'error', error: err.message }) + }) + server.listen(port, '127.0.0.1', () => { + activeServer = server + console.log('[hik-live] 内置海康取流服务已启动,端口:', port, '(HTTP 快照模式,~5fps,仅本机回环)') + resolve({ mode: 'builtin', port }) + }) + }) +} + +function stopHikvisionLiveServer() { + if (!activeServer) return + try { + activeServer.close() + } catch {} + activeServer = null + console.log('[hik-live] 内置取流服务已停止') +} + +module.exports = { startHikvisionLiveServer, stopHikvisionLiveServer, PORT } diff --git a/electron/main.js b/electron/main.js index 65d753d..e58943b 100644 --- a/electron/main.js +++ b/electron/main.js @@ -4,6 +4,7 @@ const fs = require('fs') const os = require('os') const https = require('https') const http = require('http') +const { startHikvisionLiveServer, stopHikvisionLiveServer } = require('./hikvision-live') const devServerUrl = process.env.ELECTRON_RENDERER_URL const rendererEntry = path.join(__dirname, '..', 'dist', 'build', 'h5', 'index.html') @@ -320,6 +321,11 @@ if (!gotTheLock) { const win = await createWindow() createTray(win) + // 内置海康取流服务(127.0.0.1:17320, HTTP 快照模式):端口空闲时自起,与 printServer(17311) 隔离 + startHikvisionLiveServer() + .then((r) => console.log('[main] 海康取流服务状态:', JSON.stringify(r))) + .catch((e) => console.error('[main] 海康取流服务启动失败:', e)) + app.on('activate', async () => { const allWindows = BrowserWindow.getAllWindows() if (allWindows.length === 0) { @@ -336,6 +342,7 @@ if (!gotTheLock) { app.on('before-quit', () => { isQuitting = true + stopHikvisionLiveServer() }) app.on('window-all-closed', () => { diff --git a/package-lock.json b/package-lock.json index 1b3a6c2..8a77b35 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "wms-worker-station", - "version": "1.0.1", + "version": "1.0.20", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "wms-worker-station", - "version": "1.0.1", + "version": "1.0.20", "devDependencies": { "@dcloudio/types": "^3.4.8", "@dcloudio/uni-app": "3.0.0-5000720260410001", @@ -19,6 +19,7 @@ "@vue/runtime-core": "^3.4.21", "electron": "^33.4.11", "electron-builder": "^26.15.3", + "jsbarcode": "^3.11.6", "vite": "5.2.8", "vue": "^3.4.21", "vue-i18n": "^9.1.9" @@ -7577,6 +7578,13 @@ "dev": true, "license": "MIT" }, + "node_modules/jsbarcode": { + "version": "3.12.3", + "resolved": "https://registry.npmjs.org/jsbarcode/-/jsbarcode-3.12.3.tgz", + "integrity": "sha512-CuHU9hC6dPsHF5oVFMo8NW76uQVjH4L22CsP4hW+dNnGywJHC/B0ThA1CTDVLnxKLrrpYdicBLnd2xsgTfRnvg==", + "dev": true, + "license": "MIT" + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://mirrors.cloud.tencent.com/npm/jsesc/-/jsesc-3.1.0.tgz", diff --git a/package.json b/package.json index de7bd4c..5767ae8 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "@vue/runtime-core": "^3.4.21", "electron": "^33.4.11", "electron-builder": "^26.15.3", + "jsbarcode": "^3.11.6", "vite": "5.2.8", "vue": "^3.4.21", "vue-i18n": "^9.1.9" diff --git a/src/api/camera.ts b/src/api/camera.ts new file mode 100644 index 0000000..e7e8a2f --- /dev/null +++ b/src/api/camera.ts @@ -0,0 +1,65 @@ +import { request, type ApiBody, type RequestOptions } from './request' + +/** + * 摄像头(camera.* / camera_server.*)接口。 + * 参考散单 Web 端 @/api/camera/camera 与 @/api/camera_server 移植, + * 按本工程 request(method, data) 约定(POST /system?method=xxx)。 + */ + +const workerPayload = { + device: 'workerstation', + project: 'warehouse', +} + +/** camera.list:摄像头列表(仓库隔离,分页/筛选) */ +export function cameraList( + data: { + pagination?: { page?: number; pageSize?: number } + where?: { server_id?: number; custom_name?: string; status?: number } + } = {}, + options?: RequestOptions +) { + return request('camera.list', { ...workerPayload, ...data }, options) +} + +/** camera.setOsd:设置摄像头 OSD 文字叠加 */ +export function cameraSetOsd( + data: { id: number; text: string; x?: number; y?: number }, + options?: RequestOptions +) { + return request('camera.setOsd', { ...workerPayload, ...data }, options) +} + +/** camera_server.list:录像服务器列表 */ +export function cameraServerList( + data: { + pagination?: { page?: number; pageSize?: number } + where?: { name?: string; status?: number } + } = {}, + options?: RequestOptions +) { + return request('camera_server.list', { ...workerPayload, ...data }, options) +} + +/** camera_server.detail:录像服务器详情(含密码等敏感字段) */ +export function cameraServerDetail(data: { id: number }, options?: RequestOptions) { + return request('camera_server.detail', { ...workerPayload, ...data }, options) +} + +/** + * 生成本地视频代理服务的 MJPEG 实时流 URL。 + * 与散单 Web 端 localServerApi.getLiveStreamUrl 一致: + * 后端 GET /api/hikvision/live-stream 返回 multipart MJPEG 流,前端直接用 渲染。 + */ +export function getLiveStreamUrl(params: { + ip: string + user: string + pass: string + channel: number + streamType?: number + port?: number +}): string { + const { ip, user, pass, channel, streamType = 0, port } = params + const portParam = port ? `&port=${port}` : '' + return `http://localhost:17320/api/hikvision/live-stream?ip=${encodeURIComponent(ip)}&user=${encodeURIComponent(user)}&pass=${encodeURIComponent(pass)}&channel=${channel}&streamType=${streamType}${portParam}` +} diff --git a/src/api/request.ts b/src/api/request.ts index d5b0421..94c4fd4 100644 --- a/src/api/request.ts +++ b/src/api/request.ts @@ -69,6 +69,56 @@ export type AbortablePromise = Promise & { abort?: () => void } +// ==================== 全局 401 处理 ==================== +// 鉴权请求返回 401(令牌无效/过期)时:清除本地 token 并回登录页。 +// 仅处理非 skipAuth 请求:登录/取码/工作台 token 请求由各自页面自行处理 +// (工作台 401/403 走 packaging 页的 handleWorkbenchAuthExpired 逻辑)。 +let lastUnauthorizedRedirectAt = 0 +let unauthorizedRedirecting = false + +function handleUnauthorized() { + const now = Date.now() + if (unauthorizedRedirecting || now - lastUnauthorizedRedirectAt < 3000) { + return + } + lastUnauthorizedRedirectAt = now + unauthorizedRedirecting = true + try { + uni.removeStorageSync('token') + } catch { + // 清理失败不阻断 + } + // 当前已在登录页则不跳转,避免死循环 + let route = '' + try { + const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [] + const top = pages && pages.length ? pages[pages.length - 1] : null + route = top && top.route ? String(top.route) : '' + } catch { + // 取页面栈失败忽略 + } + if (route === 'pages/login/login') { + unauthorizedRedirecting = false + return + } + uni.showToast({ + title: '登录已过期,请重新登录', + icon: 'none', + }) + setTimeout(() => { + uni.reLaunch({ + url: '/pages/login/login', + complete: () => { + unauthorizedRedirecting = false + }, + }) + }, 600) + // 兜底:reLaunch complete 未回调时解除重定向标记,避免后续 401 被永久忽略 + setTimeout(() => { + unauthorizedRedirecting = false + }, 5000) +} + export function request( method: string, data?: Record, @@ -90,7 +140,17 @@ export function request( }, data: data ?? {}, success: (res) => { - resolve(res.data as T) + const body = res.data as any + // 鉴权请求返回 401(令牌无效/过期)→ 清 token 回登录页 + if ( + !options?.skipAuth && + body && + typeof body === 'object' && + (Number(body.code) === 401 || Number(body.status) === 401) + ) { + handleUnauthorized() + } + resolve(body as T) }, fail: (err) => { reject(err) diff --git a/src/api/returnunpack.ts b/src/api/returnunpack.ts new file mode 100644 index 0000000..0e088b3 --- /dev/null +++ b/src/api/returnunpack.ts @@ -0,0 +1,316 @@ +import { request, type ApiBody, type RequestOptions } from './request' + +/** + * 退件拆包(returnUnpack.*)接口。 + * 参考散单 Web 端 returnUnpackwork 的 @/api/returnunpack,按本工程 request(method, data) 约定移植。 + * 后端约定:POST /system?method=returnUnpack.xxx,数据体带 workerPayload。 + */ + +const workerPayload = { + device: 'workerstation', + project: 'warehouse', +} + +/** 拆包单主表状态 */ +export type ReturnUnpackStatus = 'unpacking' | 'completed' | 'cancelled' + +/** returnUnpack.create:按运单号开拆包单(幂等,同运单复用已有拆包单) */ +export function returnUnpackCreate( + data: { waybill_code: string; camera_ids?: number[]; remark?: string }, + options?: RequestOptions +) { + return request('returnUnpack.create', { ...workerPayload, ...data }, options) +} + +/** returnUnpack.addDetail:以拆包单 ID 录入一条明细 */ +export function returnUnpackAddDetail( + data: { + id: number + stock_id?: number | null + barcode?: string + quantity?: number + product_status?: 'normal' | 'damaged' + remark?: string + }, + options?: RequestOptions +) { + return request('returnUnpack.addDetail', { ...workerPayload, ...data }, options) +} + +/** returnUnpack.updateDetail:更新明细数量/备注 */ +export function returnUnpackUpdateDetail( + data: { id: number; detail_id: number; quantity?: number; remark?: string }, + options?: RequestOptions +) { + return request('returnUnpack.updateDetail', { ...workerPayload, ...data }, options) +} + +/** returnUnpack.removeDetail:删除拆包单下一条明细(硬删除) */ +export function returnUnpackRemoveDetail( + data: { id: number; detail_id: number }, + options?: RequestOptions +) { + return request('returnUnpack.removeDetail', { ...workerPayload, ...data }, options) +} + +/** returnUnpack.submit:提交确认(转 completed 终态) */ +export function returnUnpackSubmit(data: { id: number }, options?: RequestOptions) { + return request('returnUnpack.submit', { ...workerPayload, ...data }, options) +} + +/** returnUnpack.cancel:取消拆包单(仅供未完成状态作业取消) */ +export function returnUnpackCancel(data: { id: number }, options?: RequestOptions) { + return request('returnUnpack.cancel', { ...workerPayload, ...data }, options) +} + +/** returnUnpack.delete:删除拆包单(物理删除,含全部明细) */ +export function returnUnpackDelete(data: { id: number }, options?: RequestOptions) { + return request('returnUnpack.delete', { ...workerPayload, ...data }, options) +} + +/** returnUnpack.detail:拆包单详情(主表 + 明细 + 视频副表) */ +export function returnUnpackDetail(data: { id: number }, options?: RequestOptions) { + return request('returnUnpack.detail', { ...workerPayload, ...data }, options) +} + +/** returnUnpack.detailList:拆包明细分页列表(识别命中商品时含 stockWarehouse 关联) */ +export function returnUnpackDetailList( + data: { + pagination?: { page?: number; pageSize?: number } + where?: { + unpack_id?: number + stock_id?: number + barcode?: string | { operator: string; value: unknown } + is_recognized?: 0 | 1 + product_status?: 'normal' | 'damaged' + } + sort?: { sortField?: string; sortOrder?: 'asc' | 'desc' } + } = {}, + options?: RequestOptions +) { + return request('returnUnpack.detailList', { ...workerPayload, ...data }, options) +} + +/** + * stock.warehouse.search:商品条码/关键字搜索(扫描条码反查系统商品)。 + * 与散单 Web 端 warehouseSearch 一致,data 可为数组或 { list, total }。 + */ +export function stockWarehouseSearch( + data: { keyword?: string; store_id?: number; with_stock?: boolean; is_batch?: boolean }, + options?: RequestOptions +) { + return request('stock.warehouse.search', { ...workerPayload, ...data }, options) +} + +/** + * order.detail:拆包单原运单反查原订单商品明细。 + * 参数与散单 Web 端 returnUnpackwork 的 loadOrderDetail 保持一致(id + ids + tableType)。 + */ +export function fetchOrderDetailForUnpack(orderId: number | string, options?: RequestOptions) { + return request( + 'order.detail', + { + ...workerPayload, + id: orderId, + ids: [orderId], + tableType: 'order', + }, + options + ) +} + +/** + * order.list:按运单号反查原订单(拆包单原运单 → 原订单商品对照)。 + */ +export function fetchOrderListByWaybill(waybill: string, options?: RequestOptions) { + return request( + 'order.list', + { + ...workerPayload, + where: { waybill_codes: [waybill] }, + pagination: { page: 1, pageSize: 1 }, + }, + options + ) +} + +// ============ 通用判定/解析辅助 ============ + +/** 是否成功响应(兼容 flag / code 两种约定) */ +export function isReturnUnpackOk(res: unknown): boolean { + if (!res || typeof res !== 'object') return false + const body = res as Record + if (body.flag === 'failure') return false + if (body.flag === 'success') return true + if (body.code != null) { + return body.code === 1 || body.code === 200 || body.code === 20000 + } + return true +} + +/** 提取错误文案 */ +export function returnUnpackErrMsg(res: unknown, fallback: string): string { + if (res && typeof res === 'object') { + const body = res as Record + const msg = body.message || body.msg + if (msg) return String(msg) + } + return fallback +} + +/** 提取接口 data 层(res.data 优先,缺失回退 res 本身) */ +export function pickApiData(res: unknown): any { + if (res && typeof res === 'object') { + const body = res as Record + if (body.data != null) return body.data + } + return res +} + +/** 解析 stock.warehouse.search 响应:data 为数组或 { list, total } */ +export function parseStockWarehouseSearch(res: unknown): { list: any[]; total: number } { + if (!isReturnUnpackOk(res)) return { list: [], total: 0 } + const payload = pickApiData(res) + let list: any[] = [] + if (Array.isArray(payload?.list)) list = payload.list + else if (Array.isArray(payload)) list = payload + else if (Array.isArray(res?.list)) list = (res as any).list + else if (Array.isArray(res?.data)) list = (res as any).data + const total = Number(payload?.total ?? (res as any)?.total ?? list.length) + return { list, total: Number.isFinite(total) ? total : list.length } +} + +/** 从搜索行提取系统商品 ID(wms_stock_warehouse.id,供 addDetail 的 stock_id 使用) */ +export function getStockItemId(row: any): number | undefined { + const candidates = [ + row?.item_id, + row?.id, + row?.store_stock?.item_id, + row?.store_stock?.id, + row?.stock?.item_id, + row?.stock?.id, + row?.goods?.item_id, + row?.goods?.id, + ] + for (const candidate of candidates) { + const itemId = Number(candidate) + if (Number.isInteger(itemId) && itemId > 0) return itemId + } + return undefined +} + +/** 从搜索行提取商品编码 */ +export function getStockItemCode(row: any): string { + const candidates = [ + row?.item_code, + row?.goods_code, + row?.store_stock?.item_code, + row?.store_stock?.goods_code, + row?.stock?.item_code, + row?.stock?.goods_code, + row?.goods?.item_code, + row?.goods?.goods_code, + ] + for (const candidate of candidates) { + const text = String(candidate ?? '').trim() + if (text && text.toLowerCase() !== 'null') return text + } + return '' +} + +/** 从搜索行提取商品名称 */ +export function getStockItemName(row: any): string { + const candidates = [ + row?.item_name, + row?.product_name, + row?.goods_name, + row?.name, + row?.store_stock?.item_name, + row?.store_stock?.product_name, + row?.stock?.item_name, + row?.goods?.item_name, + row?.goods?.product_name, + ] + for (const candidate of candidates) { + const text = String(candidate ?? '').trim() + if (text && text.toLowerCase() !== 'null') return text + } + return '' +} + +/** 从搜索行提取条码(数组取第一条、单值兜底) */ +export function getStockBarcode(row: any): string { + const arrayCandidates = [ + row?.barcodes, + row?.store_stock?.barcodes, + row?.stock?.barcodes, + row?.goods?.barcodes, + ] + for (const candidate of arrayCandidates) { + if (!Array.isArray(candidate)) continue + for (const item of candidate) { + const text = String(item?.barcode ?? item ?? '').trim() + if (text) return text + } + } + const singleCandidates = [ + row?.barcode, + row?.store_stock?.barcode, + row?.stock?.barcode, + row?.goods?.barcode, + ] + for (const candidate of singleCandidates) { + const text = String(candidate ?? '').trim() + if (text && text.toLowerCase() !== 'null') return text + } + return '' +} + +/** 从搜索行提取货主 ID */ +export function getStockStoreId(row: any): number | undefined { + const storeId = Number(row?.store_stock?.store_id ?? row?.store_id) + return Number.isFinite(storeId) && storeId > 0 ? storeId : undefined +} + +/** 搜索行归一化为商品选择项(与散单 Web 端 mapStockPickerItem 一致) */ +export function mapStockPickerItem(row: any): any { + return { + ...row, + item_id: getStockItemId(row), + item_code: getStockItemCode(row), + item_name: getStockItemName(row), + barcode: getStockBarcode(row), + } +} + +/** order.detail 商品明细解析(优先 orderItems,兼容 items 及嵌套字段) */ +export function normalizeOrderDetailItems(data: any): any[] { + const normalize = (rows: any[]) => + Array.isArray(rows) + ? rows.map((row) => { + if (!row || typeof row !== 'object') return row + if (Array.isArray(row.images)) return row + const urls = Array.isArray(row.image_url) + ? row.image_url + : typeof row.image_url === 'string' && row.image_url + ? [row.image_url] + : [] + return urls.length ? { ...row, images: urls } : row + }) + : [] + + if (!data || typeof data !== 'object') return [] + if (Array.isArray(data.orderItems)) return normalize(data.orderItems) + if (Array.isArray(data.items)) return normalize(data.items) + const rawItems = data.order?.items || data.detail?.items + if (Array.isArray(rawItems)) return normalize(rawItems) + if (typeof rawItems === 'string') { + try { + const parsed = JSON.parse(rawItems) + return Array.isArray(parsed) ? normalize(parsed) : [] + } catch { + return [] + } + } + return [] +} diff --git a/src/pages/index/index.vue b/src/pages/index/index.vue index 6ace989..41310ae 100644 --- a/src/pages/index/index.vue +++ b/src/pages/index/index.vue @@ -172,6 +172,7 @@ export default { this.loadCurrentUserInfo() }, handleMenuClick(menu) { + const rawPath = String(menu?.path || '').trim() if (!rawPath) { uni.showToast({ title: '菜单路径为空', @@ -261,7 +262,9 @@ export default { diff --git a/src/pages/login/login.vue b/src/pages/login/login.vue index 90af647..dce7c5f 100644 --- a/src/pages/login/login.vue +++ b/src/pages/login/login.vue @@ -50,8 +50,10 @@ class="input input--with-clear" v-model="form.username" placeholder="请输入账号" + confirm-type="next" @focus="handleFocus('username')" @blur="handleBlur" + @confirm="handleUsernameConfirm" /> × @@ -63,8 +65,11 @@ v-model="form.password" placeholder="请输入密码" :password="!showPassword" + :focus="passwordFocus" + confirm-type="done" @focus="handleFocus('password')" @blur="handleBlur" + @confirm="handlePasswordConfirm" /> × @@ -199,6 +204,7 @@ export default { eyeOffSvg: '', focusedField: '', + passwordFocus: false, scanLoading: false, scanBadgeSubmitting: false, scanBadgeLastSubmittedCode: '', @@ -1680,7 +1686,13 @@ export default { code, body, }) - const token = body?.token || body?.data?.token || body?.result?.token + const token = + body?.loginToken || + body?.token || + body?.data?.loginToken || + body?.data?.token || + body?.result?.loginToken || + body?.result?.token if (token) { this.scanInputFocus = false @@ -1733,6 +1745,40 @@ export default { this.scanBadgeSubmitting = false }) }, + /** 账号输入框回车:密码已有内容则直接登录,否则聚焦密码框 */ + handleUsernameConfirm(e) { + if (!this.isPageActive()) { + return + } + if (e && e.detail && e.detail.value != null) { + this.form.username = e.detail.value + } + if (String(this.form.password || '').trim()) { + this.handleAccountLogin() + } else { + this.focusPasswordField() + } + }, + /** 密码输入框回车:账号已有内容则直接登录 */ + handlePasswordConfirm(e) { + if (!this.isPageActive()) { + return + } + if (e && e.detail && e.detail.value != null) { + this.form.password = e.detail.value + } + if (String(this.form.username || '').trim()) { + this.handleAccountLogin() + } + }, + focusPasswordField() { + this.passwordFocus = false + this.$nextTick(() => { + if (this.isPageActive()) { + this.passwordFocus = true + } + }) + }, handleAccountLogin() { if (!this.isPageActive()) { return @@ -1750,7 +1796,13 @@ export default { if (!this.isPageActive()) { return } - const token = body?.token || body?.data?.token || body?.result?.token + const token = + body?.loginToken || + body?.token || + body?.data?.loginToken || + body?.data?.token || + body?.result?.loginToken || + body?.result?.token if (token) { this.scanInputFocus = false @@ -2292,6 +2344,12 @@ export default { .password-input { margin-bottom: 0; padding-right: 3.994rem; + font-family: system-ui; +} + +/* H5/APP 视图层下输入框真实 元素:密码圆点字体统一为系统字体 */ +.password-input .uni-input-input { + font-family: system-ui; } .input--with-clear { @@ -2358,6 +2416,7 @@ export default { .primary-btn { width: 100%; margin-top: 0.41rem; + font-size: 0.8rem; } .scan-login-btn { diff --git a/src/pages/returns/index.vue b/src/pages/returns/index.vue index 472ac9d..27f261a 100644 --- a/src/pages/returns/index.vue +++ b/src/pages/returns/index.vue @@ -2,18 +2,484 @@ - - - 退件 - 退件模块页面(待对接业务接口) + + + + + + 拆包工作台 + + + + + + + + 手动输入 + + + + + + 运单号 + {{ waybillCode || '等待扫描运单号' }} + + + + + 产品状态 + + 正常 + 破损 + + + + + + 商品条码 + {{ lastScannedBarcode || '—' }} + + + + + 数量 + + + + + + 货主 + {{ storeLabel || '—' }} + + + + + + + + + + + + + 📟 扫码指令 + + + {{ CMD_LABEL[cmd] }} + ● 当前 + + + {{ CMD[cmd] }} + + + + + + + + + 开单结果 + + + 拆包单号 + {{ unpackRecord.unpack_no || '—' }} + + + 运单号 + {{ unpackRecord.waybill_code || '—' }} + + + 拆包状态 + {{ statusLabel() }} + + + 原单退回 + {{ createResult.is_original_return ? '是' : '否' }} + + + 货主备注 + {{ createResult.store_remark || '—' }} + + + 扫描运单号创建拆包单 + + + + + + 原订单 {{ compareSummary.orderTypes }} 类 / {{ compareSummary.orderQty }} 件 + 已扫描 {{ compareSummary.unpackTypes }} 类 / {{ compareSummary.unpackQty }} 件 + + + 一致 {{ compareSummary.matched }} + 数量差异 {{ compareSummary.qtyDiff }} + 仅订单 {{ compareSummary.orderOnly }} + 仅拆包 {{ compareSummary.unpackOnly }} + + + + + + + 拆包明细({{ detailTotal }} 项) + + + + + 明细加载中... + + + + + 原单商品 + 订单 {{ compareSummary.orderQty }} 件 + + + + + {{ o.name }} + {{ o.code }} + {{ o.spec }} + + + 订单:{{ o.qty }} + 退回:{{ o.returned }} + 差异:{{ formatDiff(o.diff) }} + + + 无原单商品 + + + + + + + + + + — + + + + + + 拆包 + {{ row.__unpack.name || '未识别商品' }} + {{ row.__unpack.code || row.barcode || '—' }} + {{ row.__unpack.spec }} + + + + + + + − + {{ row.quantity }} + + + + + + + + {{ row.product_status === 'damaged' ? '破损' : '正常' }} + + + + + {{ row.remark || '备注' }} + + + + 暂无明细,扫描商品条码录入 + + + + + + + {{ detailPage }} / {{ detailMaxPage }} + + + + + + + + + 选择备注 + × + + + + {{ opt }} + × + + 暂无备注选项,可在下方新增 + + + + + + + + + + + + + 摄像头设置 + × + + 已选 {{ selectedCameraIds.length }} 个摄像头(保存后生效) + + 摄像头列表加载中... + + {{ selectedCameraIds.indexOf(cam.id) !== -1 ? '☑' : '☐' }} + {{ cameraLabel(cam) }} + + 暂无摄像头 + + + + + + + + + + + + {{ activeCamera ? cameraLabel(activeCamera) : '摄像头预览' }} + + + {{ activeCamera ? cameraLabel(activeCamera) : '选择' }} ▾ + + {{ floatFullscreen ? '⤡' : '⛶' }} + - + + + + + + {{ previewLoading ? '正在连接录像机…' : previewError || '无信号' }} + + + APP 端暂不支持实时预览,字幕推送不受影响 + + + + + + + 📷 预览 + + + + + diff --git a/src/router/menuRoutes.js b/src/router/menuRoutes.js index bb926fc..f63fbdd 100644 --- a/src/router/menuRoutes.js +++ b/src/router/menuRoutes.js @@ -13,12 +13,16 @@ export function normalizeMenuPath(path) { /** * 后端动态菜单 path -> 本地页面组件 - * 新增菜单时在此注册对应页面组件 + * 新增菜单时在此注册对应页面组件。 + * 同时兼容后端短路径(/order)与本地完整路径(/pages/order/index,top-nav 默认菜单兜底用)。 */ const menuRouteMap = { '/order': OrderPage, + '/pages/order/index': OrderPage, '/catchWeight': CatchWeightPage, + '/pages/weighing/index': CatchWeightPage, '/returns': ReturnsPage, + '/pages/returns/index': ReturnsPage, } /** 根据菜单 path 解析要渲染的页面组件 */