Compare commits

..

8 Commits

Author SHA1 Message Date
liufumingren
a34b194211 chore(release): 版本号 1.0.34 + 精简 APK 打包入口
删除 android:pack(= build:apk 同一脚本的别名) 与 android:prepare(pack.ps1 内部直接调 prepare.cjs 文件,无需别名);发布入口统一 build:apk,真机调试 dev:adb,android:pack:raw 保留为两者共用的内部步骤。同步 scripts/build-apk.cjs 用法注释与 config/README.md、android-offline/README.md。
2026-09-25 03:04:51 +08:00
liufumingren
72cecc8d63 feat(scan-diag): 补齐一次性发版所需的日志面 - Window焦点/输入法状态入心跳、非正常退出检测、10分钟健康快照、无结束符扫码异常 2026-09-25 01:50:21 +08:00
liufumingren
1f11cc05d2 feat(scan-diag): flush 记录本次扫码按键数与最后按键;打包页 plus 链路对 1~3 字符做最小长度拦截 2026-09-25 01:46:19 +08:00
liufumingren
ffd42fca33 feat(error-report): 接入 index.uploadClientErrorLog - 运行时异常/扫码链路异常自动批量上报(幂等+限流+持久化队列+面板手动上报) 2026-09-25 01:42:08 +08:00
liufumingren
7b3e6f1f79 feat(scan-diag): 记录扫码起始按键原始keyCode/type、主线程卡顿(stall)检测、事件带页面scope 2026-09-25 01:36:54 +08:00
liufumingren
dd3eb8319e fix(env): dev:adb 真机包默认注入 .env.local 的开发接口地址(新增 VITE_API_BASE_OVERRIDE,发布包仍强制生产) 2026-09-25 01:36:52 +08:00
liufumingren
7820b29d6e feat(scan-diag): 日志补日期+毫秒时间戳,记录收到的条码与期望条码上下文 2026-09-25 01:20:19 +08:00
liufumingren
1eb8a1dfe5 feat(scan): 扫码链路诊断埋点与长时间运行自愈(事件类型锁重置/空闲重挂监听)+现场诊断面板 2026-09-25 00:35:19 +08:00
18 changed files with 2095 additions and 28 deletions

View File

@ -1,5 +1,7 @@
# 环境变量模板:复制本文件为 .env.local 并填写真实值(.env.local 不提交 git)
# 详见 config/README.md
# 仅开发环境生效:生产构建(electron/Android 打包)固定使用 https://qimen.wms.gztbyc.com,见 env.js
# 生效范围:① npm run dev:h5(dev server) ② npm run dev:adb(真机调试,脚本会把下面的地址注入为 VITE_API_BASE_OVERRIDE)
# 发布构建(electron/Android 打包)固定使用 https://qimen.wms.gztbyc.com,见 env.js
# 注意:不要把 VITE_API_BASE_OVERRIDE 写进 .env* 文件,它只能由命令行显式注入(防止测试地址进发布包)
VITE_API_BASE_URL=http://your-server-ip:6060
VITE_IMG_URL=https://your-img-domain.com

View File

@ -48,11 +48,11 @@ android-offline/
## 3. 离线打包流程(命令打包,无需 Android Studio)
1. 生成 App 资源:`npm run build:app`(或 HBuilderX「发行 → 原生App-本地打包」,产物路径写到 `pack-config.json` 的 `wwwSource`)
2. 一条命令注入配置并打包 APK:
2. 一条命令编译前端 + 注入配置并打包 APK:
```
npm run android:pack
npm run build:apk
```
即 `powershell -NoProfile -ExecutionPolicy Bypass -File android-offline\pack.ps1`,自动完成:
即 `node scripts/build-apk.cjs` —— **强制生产编译**(注入生产接口域名、并校验产物里不得有开发地址,否则中止),再调用 `pack.ps1`,自动完成:
- 探测 JDK / Android SDK 并生成 `local.properties`
- 执行准备(`prepare.cjs`):拷贝 App 资源到工程、覆盖图标/启动图
- `gradlew assembleRelease` 命令行构建(Gradle 动态读取 `config/android.json` 与 `package.json` 获得包名/版本/签名/应用名/appid/appKey)

View File

@ -15,7 +15,22 @@
> ⚠️ **appKey 必须与 appId 严格匹配**,留空或填其他应用的 key 时,APK 启动会白屏提示“未配置appkey或配置错误”(5+ Runtime 启动校验)。本应用与散单项目共用包名/签名/appid(`__UNI__900BDC1`),因此直接复用散单已申请的离线打包 Key,无需再申请。若日后更换 appid/证书/包名,需到 https://dev.dcloud.net.cn → 应用详情 → Android → 离线打包 Key 管理重新申请(需填包名与证书 SHA-256 指纹)。
`deploy.json` 字段说明:android 段(APK 发布,`android:pack` 打包后自动 scp 上传)与 windows 段(exe 发布,`build:exe` 打包后自动 scp 上传),每段含 host(服务器 IP)、port(SSH 端口)、user(SSH 用户)、keyPath(SSH 私钥路径)、remoteDir(服务器上传目录:APK 与散单项目同为 worker_station,exe 为 worker_station_windows)、downloadUrlPrefix(下载 URL 前缀)、latestJsonName(latest.json 文件名)。跳过上传:`-NoUpload`(APK)/ `--no-upload`(exe)。
`deploy.json` 字段说明:android 段(APK 发布,`build:apk` 打包后自动 scp 上传)与 windows 段(exe 发布,`build:exe` 打包后自动 scp 上传),每段含 host(服务器 IP)、port(SSH 端口)、user(SSH 用户)、keyPath(SSH 私钥路径)、remoteDir(服务器上传目录:APK 与散单项目同为 worker_station,exe 为 worker_station_windows)、downloadUrlPrefix(下载 URL 前缀)、latestJsonName(latest.json 文件名)。跳过上传:`-NoUpload`(APK)/ `--no-upload`(exe)。
## 真机调试(dev:adb)的接口地址
`npm run build:app` 是 **Vite 生产构建**,`env.js` 里 `import.meta.env.PROD` 为真 → 默认固定指向生产域名 `https://qimen.wms.gztbyc.com`。所以**直接跑 `npm run dev:adb` 装到真机的包连的是生产库**(脚本名里的 dev 只指"改代码自动重编重装"的调试闭环,不是环境)。
`npm run dev:adb` 现在会读 `.env.local` 的 `VITE_API_BASE_URL`,通过命令行环境变量 `VITE_API_BASE_OVERRIDE` 注入编译:
| 命令 | 接口地址 |
|---|---|
| `npm run dev:adb` | 默认注入 `.env.local` 的地址(未配置 `.env.local` 时退回生产域名) |
| `npm run dev:adb -- --prod-api` | 不注入,产出与发布包一致的生产环境包 |
| `npm run dev:adb -- --api=http://192.168.1.10:6060` | 使用指定地址 |
> ⚠️ `VITE_API_BASE_OVERRIDE` 是"显式注入才生效"的开关,**不要写进 `.env*` 文件**:写进文件会让发布包也带上测试地址(会被 `scripts/build-apk.cjs` 的产物校验中止)。
> 现场确认某台设备连的是哪个后端:打包页标题 / 退件页「拆包工作台」3 秒内连点 5 次,诊断面板首行会显示 `版本` 与 `接口`。
## 根目录其他配置
@ -23,7 +38,7 @@
|---|---|---|
| `.env` / `.env.electron` | Vite 构建目标(web/electron),无敏感信息 | ✅ 提交 |
| `.env.example` | 环境变量模板(接口地址等),复制为 `.env.local` 填写 | ✅ 提交 |
| `.env.local` | 本地开发环境变量(含内网测试接口地址,勿提交;**仅 dev 生效**,生产构建固定走 `https://qimen.wms.gztbyc.com`,见 `env.js`) | ❌ 不提交(匹配 `*.local`) |
| `.env.local` | 本地开发环境变量(含内网测试接口地址,勿提交)。生效范围:`npm run dev:h5`(dev server)与 `npm run dev:adb`(真机调试脚本会把 `VITE_API_BASE_URL` 注入为 `VITE_API_BASE_OVERRIDE` 参与编译);**发布构建固定走 `https://qimen.wms.gztbyc.com`**,见 `env.js` | ❌ 不提交(匹配 `*.local`) |
| `env.js` | 前端环境模块(读 Vite 环境变量,不写死敏感地址) | ✅ 提交 |
| `electron-builder.config.cjs` | exe 打包配置(无敏感) | ✅ 提交 |
@ -42,4 +57,4 @@
2. `cp config/deploy.example.json config/deploy.json` 并填写(仅发布 APK 时需要)
3. `cp .env.example .env.local` 并填写接口地址
3. `npm install`
4. 打包:`npm run build:apk`(Android 一键打包+发布,或拆分为 `npm run build:app` + `npm run android:pack`)、`npm run build:exe`(Windows,发布到 worker_station_windows)
4. 打包:`npm run build:apk`(Android 一键打包+发布;仅改了原生工程、前端产物已是最新时可跳过重编,用 `npm run android:pack:raw`)、`npm run build:exe`(Windows,发布到 worker_station_windows)

14
env.js
View File

@ -2,9 +2,17 @@
// 避免构建机上残留的 .env.local 测试地址被带进生产包
const PROD_API_BASE = 'https://qimen.wms.gztbyc.com'
// 构建期「显式」指定的接口地址(真机调试用):
// 只有从命令行环境变量注入 VITE_API_BASE_OVERRIDE 才生效——该变量不写入任何 .env 文件,
// 所以即使构建机上存在带开发地址的 .env.local,生产打包也不会被它影响(见 scripts/build-apk.cjs 的地址校验)。
// 注入方:npm run dev:adb(默认取 .env.local 的地址,可用 --prod-api 关闭)。
const overrideApiBase = import.meta.env.VITE_API_BASE_OVERRIDE || ''
// 开发环境地址走 Vite 环境变量(见 .env.example / .env.local,敏感地址勿提交 git)
export const BASE_URL = import.meta.env.PROD
? PROD_API_BASE
: import.meta.env.VITE_API_BASE_URL || '' // 接口根地址,开发时由 .env.local 注入
export const BASE_URL = overrideApiBase
? overrideApiBase
: import.meta.env.PROD
? PROD_API_BASE
: import.meta.env.VITE_API_BASE_URL || '' // 接口根地址,开发时由 .env.local 注入
export const API_URL = `${BASE_URL}/system` // 后台接口域名
export const IMG_URL = import.meta.env.VITE_IMG_URL || 'https://ye4s.file.gzxunren.com' // 全局网络图片地址变量,css背景图片地址变量在uni.scss

View File

@ -1,6 +1,6 @@
{
"name": "wms-worker-station",
"version": "1.0.33",
"version": "1.0.34",
"description": "WMS仓库工作台桌面端",
"author": "tianbao",
"main": "electron/main.js",
@ -14,8 +14,6 @@
"build:app": "uni build -p app",
"build:exe": "node scripts/build-exe.cjs",
"build:apk": "node scripts/build-apk.cjs",
"android:prepare": "node android-offline/prepare.cjs",
"android:pack": "node scripts/build-apk.cjs",
"android:pack:raw": "powershell -NoProfile -ExecutionPolicy Bypass -File android-offline/pack.ps1",
"start:electron": "electron electron/main.js"
},

View File

@ -14,9 +14,12 @@
* 3. 产物防御性校验:dist/build/app 必须包含生产域名、不得包含开发地址,否则中止。
*
* 用法:
* npm run android:pack # 编译 + 打包 + 发布上传(pack.ps1 默认行为)
* npm run android:pack -- -NoUpload # 编译 + 打包,跳过发布上传
* npm run build:apk # 同 android:pack
* npm run build:apk # 编译 + 打包 + 发布上传(pack.ps1 默认行为)
* npm run build:apk -- -NoUpload # 编译 + 打包,跳过发布上传
* npm run build:apk -- -Clean # gradle 全量重编
*
* 对外入口:build:apk(发布)、dev:adb(真机调试)、build:app(只编前端);
* android:pack:raw 是本脚本与 dev:adb 共用的内部步骤,不对外暴露。
*/
const { spawnSync } = require('child_process')
const fs = require('fs')
@ -61,6 +64,9 @@ if (
env: {
NODE_ENV: 'production',
VITE_API_BASE_URL: PROD_API_BASE,
// 显式关闭真机调试(dev:adb)的地址覆盖,避免本机 shell 里残留的
// VITE_API_BASE_OVERRIDE 把测试地址带进发布包
VITE_API_BASE_OVERRIDE: '',
},
})
) {

View File

@ -8,6 +8,13 @@
* npm run dev:adb # 自动选唯一设备
* npm run dev:adb -- --no-launch # 重装后不自动启动应用
* npm run dev:adb -- --adb=adb路径 # 自定义 adb 路径
* npm run dev:adb -- --prod-api # 不注入开发地址,产出与发布包一致的生产环境包
* npm run dev:adb -- --api=http://192.168.1.10:6060 # 指定接口地址
*
* 接口地址(重要):build:app 是 Vite 生产构建,env.js 默认会固定指向生产域名
* (见 env.js 的 PROD_API_BASE)。本脚本默认把 .env.local 里的 VITE_API_BASE_URL
* 通过 VITE_API_BASE_OVERRIDE 注入编译,避免真机调试打到生产库;
* 该变量不写入任何 .env 文件,因此不会影响正式发布包。
*
* 变更监听范围:
* src/(uni-app 前端资源)
@ -72,7 +79,46 @@ const WATCH_EXTS = new Set([
'.vue', '.js', '.ts', '.json', '.scss', '.css', '.cjs', '.ps1', '.xml', '.java', '.png', '.jpg', '.jpeg', '.md',
])
// ---------- 接口环境(真机调试选地址)----------
/** 读取 .env.local 里指定键的值(文件不存在/未配置时返回空) */
function readEnvLocal(key) {
try {
const text = fs.readFileSync(path.join(ROOT, '.env.local'), 'utf-8')
for (const line of text.split(/\r?\n/)) {
const matched = line.match(/^\s*([A-Za-z0-9_]+)\s*=\s*(.*)$/)
if (matched && matched[1] === key) {
return matched[2].trim().replace(/^["']|["']$/g, '')
}
}
} catch (e) {
// 忽略:文件缺失视为未配置
}
return ''
}
/** 解析本次真机包的接口地址(返回空字符串 = 不注入,沿用构建默认即生产域名) */
function resolveApiTarget() {
if (process.argv.includes('--prod-api')) {
return { base: '', note: '--prod-api 指定,与发布包一致' }
}
const argApi = process.argv.find((a) => a.startsWith('--api='))
if (argApi) {
return { base: argApi.slice('--api='.length), note: '命令行 --api 指定' }
}
const dev = readEnvLocal('VITE_API_BASE_URL')
if (dev) {
return { base: dev, note: '.env.local 的 VITE_API_BASE_URL' }
}
return { base: '', note: '未配置 .env.local,沿用构建默认(生产域名)' }
}
const API_TARGET = resolveApiTarget()
const BUILD_ENV = API_TARGET.base ? { VITE_API_BASE_OVERRIDE: API_TARGET.base } : {}
const log = (msg) => console.log(`[dev-adb] ${msg}`)
// 启动即声明本次真机包的接口地址(长驻 watch 中每次构建还会再打一次)
log(`接口地址 = ${API_TARGET.base || 'https://qimen.wms.gztbyc.com(生产)'} 〔${API_TARGET.note}〕`)
const run = (cmd, args, opts = {}) => {
// Windows 下通过 shell 执行,自动解析 npm.cmd / 全路径 exe
const res = spawnSync(cmd, args, {
@ -208,8 +254,11 @@ let buildFinishedAt = 0
async function buildAndInstall(serial, trigger) {
const t0 = Date.now()
log(`开始构建(触发: ${trigger})`)
// 1. uni-app 编译 App 资源
if (!run('npm', ['run', 'build:app'])) {
log(
`接口地址 = ${API_TARGET.base || 'https://qimen.wms.gztbyc.com(生产)'} 〔${API_TARGET.note}〕`
)
// 1. uni-app 编译 App 资源(注入开发地址,避免真机调试打到生产库)
if (!run('npm', ['run', 'build:app'], { env: BUILD_ENV })) {
log('✗ build:app 失败,跳过安装')
return false
}

View File

@ -1,5 +1,6 @@
<script>
import { guardCurrentPage } from './core/nav-guard'
import { flushClientErrorReport } from './core/error-report'
// rem 基准:以 1920×1280 设计稿为准,100px = 1rem,按宽高取小(contain)缩放
const DESIGN_WIDTH = 1920
const DESIGN_HEIGHT = 1280
@ -107,6 +108,8 @@ export default {
},
onHide: function () {
console.log('App Hide')
// 退到后台立即把待上报的错误日志发出去(后台可能被系统回收,晚发就没了)
flushClientErrorReport()
},
}
</script>

View File

@ -19,6 +19,26 @@ export function getLoginWechatCode(
})
}
/**
* 上报客户端错误日志(免登录、免权限、免鉴权,服务端写 wms_client_error_log)
* - 入参支持单条对象/数组/{logs:[...]} 三种形态,单次最多 50 条;这里统一用 { logs } 包裹
* - error_message 与 error_stack 至少一项有值;report_uuid 幂等去重(重复上报静默成功)
*/
export function uploadClientErrorLog(
logs: Record<string, unknown>[] | Record<string, unknown>,
options?: RequestOptions
) {
const list = Array.isArray(logs) ? logs : [logs]
return request<ApiBody>(
'index.uploadClientErrorLog',
{ logs: list },
{
skipAuth: true,
...options,
}
)
}
/**
* 工作台登录:获取工作台绑定码 / 绑定状态(免登录、免鉴权)
* - 不传 clientCode:分配新客户端编码并立即返回绑定码

View File

@ -0,0 +1,214 @@
<template>
<view v-if="visible" class="diag-mask" @click="handleClose">
<view class="diag-panel" @click.stop>
<view class="diag-head">
<text class="diag-title">扫码诊断</text>
<view class="diag-head-actions">
<text class="diag-action" @click="refresh">刷新</text>
<text class="diag-action" @click="submitReport">上报</text>
<text class="diag-action" @click="copyText">复制</text>
<text class="diag-action diag-action--danger" @click="clearLog">清空</text>
<text class="diag-action diag-action--close" @click="handleClose">×</text>
</view>
</view>
<scroll-view class="diag-body" scroll-y>
<text class="diag-text">{{ text }}</text>
</scroll-view>
<view class="diag-foot">
<text class="diag-foot-text">{{ hint }}</text>
</view>
</view>
</view>
</template>
<script>
import { diagText, diagClear } from '@/core/scan-diag'
import { reportScanDiagNow, getClientErrorQueueSize } from '@/core/error-report'
/**
* 扫码诊断面板(现场可读,无需 adb)
* 打开方式由宿主页面决定(打包页=3 秒内连点标题 5 次)。
* 数据来自 src/core/scan-diag.js,与 logcat(tag: WMSScan) 同源。
*/
export default {
name: 'ScanDiagPanel',
props: {
visible: {
type: Boolean,
default: false,
},
},
emits: ['close'],
data() {
return {
text: '',
hint: '复制后可直接发到群里;真机也可用 adb logcat -s WMSScan 查看',
}
},
watch: {
visible(value) {
if (value) {
this.refresh()
this.startTimer()
} else {
this.stopTimer()
}
},
},
beforeUnmount() {
this.stopTimer()
},
methods: {
startTimer() {
this.stopTimer()
this.timer = setInterval(() => {
this.refresh()
}, 1000)
},
stopTimer() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
},
refresh() {
try {
this.text = diagText()
this.hint = `待上报 ${getClientErrorQueueSize()} 条(点「上报」立即送服务端);真机也可用 adb logcat -s WMSScan`
} catch (e) {
this.text = `诊断信息生成失败:${e && e.message}`
}
},
/** 手动上报到服务端 wms_client_error_log(带完整扫码诊断快照) */
submitReport() {
let ok = false
try {
ok = reportScanDiagNow('诊断面板手动上报')
} catch (e) {
ok = false
}
uni.showToast({ title: ok ? '已上报(后台发送)' : '上报被限流,稍后再试', icon: 'none' })
this.refresh()
},
copyText() {
try {
uni.setClipboardData({
data: this.text,
success: () => {
uni.showToast({ title: '诊断信息已复制', icon: 'none' })
},
fail: () => {
uni.showToast({ title: '复制失败,请截图上报', icon: 'none' })
},
})
} catch (e) {
uni.showToast({ title: '复制失败,请截图上报', icon: 'none' })
}
},
clearLog() {
try {
diagClear()
} catch (e) {
// 忽略
}
this.refresh()
uni.showToast({ title: '日志已清空', icon: 'none' })
},
handleClose() {
this.$emit('close')
},
},
}
</script>
<style scoped>
/* 诊断面板固定用 px:不随页面 rem 缩放变化,保证任何缩放系数下都可读 */
.diag-mask {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.6);
z-index: 3000;
display: flex;
align-items: center;
justify-content: center;
}
.diag-panel {
width: 76vw;
max-width: 900px;
height: 74vh;
background-color: #1e1e1e;
border-radius: 6px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.diag-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
background-color: #2b2b2b;
border-bottom: 1px solid #3c3c3c;
}
.diag-title {
color: #ffffff;
font-size: 15px;
font-weight: bold;
}
.diag-head-actions {
display: flex;
align-items: center;
}
.diag-action {
color: #4ea1ff;
font-size: 13px;
padding: 4px 10px;
border: 1px solid #3c3c3c;
border-radius: 4px;
margin-left: 8px;
}
.diag-action--danger {
color: #ff7875;
}
.diag-action--close {
color: #dddddd;
font-size: 16px;
padding: 2px 10px;
}
.diag-body {
flex: 1;
padding: 10px 12px;
overflow: hidden;
}
.diag-text {
color: #d4d4d4;
font-size: 12px;
line-height: 18px;
font-family: Consolas, Menlo, 'Courier New', monospace;
white-space: pre-wrap;
word-break: break-all;
}
.diag-foot {
padding: 6px 12px;
background-color: #2b2b2b;
border-top: 1px solid #3c3c3c;
}
.diag-foot-text {
color: #909399;
font-size: 11px;
}
</style>

60
src/core/device-probe.js Normal file
View File

@ -0,0 +1,60 @@
/**
* App 端原生环境探测(仅 APP-PLUS 有效,其它平台返回空对象)
*
* 用途:把"按键能不能到 WebView"的两个决定性条件纳入心跳快照——
* 1. winFocus:Activity/Window 是否仍有焦点。失去焦点时 Android 不会把按键派发到 WebView,
* 表现出来就是"扫码完全没反应"(真机上曾出现过无聚焦元素导致设备不投递按键的情况)。
* 2. imeUp:输入法是否处于激活态。IME 位于 WebView 之前(dispatchKeyEventPreIme),
* 激活时按键会被输入法截获 —— 现场表现为"扫一次后不再接收"。
*
* 注意:Native.js 桥接对象在 service 层不支持点方法调用,实例方法必须用 plus.android.invoke;
* 探测失败一律静默返回,绝不影响业务。
*/
// 结果缓存:看门狗每 2s 调一次,桥接调用不宜过于频繁
const CACHE_MS = 10000
let cached = null
let cachedAt = 0
export function probeAppWindow() {
const now = Date.now()
if (cached && now - cachedAt < CACHE_MS) {
return cached
}
const result = {}
try {
if (
typeof plus === 'undefined' ||
!plus ||
!plus.android ||
typeof plus.android.runtimeMainActivity !== 'function'
) {
cached = result
cachedAt = now
return result
}
const main = plus.android.runtimeMainActivity()
if (!main) {
cached = result
cachedAt = now
return result
}
result.winFocus = !!plus.android.invoke(main, 'hasWindowFocus')
// Context.INPUT_METHOD_SERVICE = "input_method"(字符串直传,避免静态字段访问失败)
const imm = plus.android.invoke(main, 'getSystemService', 'input_method')
if (imm) {
result.imeUp = !!plus.android.invoke(imm, 'isActive')
}
} catch (e) {
// 探测失败静默
}
cached = result
cachedAt = now
return result
}
/** 清空缓存(页面切换/退后台后需要重新探测时调用) */
export function resetAppWindowProbe() {
cached = null
cachedAt = 0
}

533
src/core/error-report.js Normal file
View File

@ -0,0 +1,533 @@
/**
* 客户端错误 / 扫码诊断日志上报(index.uploadClientErrorLog,免登录免鉴权)
*
* 目标:现场"长时间使用后扫码没反应"这类问题无法复现、也没法现场抓 adb,
* 因此把运行时错误与扫码链路异常**自动**批量上报到服务端 wms_client_error_log,
* 由服务端按 device_id / error_type 聚合排查。
*
* 上报内容:
* 1. 运行时错误:Vue 渲染/生命周期异常、window error/unhandledrejection、uni 未处理 Promise;
* 2. 扫码链路异常(由 scan-diag 通过 setDiagSink 外送):
* scan-stall(主线程卡顿)/ scan-heal(自愈动作)/ scan-drop(扫码被丢弃,带收到的码);
* 3. 现场手动上报(诊断面板「上报」按钮):scan-manual,带完整精简快照。
*
* 设计约束(务必保持):
* - 任何异常都不得向上抛,绝不能因为上报失败影响业务;
* - 批量 ≤50 条/次(接口上限),队列持久化,重启后续报;report_uuid 幂等,重发不会产生重复行;
* - 多重限流:同类消息 60s 去重、每会话最多 40 次请求、失败保留队列下次再发;
* - 可在现场关闭:uni.setStorageSync('clientErrorLog:disabled', 1)。
*/
import { uploadClientErrorLog } from '@/api/index'
import { appEnv } from '@/config/env'
import { diagDigest, setDiagSink } from '@/core/scan-diag'
const STORAGE_QUEUE_KEY = 'clientErrorLog:queue'
const STORAGE_DEVICE_KEY = 'clientErrorLog:deviceId'
const STORAGE_DISABLED_KEY = 'clientErrorLog:disabled'
const MAX_BATCH = 50
const QUEUE_LIMIT = 200
const FLUSH_INTERVAL_MS = 15000
const FLUSH_THRESHOLD = 8
const RETRY_BASE_DELAY_MS = 5000
const MAX_REQUESTS_PER_SESSION = 40
const DEDUPE_WINDOW_MS = 60000
// 接口侧限制:error_message 5000、error_stack/extra 65535,这里留出余量
const MAX_MESSAGE_LEN = 4800
const MAX_STACK_LEN = 20000
const MAX_EXTRA_LEN = 60000
const DIAG_EXTRA_MAX_EVENTS = 30
let queue = []
let installed = false
let sending = false
let requestCount = 0
let consecutiveFailures = 0
let flushTimer = null
let deviceInfo = null
let lastResult = null
const lastReportAtByKey = {}
// ---------- 基础工具(全部 try/catch 包裹,永不抛错) ----------
function storageGet(key) {
try {
return uni.getStorageSync(key)
} catch (e) {
return ''
}
}
function storageSet(key, value) {
try {
uni.setStorageSync(key, value)
} catch (e) {
// 忽略:存储失败不影响上报流程
}
}
function truncate(text, max) {
const str = String(text == null ? '' : text)
return str.length > max ? str.slice(0, max) : str
}
function isDisabled() {
return !!storageGet(STORAGE_DISABLED_KEY)
}
function currentRoute() {
try {
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
const top = pages && pages.length ? pages[pages.length - 1] : null
return top && top.route ? String(top.route) : ''
} catch (e) {
return ''
}
}
function deviceId() {
let id = String(storageGet(STORAGE_DEVICE_KEY) || '')
if (!id) {
id = `ws-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
storageSet(STORAGE_DEVICE_KEY, id)
}
return id
}
/** 设备信息(首次调用时取一次并缓存) */
function resolveDeviceInfo() {
if (deviceInfo) {
return deviceInfo
}
let info = {}
try {
info = (typeof uni !== 'undefined' && uni.getSystemInfoSync && uni.getSystemInfoSync()) || {}
} catch (e) {
info = {}
}
const platform = String(info.platform || '').toLowerCase()
deviceInfo = {
client_type: appEnv.isApp ? 'android' : appEnv.isElectron ? 'electron' : platform || 'web',
device_id: deviceId(),
os_version: truncate(info.system || info.osVersion || '', 64),
device_model: truncate(
[info.brand, info.model].filter(Boolean).join(' ') || info.deviceModel || '',
128
),
}
return deviceInfo
}
function buildReportUuid() {
return `client-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
}
function normalizeExtra(extra) {
let text = ''
try {
text = typeof extra === 'string' ? extra : JSON.stringify(extra == null ? {} : extra)
} catch (e) {
text = String(extra)
}
return truncate(text, MAX_EXTRA_LEN)
}
// ---------- 队列 ----------
function persistQueue() {
storageSet(STORAGE_QUEUE_KEY, queue.slice(-QUEUE_LIMIT))
}
function loadQueue() {
const cached = storageGet(STORAGE_QUEUE_KEY)
if (Array.isArray(cached)) {
queue = cached.filter((item) => item && typeof item === 'object').slice(-QUEUE_LIMIT)
}
}
function enqueue(log) {
queue.push(log)
if (queue.length > QUEUE_LIMIT) {
queue.splice(0, queue.length - QUEUE_LIMIT)
}
persistQueue()
if (queue.length >= FLUSH_THRESHOLD) {
scheduleFlush(300)
}
}
function scheduleFlush(delay) {
if (flushTimer || isDisabled()) {
return
}
flushTimer = setTimeout(() => {
flushTimer = null
flushClientErrorReport()
}, delay)
}
/**
* 立即上报一批(公开给页面/面板调用)。
* 返回 Promise,但调用方可以不管;内部失败只保留队列,不抛错。
*/
export async function flushClientErrorReport() {
if (sending || isDisabled()) {
return
}
if (!queue.length) {
scheduleFlush(FLUSH_INTERVAL_MS)
return
}
if (requestCount >= MAX_REQUESTS_PER_SESSION) {
return
}
sending = true
const batch = queue.slice(0, MAX_BATCH)
try {
const body = await uploadClientErrorLog(batch, { timeout: 20000 })
const code = Number(body && body.code)
const ok = body && (body.flag === 'success' || code === 200 || body.success === true)
lastResult = {
at: Date.now(),
batch: batch.length,
flag: body && body.flag,
code,
message: (body && body.message) || '',
accepted: body && body.accepted,
duplicated: body && body.duplicated,
rejected: body && body.rejected,
}
if (ok) {
queue.splice(0, batch.length)
persistQueue()
requestCount += 1
consecutiveFailures = 0
} else if (code === 400) {
// 入参/数据问题:这批永远发不出去,丢弃以免阻塞后续日志
queue.splice(0, batch.length)
persistQueue()
requestCount += 1
} else {
consecutiveFailures += 1
}
} catch (e) {
// 网络异常:保留队列,退避后重试
consecutiveFailures += 1
lastResult = { at: Date.now(), batch: batch.length, error: (e && e.message) || 'network-error' }
} finally {
sending = false
if (queue.length) {
const delay = Math.min(
RETRY_BASE_DELAY_MS * Math.pow(2, Math.min(consecutiveFailures, 4)),
5 * 60 * 1000
)
scheduleFlush(consecutiveFailures > 0 ? delay : FLUSH_INTERVAL_MS)
} else if (!flushTimer) {
scheduleFlush(FLUSH_INTERVAL_MS)
}
}
}
// ---------- 上报入口 ----------
/**
* 上报一条错误/诊断日志。
* @param payload { type, message, stack, extra, force }
* @returns boolean 是否进入队列(被限流/关闭时返回 false)
*/
export function reportClientError(payload = {}) {
try {
if (isDisabled()) {
return false
}
const message = truncate(payload.message, MAX_MESSAGE_LEN)
const stack = truncate(payload.stack, MAX_STACK_LEN)
if (!message && !stack) {
return false
}
const type = String(payload.type || 'error')
// 同类消息 60s 去重:避免同一异常刷爆服务端(force 可绕过,如现场手动上报)
const dedupeKey = `${type}|${message}`
const now = Date.now()
if (
!payload.force &&
lastReportAtByKey[dedupeKey] &&
now - lastReportAtByKey[dedupeKey] < DEDUPE_WINDOW_MS
) {
return false
}
lastReportAtByKey[dedupeKey] = now
const info = resolveDeviceInfo()
enqueue({
client_type: info.client_type,
device_id: info.device_id,
os_version: info.os_version,
device_model: info.device_model,
app_version: appEnv.version,
error_type: type,
error_message: message,
error_stack: stack,
extra: normalizeExtra(
Object.assign({ route: currentRoute(), packType: appEnv.packType }, payload.extra || {})
),
report_uuid: buildReportUuid(),
client_time: now,
})
return true
} catch (e) {
return false
}
}
/** 现场手动上报:带完整扫码诊断快照(面板「上报」按钮用) */
export function reportScanDiagNow(reason = '手动上报') {
const ok = reportClientError({
type: 'scan-manual',
message: `扫码诊断手动上报:${reason}`,
extra: { diag: diagDigest(60) },
force: true,
})
flushClientErrorReport()
return ok
}
// ---------- 扫码诊断外送 ----------
function hookDiagSink() {
setDiagSink((kind, payload) => {
try {
if (kind === 'stall') {
// 消息文本保持稳定(不带变化量)以便 60s 去重,细节放 extra
reportClientError({
type: 'scan-stall',
message: '扫码期间主线程卡顿',
extra: { stall: payload, diag: diagDigest(DIAG_EXTRA_MAX_EVENTS) },
})
return
}
if (kind === 'heal') {
reportClientError({
type: 'scan-heal',
message: `扫码链路自愈:${payload.reason}`,
extra: { heal: payload.data || {}, diag: diagDigest(DIAG_EXTRA_MAX_EVENTS) },
})
return
}
if (kind === 'drop') {
const data = payload.data || {}
// 同样保持消息稳定:reason 相同则 60s 内只上报一条,累计次数在 extra.drop.count
reportClientError({
type: 'scan-drop',
message: `扫码被丢弃:${payload.reason}`,
extra: {
drop: { reason: payload.reason, count: payload.count, ...data },
diag: diagDigest(DIAG_EXTRA_MAX_EVENTS),
},
})
return
}
if (kind === 'anomaly') {
const name = String(payload.name || 'anomaly')
reportClientError({
type: `scan-${name}`,
message: `扫码异常:${name}`,
extra: { anomaly: payload.data || {}, diag: diagDigest(DIAG_EXTRA_MAX_EVENTS) },
})
return
}
if (kind === 'health') {
// 周期健康快照:服务端拿到连续轨迹,能看出"哪一刻开始收不到按键"
reportClientError({
type: 'scan-health',
message: '扫码健康快照',
extra: { health: payload },
})
}
} catch (e) {
// 忽略:上报失败不影响扫码
}
})
}
// ---------- 全局错误钩子 ----------
function describeUnknown(value) {
if (value instanceof Error) {
return { message: value.message || String(value), stack: value.stack || '' }
}
if (value && typeof value === 'object') {
try {
return { message: value.message ? String(value.message) : JSON.stringify(value), stack: value.stack || '' }
} catch (e) {
return { message: String(value), stack: '' }
}
}
return { message: String(value == null ? '' : value), stack: '' }
}
function hookGlobalErrors(vueApp) {
// 1) Vue 渲染 / 生命周期 / 事件处理异常
try {
if (vueApp && vueApp.config) {
const previous = vueApp.config.errorHandler
vueApp.config.errorHandler = (err, instance, info) => {
const desc = describeUnknown(err)
reportClientError({
type: 'vue-error',
message: `[${info || 'vue'}] ${desc.message}`,
stack: desc.stack,
extra: { hook: info || '' },
})
if (typeof previous === 'function') {
try {
previous(err, instance, info)
} catch (e) {
// 忽略
}
}
}
}
} catch (e) {
// 忽略
}
// 2) 全局 JS 错误与未处理 Promise(H5/Electron 及部分 App WebView 有 window)
try {
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
window.addEventListener('error', (event) => {
const desc = describeUnknown((event && (event.error || event.message)) || '')
reportClientError({
type: 'window-error',
message: desc.message,
stack: desc.stack,
extra: {
source: (event && event.filename) || '',
line: (event && event.lineno) || '',
column: (event && event.colno) || '',
},
})
})
window.addEventListener('unhandledrejection', (event) => {
const desc = describeUnknown(event && event.reason)
reportClientError({
type: 'unhandled-rejection',
message: desc.message,
stack: desc.stack,
})
})
}
} catch (e) {
// 忽略
}
// 3) uni 未处理 Promise(存在则挂载)
try {
if (typeof uni !== 'undefined' && typeof uni.onUnhandledRejection === 'function') {
uni.onUnhandledRejection((res) => {
const desc = describeUnknown(res && res.reason)
reportClientError({
type: 'uni-unhandled-rejection',
message: desc.message,
stack: desc.stack,
})
})
}
} catch (e) {
// 忽略
}
// 4) uni 全局错误(部分平台提供 onError,存在则挂载)
try {
if (typeof uni !== 'undefined' && typeof uni.onError === 'function') {
uni.onError((error) => {
const desc = describeUnknown(error)
reportClientError({
type: 'uni-error',
message: desc.message,
stack: desc.stack,
})
})
}
} catch (e) {
// 忽略
}
}
/**
* 安装上报(main.js 创建 app 后调用一次)
* @param vueApp createSSRApp 返回的 app 实例(用于挂 Vue errorHandler)
*/
export function installClientErrorReport(vueApp) {
if (installed) {
return
}
installed = true
try {
loadQueue()
hookDiagSink()
hookGlobalErrors(vueApp)
exposeDebugApi()
scheduleFlush(FLUSH_INTERVAL_MS)
// 上一次运行残留的日志(崩溃/杀进程前没发出去)优先发一批
if (queue.length) {
scheduleFlush(3000)
}
} catch (e) {
// 忽略:上报不可用不影响应用启动
}
}
/** 现场关闭/开启上报(调试用;关闭后队列保留不再发送) */
export function setClientErrorReportEnabled(enabled) {
if (enabled) {
try {
uni.removeStorageSync(STORAGE_DISABLED_KEY)
} catch (e) {
// 忽略
}
scheduleFlush(0)
return
}
storageSet(STORAGE_DISABLED_KEY, 1)
}
/** 当前队列长度(诊断面板展示用) */
export function getClientErrorQueueSize() {
return queue.length
}
/** 上报模块状态(联调/现场排查用) */
export function getClientErrorReportState() {
return {
queue: queue.length,
requestCount,
consecutiveFailures,
disabled: isDisabled(),
lastResult,
}
}
/**
* H5/Electron 暴露调试入口(App 逻辑层无 window,自动跳过):
* 控制台可用 window.__wmsErrorReport.state() 看队列与服务端应答
*/
function exposeDebugApi() {
try {
if (typeof window === 'undefined') {
return
}
window.__wmsErrorReport = {
report: reportClientError,
reportDiag: reportScanDiagNow,
flush: flushClientErrorReport,
state: getClientErrorReportState,
enable: () => setClientErrorReportEnabled(true),
disable: () => setClientErrorReportEnabled(false),
}
} catch (e) {
// 忽略
}
}

588
src/core/scan-diag.js Normal file
View File

@ -0,0 +1,588 @@
/**
* 扫码链路诊断(长时间运行可追踪)
*
* 背景:真机上「长时间使用后扫码没反应」这类问题无法现场复现,必须留下可事后追溯的证据链。
* 本模块提供三件事:
* 1. 事件环形缓冲 + 计数器(按键到达 / 各门控丢弃 / 自愈次数 / 成功识别),
* 节流持久化到 storage:应用被杀或重启后日志仍在(诊断面板或 storage 可读)。
* 2. 真机同步写 logcat(tag: WMSScan),release 包也能 `adb logcat -s WMSScan` 事后追踪。
* 3. 60 秒健康心跳:记录区间内按键数 / 丢弃增量 / 门控快照,
* 可精确定位「哪一分钟开始收不到按键」以及当时的门控状态。
*
* 约定:本模块只做记录,不做任何业务决策,任何异常都不得向上抛。
*/
import { BASE_URL } from '../../env.js'
const STORAGE_KEY = 'scanDiagLog:v1'
const LOGCAT_TAG = 'WMSScan'// 内存中保留的事件条数
const MAX_EVENTS = 300
// 持久化到 storage 的事件条数(控制体积,约 10KB)
const MAX_PERSIST_EVENTS = 160
const PERSIST_THROTTLE_MS = 2000
// 健康心跳间隔(心跳里带门控快照,是"何时开始不响应"的关键线索)
const HEALTH_INTERVAL_MS = 60 * 1000
// 同一丢弃原因的最小记录间隔(计数照常累加,避免刷屏)
const DROP_LOG_MIN_INTERVAL_MS = 30 * 1000
// 带内容(收到的条码/已缓冲的字符)的丢弃必须留痕,只用 1s 节流防刷屏
const CONTENT_LOG_MIN_INTERVAL_MS = 1000
// 单个字段值最长保留字符数(超长时截断,避免整条日志被一条条码刷满)
const MAX_VALUE_LEN = 220
// 超过该空闲时长后恢复的第一下按键单独记一条 key-resume
const KEY_RESUME_GAP_MS = 60 * 1000
// 大于该间隔视为"新的一次扫码",记录起始按键的原始 keyCode/type
const KEY_BURST_GAP_MS = 500
// 心跳定时器迟到判定:实际间隔 > 设定周期 * 该倍数 → 主线程被卡住
const STALL_FACTOR = 2.5
// 服务端健康快照间隔:服务端拿到连续轨迹,而不只是异常点
const REPORT_HEALTH_INTERVAL_MS = 10 * 60 * 1000
const state = {
scope: 'unknown',
startedAt: Date.now(),
events: [],
counters: { keys: 0, keysBySource: {}, flushes: 0, heals: 0, drops: {} },
gates: {},
// 当前业务上下文(任务号、期望条码…):面板顶部展示 + 随日志落盘
context: {},
prevCounters: null,
lastKeyAt: 0,
lastHealthAt: 0,
healthKeys: 0,
healthDrops: 0,
healthHeals: 0,
dropLoggedAt: {},
lastTickAt: 0,
maxTickGapMs: 0,
stallCount: 0,
lastHealthReportAt: 0,
healthReportKeys: 0,
loaded: false,
persistedAt: 0,
persistTimer: null,
logcatClass: null,
}
// ---------- 基础工具 ----------
/**
* 诊断事件外送上钩子:由 src/core/error-report.js 注册。
* 只在"异常类"事件上触发(卡顿/自愈/带内容的丢弃),让服务端能远程看到现场异常,
* 而不需要现场人员打开面板。这里用回调而非直接 import,避免两个模块循环依赖。
*/
let sink = null
/** 注册外送上钩子(fn(kind, payload));传 null 取消 */
export function setDiagSink(fn) {
sink = typeof fn === 'function' ? fn : null
}
function emitSink(kind, payload) {
if (!sink) {
return
}
try {
sink(kind, payload)
} catch (e) {
// 上报失败绝不影响业务
}
}
function hasUni() {
return typeof uni !== 'undefined' && !!uni && typeof uni.setStorageSync === 'function'
}
function pad2(n) {
return String(n).padStart(2, '0')
}
function fmtClock(ts) {
const d = new Date(ts)
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
}
/**
* 事件时间戳:MM-DD HH:MM:SS.mmm
* 排查"长时间运行"问题时只有时分秒不够用:跨天、以及同一秒内多个事件都区分不出来。
*/
function fmtStamp(ts) {
const d = new Date(ts)
return (
`${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ` +
`${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}.` +
String(d.getMilliseconds()).padStart(3, '0')
)
}
/** 完整日期时间:YYYY-MM-DD HH:MM:SS */
function fmtFull(ts) {
const d = new Date(ts)
return (
`${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ` +
`${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
)
}
/** 应用版本(vite define 注入,取不到就空) */
function appVersion() {
try {
return typeof __APP_VERSION__ !== 'undefined' ? String(__APP_VERSION__) : ''
} catch (e) {
return ''
}
}
/** 当前构建指向的接口主机:现场确认"这台机器连的是哪个后端" */
function apiHost() {
try {
return String(BASE_URL || '').replace(/^https?:\/\//, '').replace(/\/.*$/, '') || 'unknown'
} catch (e) {
return 'unknown'
}
}
function fmtDuration(ms) {
const totalSec = Math.max(0, Math.floor(ms / 1000))
if (totalSec < 60) {
return `${totalSec}s`
}
const totalMin = Math.floor(totalSec / 60)
if (totalMin < 60) {
return `${totalMin}m${pad2(totalSec % 60)}s`
}
return `${Math.floor(totalMin / 60)}h${pad2(totalMin % 60)}m`
}
/** 只保留可读的轻量字段,避免把大对象写进日志 */
function tidy(data) {
if (!data || typeof data !== 'object') {
return undefined
}
const out = {}
Object.keys(data).forEach((key) => {
const value = data[key]
if (value === undefined || value === null) {
return
}
const type = typeof value
if (type === 'number' || type === 'boolean') {
out[key] = value
} else if (type === 'string') {
// 条码内容要留下,但过长时截断
out[key] = value.length > MAX_VALUE_LEN ? `${value.slice(0, MAX_VALUE_LEN)}…` : value
}
})
return Object.keys(out).length ? out : undefined
}
function dataText(data) {
const tidyData = tidy(data)
if (!tidyData) {
return ''
}
return (
' ' +
Object.keys(tidyData)
.map((key) => `${key}=${tidyData[key]}`)
.join(' ')
)
}
function totalDrops() {
return Object.keys(state.counters.drops).reduce((sum, key) => sum + state.counters.drops[key], 0)
}
/** 真机同步写 logcat:release 包 console 不可见,只能靠 logcat 事后追踪 */
function logcat(line) {
try {
if (typeof plus === 'undefined' || !plus || !plus.android) {
return
}
if (!state.logcatClass) {
state.logcatClass = plus.android.importClass('android.util.Log')
}
state.logcatClass.i(LOGCAT_TAG, String(line))
} catch (e) {
// 忽略:日志失败绝不影响业务
}
}
// ---------- 持久化 ----------
function persistNow() {
if (!hasUni()) {
return
}
state.persistedAt = Date.now()
try {
uni.setStorageSync(STORAGE_KEY, {
v: 1,
savedAt: state.persistedAt,
scope: state.scope,
counters: state.counters,
gates: state.gates,
context: state.context,
events: state.events.slice(-MAX_PERSIST_EVENTS),
})
} catch (e) {
// 忽略:存储失败不影响业务
}
}
function schedulePersist() {
if (state.persistTimer) {
return
}
const wait = Math.max(0, PERSIST_THROTTLE_MS - (Date.now() - state.persistedAt))
state.persistTimer = setTimeout(() => {
state.persistTimer = null
persistNow()
}, wait)
}
function load() {
if (state.loaded) {
return
}
state.loaded = true
if (!hasUni()) {
return
}
try {
const raw = uni.getStorageSync(STORAGE_KEY)
if (raw && typeof raw === 'object' && Array.isArray(raw.events)) {
state.events = raw.events
.filter((item) => item && item.t && item.msg)
.slice(-MAX_PERSIST_EVENTS)
if (raw.context && typeof raw.context === 'object') {
state.context = raw.context
}
if (raw.counters && typeof raw.counters === 'object') {
// 上次运行的累计值仅作参考,不并入本次计数
state.prevCounters = raw.counters
}
}
} catch (e) {
// 忽略
}
}
// ---------- 写入事件 ----------
function push(kind, message, data) {
const entry = { t: Date.now(), kind, msg: `${message}${dataText(data)}` }
state.events.push(entry)
if (state.events.length > MAX_EVENTS) {
state.events.splice(0, state.events.length - MAX_EVENTS)
}
// 按键逐条记录会刷屏,只计数(key-resume / key-start 会单独 push)
if (kind !== 'key') {
logcat(`${fmtStamp(entry.t)} [${kind}] ${entry.msg}`)
schedulePersist()
}
return entry
}
// ---------- 对外 API ----------
/** 页面进入时声明作用域(同一 scope 重复调用不产生新标记) */
export function diagBegin(scope) {
load()
const next = String(scope || 'unknown')
if (state.scope === next) {
return
}
state.scope = next
const prev = state.prevCounters
const abnormal = detectPrevAbnormalExit()
push('note', `session-start scope=${next}${prev ? ` 上次运行=${JSON.stringify(prev)}` : ''}`)
// 上次是"确实在用"的会话,且最后一条生命周期不是 onHide/onUnload → 疑似被系统杀掉/崩溃。
// 长跑场景里"用着用着没反应"可能就是应用被回收后重进,这条能直接区分。
if (abnormal && prev && (Number(prev.keys) >= 50 || Number(prev.flushes) >= 1)) {
diagAnomaly('abnormal-exit', abnormal)
}
}
/**
* 上一次运行是否非正常结束(被杀/崩溃):
* 判据是"日志在非收尾状态下停止,且已经静默超过 1 分钟"。
* 不能只看最后一条生命周期:页面切换时旧页 onHide 可能晚于新页 onShow,
* 但那种情况会在毫秒级继续写日志,gapMs 很小,不会命中。
*/
function detectPrevAbnormalExit() {
const newest = state.events[state.events.length - 1]
if (!newest) {
return null
}
if (newest.kind === 'note' && /onHide|onUnload|deactivated/.test(newest.msg)) {
return null
}
const gapMs = Date.now() - newest.t
if (gapMs < 60000) {
return null
}
return { lastEvent: newest.msg, lastKind: newest.kind, gapMs }
}
/** 更新门控快照(会随健康心跳一起落盘,是定位"为何没反应"的核心依据) */
export function diagSetGates(gates) {
const tidyGates = tidy(gates)
if (!tidyGates) {
return
}
state.gates = Object.assign({}, state.gates, tidyGates)
}
/**
* 记录一次按键到达(在任何门控判断之前调用)。
* 用于区分「按键根本没到 JS」和「到了 JS 但被门控丢掉」。
*/
export function diagKey(source, extra) {
const now = Date.now()
const gap = state.lastKeyAt ? now - state.lastKeyAt : 0
state.lastKeyAt = now
state.counters.keys += 1
const key = String(source || 'unknown')
state.counters.keysBySource[key] = (state.counters.keysBySource[key] || 0) + 1
if (gap > KEY_RESUME_GAP_MS) {
// 长时间无按键后的第一下:定位"卡住→恢复"的时间点
push('key', `key-resume source=${key} 空闲=${fmtDuration(gap)}`)
} else if (gap > KEY_BURST_GAP_MS) {
// 一次扫码的起始按键:记下原始 keyCode/type——用于识别输入法注入/合成事件/异常按键流
push('key-start', `source=${key}`, extra)
}
}
/** 记录一次被丢弃的按键(reason 区分门控,便于统计各原因占比) */
export function diagDrop(reason, data) {
const key = String(reason || 'unknown')
state.counters.drops[key] = (state.counters.drops[key] || 0) + 1
const count = state.counters.drops[key]
const now = Date.now()
const last = state.dropLoggedAt[key] || 0
// 带内容(收到的条码 / 已缓冲的字符)的丢弃必须留痕,否则现场无法回答
// “扫的是哪个码、为什么没生效”;纯计数型的丢弃按间隔节流即可
const hasContent = !!(
data &&
((data.code && String(data.code).length) || (data.buffer && String(data.buffer).length))
)
const minInterval = hasContent ? CONTENT_LOG_MIN_INTERVAL_MS : DROP_LOG_MIN_INTERVAL_MS
if (count === 1 || now - last >= minInterval || count % 100 === 0) {
state.dropLoggedAt[key] = now
push('drop', `reason=${key} count=${count}`, data)
if (hasContent) {
emitSink('drop', { reason: key, count, data })
}
}
}
/** 记录一次成功识别出的扫码结果 */
export function diagFlush(info) {
state.counters.flushes += 1
push('flush', `#${state.counters.flushes}`, info)
}
/** 记录一次自愈动作(事件类型锁重置 / 监听重挂等) */
export function diagHeal(reason, data) {
state.counters.heals += 1
push('heal', `reason=${reason} count=${state.counters.heals}`, data)
emitSink('heal', { reason, data })
}
/** 记录任意备注(生命周期、提交动作、状态切换等) */
export function diagNote(name, data) {
load()
push('note', String(name || ''), data)
}
/**
* 记录一次"值得服务端知道"的异常(除卡顿/自愈/丢弃之外的自定义异常)。
* 例:abnormal-exit(上次非正常退出)、partial-code-no-terminator(扫码未收到结束符)。
* 有外送上钩子时自动上报(error_type = scan-<name>)。
*/
export function diagAnomaly(name, data, options) {
load()
const key = String(name || 'anomaly')
push('anomaly', key, data)
// report:false 时只写本地日志不外送(用于需要本地限流的场景)
if (!options || options.report !== false) {
emitSink('anomaly', { name: key, data })
}
}
/**
* 设置/更新当前业务上下文(当前任务、期望条码等)。
* 变更时留一条记录:现场看日志时能直接对照“该收到哪个码 / 现在在做什么任务”。
*/
export function diagSetContext(patch) {
load()
const tidyPatch = tidy(patch)
if (!tidyPatch) {
return
}
const before = JSON.stringify(state.context)
state.context = Object.assign({}, state.context, tidyPatch)
if (JSON.stringify(state.context) !== before) {
push('note', 'context', state.context)
}
}
/**
* 健康心跳
* - 每次调用(包括被节流跳过的)都会检查"定时器迟到":页面看门狗/自愈心跳是固定周期调的,
* 实际间隔远超周期 → JS 主线程被长任务/GC/其它进程卡住,这是"全局卡住"的直接证据;
* - 每 intervalMs 输出一条 health,含区间按键/丢弃增量与门控快照。
* @param options { force?: boolean, intervalMs?: number }
*/
export function diagHeartbeat(options) {
const opts = options && typeof options === 'object' ? options : { force: !!options }
const now = Date.now()
const intervalMs = Number(opts.intervalMs) > 0 ? Number(opts.intervalMs) : HEALTH_INTERVAL_MS
const tickGap = state.lastTickAt ? now - state.lastTickAt : 0
state.lastTickAt = now
if (tickGap && tickGap > intervalMs * STALL_FACTOR) {
state.stallCount += 1
state.maxTickGapMs = Math.max(state.maxTickGapMs, tickGap)
push('stall', `主线程疑似卡顿 ${tickGap}ms(定时器周期 ${intervalMs}ms)`, {
gapMs: tickGap,
intervalMs,
keys: state.counters.keys,
gates: state.gates,
})
emitSink('stall', { gapMs: tickGap, intervalMs, keys: state.counters.keys, gates: state.gates })
}
if (!opts.force && now - state.lastHealthAt < HEALTH_INTERVAL_MS) {
return
}
const keys = state.counters.keys - state.healthKeys
const drops = totalDrops() - state.healthDrops
const heals = state.counters.heals - state.healthHeals
const idleAgo = state.lastKeyAt ? `${fmtDuration(now - state.lastKeyAt)}前` : 'never'
state.lastHealthAt = now
state.healthKeys = state.counters.keys
state.healthDrops = totalDrops()
state.healthHeals = state.counters.heals
push(
'health',
`keys=${keys} drops=${drops} heals=${heals} flush累计=${state.counters.flushes} ` +
`最近按键=${idleAgo} tick=${tickGap || intervalMs}ms 最大tick=${state.maxTickGapMs}ms 卡顿=${state.stallCount}`,
state.gates
)
// 服务端健康快照:本会话确实收到过按键后,每 10 分钟外送一次,
// 这样"某一刻开始收不到按键"即使无人上报也能在服务端看出来(轨迹而不是只有异常点)
if (state.counters.keys > 0 && now - state.lastHealthReportAt >= REPORT_HEALTH_INTERVAL_MS) {
const keysSinceReport = state.counters.keys - state.healthReportKeys
state.lastHealthReportAt = now
state.healthReportKeys = state.counters.keys
emitSink('health', {
keysSinceReport,
keysTotal: state.counters.keys,
flushes: state.counters.flushes,
drops: state.counters.drops,
heals: state.counters.heals,
lastKeyAgoMs: state.lastKeyAt ? now - state.lastKeyAt : null,
stallCount: state.stallCount,
maxTickGapMs: state.maxTickGapMs,
gates: state.gates,
context: state.context,
})
}
}
/** 立即落盘(页面 onHide/onUnload 时调用,避免节流窗口内丢日志) */
export function diagPersistNow() {
if (state.persistTimer) {
clearTimeout(state.persistTimer)
state.persistTimer = null
}
persistNow()
}
/** 结构化快照(面板/上报可用) */
export function diagSnapshot() {
return {
scope: state.scope,
uptimeMs: Date.now() - state.startedAt,
counters: {
keys: state.counters.keys,
keysBySource: Object.assign({}, state.counters.keysBySource),
flushes: state.counters.flushes,
heals: state.counters.heals,
drops: Object.assign({}, state.counters.drops),
},
gates: Object.assign({}, state.gates),
context: Object.assign({}, state.context),
lastKeyAgoMs: state.lastKeyAt ? Date.now() - state.lastKeyAt : null,
maxTickGapMs: state.maxTickGapMs,
stallCount: state.stallCount,
events: state.events.slice(),
}
}
/** 精简快照(上报服务端用:带上下文与最近事件,体积可控) */
export function diagDigest(maxEvents = 25) {
const snapshot = diagSnapshot()
return {
scope: snapshot.scope,
uptimeMs: snapshot.uptimeMs,
counters: snapshot.counters,
gates: snapshot.gates,
context: snapshot.context,
lastKeyAgoMs: snapshot.lastKeyAgoMs,
stallCount: snapshot.stallCount,
maxTickGapMs: snapshot.maxTickGapMs,
events: snapshot.events.slice(-maxEvents),
}
}
/** 纯文本摘要(现场截图/复制即可上报,无需 adb) */
export function diagText() {
const snapshot = diagSnapshot()
const lines = []
const version = appVersion()
lines.push(
`【扫码诊断】${fmtFull(Date.now())} scope=${snapshot.scope}` +
`${version ? ` 版本=${version}` : ''} 接口=${apiHost()} 已运行=${fmtDuration(snapshot.uptimeMs)}`
)
const ctxKeys = Object.keys(snapshot.context)
if (ctxKeys.length) {
// 业务上下文(当前任务 / 期望条码)——“应该接收到的条码”就看这里
lines.push(`上下文 ${ctxKeys.map((key) => `${key}=${snapshot.context[key]}`).join(' ')}`)
}
lines.push(
`按键到达=${snapshot.counters.keys}` +
(snapshot.lastKeyAgoMs === null
? '(本次运行还没收到任何按键)'
: `(最近一次 ${fmtDuration(snapshot.lastKeyAgoMs)} 前)`)
)
lines.push(`按键来源=${JSON.stringify(snapshot.counters.keysBySource)}`)
lines.push(`成功识别=${snapshot.counters.flushes} 自愈=${snapshot.counters.heals} 主线程卡顿=${snapshot.stallCount}(最大${snapshot.maxTickGapMs}ms)`)
const dropKeys = Object.keys(snapshot.counters.drops)
lines.push(
`丢弃统计=${
dropKeys.length
? dropKeys.map((key) => `${key}:${snapshot.counters.drops[key]}`).join(' ')
: '无'
}`
)
lines.push(`门控快照=${JSON.stringify(snapshot.gates)}`)
lines.push('---- 最近事件(新→旧,时间=月-日 时:分:秒.毫秒) ----')
const events = snapshot.events
for (let i = events.length - 1; i >= 0 && i >= events.length - 80; i--) {
lines.push(`${fmtStamp(events[i].t)} [${events[i].kind}] ${events[i].msg}`)
}
return lines.join('\n')
}
/** 清空日志(诊断面板手动清空,或问题确认消除后清空) */
export function diagClear() {
state.events = []
state.counters = { keys: 0, keysBySource: {}, flushes: 0, heals: 0, drops: {} }
state.healthKeys = 0
state.healthDrops = 0
state.healthHeals = 0
state.lastHealthAt = 0
state.dropLoggedAt = {}
push('note', 'log-cleared')
diagPersistNow()
}

View File

@ -5,8 +5,37 @@
* - 页面通过 registerScanReceiver 注册接收;同一时刻仅一个接收者
* - Enter 或超时(380ms/420ms)flush;长度 < minLength 的码直接丢弃
* - setScanPaused(true) 暂停捕获(如账号/密码输入框聚焦时)
*
* 长时间运行可追踪(配合 src/core/scan-diag.js):
* - 任何按键到达 JS 先计数(diagKey),再按门控丢弃原因分类计数(diagDrop),
* 由此可区分「按键根本没到」与「到了但被门控丢掉」。
* - 空闲后自动重置事件类型锁、长时间无按键强制重挂监听(自愈)。
*/
import {
diagKey,
diagDrop,
diagFlush,
diagHeal,
diagHeartbeat,
diagSetGates,
diagNote,
diagAnomaly,
diagPersistNow,
} from './scan-diag'
import { probeAppWindow } from './device-probe'
// 空闲超过该时长后重新锁定 plus.key 实际生效的事件类型。
// 根因:本机实测只投递 keyup,若某次运行时锁被设成 'keydown'(其它来源的合成/注入事件),
// 之后所有真按键都会被事件类型过滤静默丢掉 → 表现为「扫着扫着彻底没反应」。
const IDLE_LOCK_RESET_MS = 1200
// 长时间(默认 10 分钟)没有任何按键到达时,强制重挂 plus/DOM 监听(防桥接回调静默失效)
const LISTENER_REARM_IDLE_MS = 10 * 60 * 1000
// 自愈心跳间隔
const SELF_HEAL_INTERVAL_MS = 5000
// "无结束符"异常上报的最小间隔(本地日志仍逐次记录)
const NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS = 10 * 60 * 1000
// Android KeyEvent 符号键映射(KEYCODE_* → 字符)。
// 这些 keyCode 与 ASCII 字母/数字区间重叠,必须优先于 ASCII 分支判断,
// 否则 KEYCODE_EQUALS=70 会被 ASCII 的 [65..90] 分支误读为 'F'。
@ -35,9 +64,18 @@ let buffer = ''
let startedAt = 0
let lastAt = 0
let timer = null
// 本次扫码已处理的按键数 + 最近一个按键(诊断用:区分"只收到 1 个字符"与"按键中途停止投递")
let burstKeyCount = 0
let lastPlusKeyCode = 0
let lastDomKey = ''
let domListenerAttached = false
let plusAttached = false
let lastAnyKeyAt = 0 // 最近一次按键到达(含被门控丢弃的),用于空闲判定
let rearmedForIdle = false // 本次空闲是否已重挂过监听(收到按键后复位)
let selfHealTimer = null
let selfHealStartedAt = 0
let lastNoTerminatorAnomalyAt = 0
let plusKeyStyle = null // 'android' | 'ascii'
let plusShiftDown = false
let plusShiftPrev = false
@ -69,13 +107,25 @@ function resetBuffer() {
buffer = ''
startedAt = 0
lastAt = 0
burstKeyCount = 0
}
/** 当前已缓冲字符的尾部:丢弃时用它回答"扫的码已经收到多少了" */
function bufferTail(max = 40) {
if (!buffer) {
return ''
}
return buffer.length > max ? buffer.slice(-max) : buffer
}
function flush(trigger, source) {
clearTimer()
const code = buffer.trim()
const keyCount = burstKeyCount
const lastKey = source === 'plus' ? lastPlusKeyCode : lastDomKey
const durationMs = startedAt ? Math.max(0, (lastAt || Date.now()) - startedAt) : 0
buffer = ''
burstKeyCount = 0
startedAt = 0
lastAt = 0
@ -85,11 +135,45 @@ function flush(trigger, source) {
// 少于最小长度的码直接丢弃(可能是键盘误按/短码)
if (code.length < minLength) {
diagDrop('too-short', {
scope: receiverScope(),
code,
length: code.length,
keys: keyCount,
lastKey,
minLength,
trigger,
source,
})
debug('code-dropped', { reason: 'too-short', code, length: code.length, minLength, trigger, source })
return
}
// 记录完整条码与按键数:事后要能回答"这条到底扫到了什么"、"按键是否中途停了"
diagFlush({ scope: receiverScope(), trigger, source, code, length: code.length, durationMs, keys: keyCount, lastKey })
debug('flush-buffer', { code, length: code.length, durationMs, trigger, source })
// 扫码枪通常以 Enter 结尾:没有结束符就靠空闲 flush,优先怀疑按键流在结束符前中断
if (trigger !== 'enter' && keyCount >= 4 && durationMs > 0 && durationMs <= 1500) {
const now = Date.now()
const shouldReport = now - lastNoTerminatorAnomalyAt >= NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS
if (shouldReport) {
lastNoTerminatorAnomalyAt = now
}
diagAnomaly(
'partial-code-no-terminator',
{
scope: receiverScope(),
source,
code,
keys: keyCount,
length: code.length,
durationMs,
lastKey,
reported: shouldReport ? 1 : 0,
},
{ report: shouldReport }
)
}
if (receiver && typeof receiver.onScanCode === 'function') {
try {
@ -111,19 +195,57 @@ function appendChar(ch) {
timer = setTimeout(() => flush('timer', 'dom'), 380)
}
/** 当前接收者所属页面(诊断日志用):页面注册时传 scope,未传则为 scan */
function receiverScope() {
return (receiver && receiver.scope) || 'scan'
}
/**
* 记录「按键到达 JS」这一事实(必须在任何门控判断之前调用)。
* extra 用于扫码起始按键采样(keyCode/type/key),便于识别输入法注入与异常按键流。
* 返回距上一次按键的空闲时长,供事件类型锁自愈使用。
*/
function markKeyArrival(source, extra) {
const now = Date.now()
const gap = lastAnyKeyAt ? now - lastAnyKeyAt : 0
lastAnyKeyAt = now
rearmedForIdle = false
if (extra) {
if (extra.keyCode) {
lastPlusKeyCode = extra.keyCode
}
if (extra.key) {
lastDomKey = String(extra.key)
}
}
diagKey(source, extra)
return gap
}
// ---------- DOM(H5/Electron) ----------
function onDomKeydown(event) {
markKeyArrival('dom', { key: (event && event.key) || '' })
if (!receiver || paused) {
diagDrop(receiver ? 'paused' : 'no-receiver', {
scope: receiverScope(),
source: 'dom',
buffer: bufferTail(),
})
return
}
const key = event?.key || ''
const isPrintable = key.length === 1
const isEnter = key === 'Enter'
if (!isPrintable && !isEnter) {
diagDrop('unmapped-dom-key', { scope: receiverScope(), key, buffer: bufferTail() })
return
}
debug('key-captured', { key, paused })
if (isPrintable) {
if (!buffer) {
burstKeyCount = 0
}
burstKeyCount += 1
appendChar(key)
return
}
@ -239,10 +361,22 @@ function isPlusEnterKey(keyCode, text) {
}
function handlePlusKeyEvent(event, type) {
const keyCode = Number((event && event.keyCode) || 0)
const gap = markKeyArrival('plus', { keyCode, type })
// 空闲后重新锁定实际生效的事件类型:自愈「锁错就永久静默」
if (plusKeyEventType && gap > IDLE_LOCK_RESET_MS) {
const locked = plusKeyEventType
plusKeyEventType = null
diagHeal('event-type-lock-idle-reset', { scope: receiverScope(), locked, gapMs: gap })
}
if (!receiver || paused) {
diagDrop(receiver ? 'paused' : 'no-receiver', {
scope: receiverScope(),
source: 'plus',
buffer: bufferTail(),
})
return
}
const keyCode = Number((event && event.keyCode) || 0)
// 跟踪 Shift 修饰键(Android KEYCODE_SHIFT_LEFT=59 / SHIFT_RIGHT=60)
if (keyCode === 59 || keyCode === 60) {
@ -263,6 +397,7 @@ function handlePlusKeyEvent(event, type) {
plusShiftPrev = plusShiftDown
const isEnter = isPlusEnterKey(keyCode, text)
if (!text && !isEnter) {
diagDrop('unmapped-keycode', { scope: receiverScope(), keyCode, type, buffer: bufferTail() })
return
}
@ -271,6 +406,14 @@ function handlePlusKeyEvent(event, type) {
plusKeyEventType = type
}
if (plusKeyEventType !== type) {
// 这一类丢弃最致命(整串码会丢),必须带上已收到的内容
diagDrop('event-type-locked', {
scope: receiverScope(),
keyCode,
type,
locked: plusKeyEventType,
dropped: bufferTail(),
})
return
}
@ -278,7 +421,9 @@ function handlePlusKeyEvent(event, type) {
const now = Date.now()
if (!buffer) {
startedAt = now
burstKeyCount = 0
}
burstKeyCount += 1
lastAt = now
buffer += text
clearTimer()
@ -304,6 +449,8 @@ function ensurePlusListener() {
plus.key.addEventListener('keydown', onPlusKeyDown)
plus.key.addEventListener('keyup', onPlusKeyUp)
plusAttached = true
diagNote('plus-listener-attached')
diagSetGates({ scope: receiverScope(), plusAttached: true })
debug('plus-listener-attached')
// #endif
}
@ -322,6 +469,7 @@ function removePlusListener() {
plusKeyEventType = null
plusShiftDown = false
plusShiftPrev = false
diagSetGates({ plusAttached: false })
}
// ---------- 公共 API ----------
@ -340,6 +488,8 @@ export function registerScanReceiver(next) {
if (receiver) {
ensureDomListener()
ensurePlusListener()
diagSetGates({ scope: receiverScope(), receiver: true, minLength })
diagNote('receiver-registered', { scope: receiverScope() })
debug('receiver-registered')
}
}
@ -349,16 +499,25 @@ export function unregisterScanReceiver(target) {
if (target && receiver !== target) {
return
}
const scope = receiverScope()
receiver = null
resetBuffer()
removeDomListener()
removePlusListener()
setScanPaused(false)
diagSetGates({ scope, receiver: false, paused: false, buffer: 0 })
diagNote('receiver-unregistered', { scope })
}
/** 暂停/恢复捕获(账号/密码等输入框聚焦时暂停,并清空已缓冲的按键) */
export function setScanPaused(value) {
paused = !!value
const next = !!value
if (paused !== next) {
// 暂停标志卡住是最常见的"扫码没反应"原因,必须留痕
diagNote('setScanPaused', { scope: receiverScope(), value: next })
}
paused = next
diagSetGates({ paused })
if (paused) {
resetBuffer()
} else {
@ -371,6 +530,7 @@ export function setScanMinLength(value) {
const num = Number(value)
if (num >= 1) {
minLength = Math.floor(num)
diagSetGates({ minLength })
}
}
@ -383,3 +543,71 @@ export function resetScanBuffer() {
export function getScanMinLength() {
return minLength
}
/** 当前链路状态快照(诊断面板/日志用) */
export function getScanDiagState() {
return {
paused,
receiver: !!receiver,
plusAttached,
eventTypeLock: plusKeyEventType,
minLength,
bufferLength: buffer.length,
lastKeyAgoMs: lastAnyKeyAt ? Date.now() - lastAnyKeyAt : null,
}
}
/**
* 启动扫码链路自愈心跳(页面 onShow/activated 调用,onHide/deactivated 停止)
* - 每 5s 刷新门控快照 + 输出健康心跳(内部按 60s 节流);
* - 空闲超过 10 分钟仍无任何按键时,强制重挂 plus/DOM 监听(防桥接回调静默失效)。
* 注意:仅在空闲时重挂,不会打断正在进行的扫码。
*/
export function startScanSelfHeal(intervalMs) {
if (selfHealTimer) {
return
}
const period = Number(intervalMs) > 0 ? Number(intervalMs) : SELF_HEAL_INTERVAL_MS
selfHealStartedAt = Date.now()
selfHealTimer = setInterval(() => {
// 从未收到过按键时以心跳启动时刻为基准,否则"一直收不到"的情况永远不会触发重挂
const now = Date.now()
const idleForRearmMs = now - (lastAnyKeyAt || selfHealStartedAt)
diagSetGates(
Object.assign(
{
scope: receiverScope(),
paused,
receiver: !!receiver,
plusAttached,
eventTypeLock: plusKeyEventType || 'none',
idleSec: lastAnyKeyAt ? Math.round((now - lastAnyKeyAt) / 1000) : 'never',
},
// 真机:Window 焦点 / 输入法状态(决定按键能否到达 WebView),H5 返回空对象
probeAppWindow()
)
)
if (receiver && idleForRearmMs > LISTENER_REARM_IDLE_MS && !rearmedForIdle) {
rearmedForIdle = true
removePlusListener()
removeDomListener()
ensurePlusListener()
ensureDomListener()
diagHeal('listener-rearmed-idle', {
scope: receiverScope(),
idleMs: idleForRearmMs,
hint: '长时间无按键,强制重挂监听',
})
}
diagHeartbeat({ intervalMs: period })
}, period)
}
/** 停止自愈心跳(页面 onHide/deactivated 调用) */
export function stopScanSelfHeal() {
if (selfHealTimer) {
clearInterval(selfHealTimer)
selfHealTimer = null
}
diagPersistNow()
}

View File

@ -4,6 +4,7 @@ import {
import App from "./App.vue";
import appEnv from './config/env'
import { installNavGuard } from './core/nav-guard'
import { installClientErrorReport } from './core/error-report'
import { getVoice } from './core/voice'
// #ifdef APP-PLUS
@ -75,6 +76,8 @@ export function createApp() {
app.provide('appEnv', appEnv)
// 路由前置守卫:必须在任何页面跳转发生前安装
installNavGuard()
// 客户端错误/扫码诊断日志上报(index.uploadClientErrorLog,免登录免鉴权)
installClientErrorReport(app)
return {
app,
};

View File

@ -107,7 +107,15 @@
></image>
<text v-else class="scan-placeholder">{{ workbenchBindCode || '绑定码生成中...' }}</text>
</view>
<!-- 绑定码文本:二维码扫不出/需人工输入时直接读这里(与二维码内容为同一个码) -->
<view class="wb-code-box">
<text class="wb-code-label">绑定码</text>
<text class="wb-code-value">{{ workbenchBindCode || '—' }}</text>
</view>
<text class="scan-tip-bottom">{{ workbenchStatus }}</text>
<view class="wb-refresh-link" @click="handleWorkbenchRefresh">
<text>刷新绑定码</text>
</view>
</block>
</view>
</view>
@ -169,7 +177,10 @@ import {
unregisterScanReceiver,
setScanPaused,
resetScanBuffer,
startScanSelfHeal,
stopScanSelfHeal,
} from '@/core/scan'
import { diagBegin, diagDrop, diagNote, diagPersistNow } from '@/core/scan-diag'
const qrBaseUrl = 'https://ye4s.wms.gztbyc.com/grcode/build?text='
const qrFallbackBaseUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=280x280&data='
@ -282,20 +293,27 @@ export default {
this.clearHiddenRefocusTimer()
this.clearAutoEnterPackTimer()
this.scanBadgeSubmitting = false
stopScanSelfHeal()
diagPersistNow()
},
onReady() {
this.pageActive = true
diagBegin('login')
diagNote('lifecycle', { hook: 'onReady' })
this.hasStoredWorkbench = !!uni.getStorageSync('workbench_token')
this.setupScanCaptureMode()
this.registerScanCapture()
startScanSelfHeal()
this.suppressSoftKeyboardBurst()
this.scheduleScanInputFocus(260)
this.checkAppUpdate()
},
onShow() {
this.pageActive = true
diagNote('lifecycle', { hook: 'onShow' })
this.setupScanCaptureMode()
this.registerScanCapture()
startScanSelfHeal()
this.suppressSoftKeyboardBurst()
this.scheduleScanInputFocus(320)
this.resumeWorkbenchFlow()
@ -303,6 +321,7 @@ export default {
},
onHide() {
this.pageActive = false
diagNote('lifecycle', { hook: 'onHide' })
this.stopScanLongPolling()
this.stopWorkbenchLongPolling()
this.abortScanRequest()
@ -318,6 +337,7 @@ export default {
this.clearAutoEnterPackTimer()
this.scanHiddenFocused = false
this.scanInputFocus = false
stopScanSelfHeal()
},
beforeUnmount() {
this.pageActive = false
@ -338,6 +358,8 @@ export default {
this.scanBadgeSubmitting = false
this.scanHiddenFocused = false
this.scanInputFocus = false
stopScanSelfHeal()
diagPersistNow()
},
methods: {
isPageActive() {
@ -534,11 +556,14 @@ export default {
// 注册/注销通用全局扫码接收(捕获与最小长度过滤由 src/core/scan.js 统一处理)
registerScanCapture() {
registerScanReceiver({
scope: 'login',
onScanCode: (code, meta) => {
if (!this.isPageActive()) {
return
}
if (this.loginMode !== 'account' && this.loginMode !== 'scan') {
// 非扫码模式下收到的码被丢弃:记下内容与当前模式
diagDrop('mode-not-scan', { code, mode: String(this.loginMode || '') })
return
}
this.handleScanBadgeLogin(code, meta)
@ -1654,12 +1679,14 @@ export default {
this.logScanDebug('scan-login-abort', { reason: 'empty-code' })
return
}
diagNote('badge-login', { code })
const now = Date.now()
if (
this.scanBadgeSubmitting ||
(this.scanBadgeLastSubmittedCode === code && now - this.scanBadgeLastSubmittedAt < 1200)
) {
diagDrop('badge-duplicate', { code })
this.logScanDebug('scan-login-skipped', {
reason: this.scanBadgeSubmitting ? 'submitting' : 'duplicate-in-1200ms',
code,
@ -2295,6 +2322,42 @@ export default {
margin-bottom: 0;
}
/* 绑定码文本(工作台面板):与二维码内容一致,供二维码扫不出时人工读取/输入 */
.wb-code-box {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 0.205rem;
}
.wb-code-label {
font-size: 0.563rem;
color: #666;
margin-right: 0.205rem;
}
.wb-code-value {
font-size: 0.717rem;
font-weight: bold;
color: #2f7dff;
letter-spacing: 0.051rem;
font-family: Consolas, Menlo, monospace;
max-width: 5.6rem;
word-break: break-all;
text-align: center;
user-select: text;
}
.wb-refresh-link {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
padding: 0.205rem 0 0;
font-size: 0.563rem;
color: #2f7dff;
}
.scan-hidden-input {
position: absolute;
width: 0.02rem;

View File

@ -6,7 +6,7 @@
<view class="mode-title">
<text v-if="workbenchInfo && workbenchInfo.name" class="mode-title-name">{{ workbenchInfo.name }}</text>
<text v-if="workbenchInfo && workbenchInfo.name" class="mode-title-divider"></text>
<text class="mode-title-label">打包模式</text>
<text class="mode-title-label" @click="handleDiagTitleTap">打包模式</text>
</view>
</view>
<view class="topbar-actions">
@ -314,6 +314,9 @@
</view>
</view>
</view>
<!-- 扫码诊断面板(隐藏入口:3 秒内连点标题 5 次) -->
<scan-diag-panel :visible="diagPanelVisible" @close="diagPanelVisible = false" />
</view>
</template>
@ -328,12 +331,32 @@ import {
packOrder,
finishPack,
} from '@/api/index'
import ScanDiagPanel from '@/components/scan-diag-panel.vue'
import {
diagAnomaly,
diagBegin,
diagDrop,
diagFlush,
diagHeal,
diagHeartbeat,
diagKey,
diagNote,
diagPersistNow,
diagSetContext,
diagSetGates,
} from '@/core/scan-diag'
import { probeAppWindow } from '@/core/device-probe'
// 扫码枪识别参数(广播扫描:扫码枪为键盘 HID 设备,按键事件全局广播)
// 无回车结束符时:停止输入超过该毫秒数视为一次完整扫码,自动提交
const SCAN_IDLE_TIMEOUT = 300
// 自动提交所需的最短内容长度
const SCAN_MIN_LENGTH = 2
// 真机 plus 链路的最小码长:运单/商品码都是 8~13 位、工牌 64 位,
// 1~3 字符必然是误触/输入法/枪配置异常,不得当运单提交
const SCAN_CODE_MIN_LENGTH = 4
// "无结束符"异常上报的最小间隔(避免未配置后缀的枪刷爆服务端;本地日志仍逐次记录)
const NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS = 10 * 60 * 1000
// 手动输入识别:相邻按键间隔超过该毫秒数视为手动输入,不自动提交
const SCAN_BURST_MAX_GAP = 100
// Android KeyEvent 符号键映射(KEYCODE_* → 字符)。
@ -359,6 +382,10 @@ const ANDROID_PUNCT_MAP = {
const MEMBER_STORAGE_KEY = 'workbenchMember'
// 扫描记录本地缓存 key(最多 50 条,出入栈:最新在前、超限丢最旧)
const SCAN_RECORDS_STORAGE_KEY = 'packScanRecords'
// 空闲超过该时长后重新锁定 plus.key 实际生效的事件类型(自愈「锁错就永久静默」)
const SCAN_IDLE_LOCK_RESET_MS = 1200
// 长时间(默认 10 分钟)无任何按键到达时强制重挂监听(防桥接回调静默失效)
const SCAN_LISTENER_REARM_IDLE_MS = 10 * 60 * 1000
// 无新打包任务自动退出:超过该时长(毫秒)自动登出所有成员并结束最后打包任务
const IDLE_AUTO_LOGOUT_MS = 30 * 60 * 1000
// 语音播报:HTTP 语音接口(参考 WMS_PDA voice.js,不依赖平板系统中文语音包)
@ -367,6 +394,7 @@ const VOICE_API_PATH = 'http://tbdata.gztbyc.com'
export default {
name: 'PackagingPage',
components: { ScanDiagPanel },
data() {
return {
workbenchInfo: null,
@ -399,6 +427,11 @@ export default {
plusKeyTimer: null,
plusKeyStartedAt: 0,
plusKeyLastAt: 0,
// 本次扫码已处理的按键数(诊断用:区分"只收到 1 个字符"与"整个码都收到了")
plusKeyBurstCount: 0,
// 最近一个原始 keyCode(诊断用)+ 无结束符异常上次上报时间
plusKeyLastCode: 0,
lastNoTerminatorAnomalyAt: 0,
// 字母大小写策略:'auto' 跟踪 Shift 键 / 'upper' 全大写 / 'lower' 全小写
// 注意:plus.key 只给 keyCode、无 Shift 状态;仅当扫码枪会额外上报
// Android Shift 键(KEYCODE_SHIFT_LEFT=59 / SHIFT_RIGHT=60)时 'auto' 才能还原大小写。
@ -425,6 +458,13 @@ export default {
scanInputIdleTimer: null,
lastSubmittedScan: { code: '', at: 0 },
lastScannedCode: '',
// ---- 长时间运行可追踪/自愈 ----
lastScanKeyArrivedAt: 0, // 最近一次按键到达(任何门控之前)
scanRearmedForIdle: false, // 本次空闲是否已重挂过监听(收到按键后复位)
scanWatchdogStartedAt: 0, // 看门狗启动时刻(从未收到按键时的空闲基线)
diagPanelVisible: false,
diagTitleTapAt: 0,
diagTitleTapCount: 0,
// ---- 绑定操作员(工作台成员)----
operatorDialogVisible: false,
badgeHandling: false,
@ -590,6 +630,8 @@ export default {
// #ifdef APP-PLUS
plus.android.importClass('android.util.Log').i('WMSPage', 'onLoad')
// #endif
diagBegin('packaging')
diagNote('lifecycle', { hook: 'onLoad' })
// 简单守卫:无 token 时回到登录页
if (!uni.getStorageSync('token')) {
uni.reLaunch({
@ -613,6 +655,7 @@ export default {
// #ifdef APP-PLUS
plus.android.importClass('android.util.Log').i('WMSPage', 'onShow')
// #endif
diagNote('lifecycle', { hook: 'onShow' })
try {
this.pageActive = true
this.lockLandscape()
@ -640,6 +683,9 @@ export default {
this.removeGlobalKeyboardListener()
this.clearScanTimers()
this.clearIdleAutoLogoutTimer()
diagNote('lifecycle', { hook: 'onHide' })
diagSetGates({ pageActive: false })
diagPersistNow()
},
methods: {
// 强制锁定横屏 + 全屏重排:
@ -690,6 +736,7 @@ export default {
}
// 连续重复扫码限制:与上一次扫描内容一致时不执行任何操作
if (this.lastScannedCode === kw) {
diagDrop('duplicate-consecutive', { code: kw })
console.log('[packaging][scan] handlePackSearch skip: duplicate consecutive code =', kw)
this.keyword = ''
this.scheduleScanInputFocus(150)
@ -705,6 +752,7 @@ export default {
}
// 无在线成员:非工牌码(非用户码)拦截,不走查询用户,提示先登录
if (!this.workbenchMembers.length) {
diagDrop('no-member-intercept', { code: kw })
console.log('[packaging][scan] handlePackSearch -> 无成员且非工牌码,拦截')
this.keyword = ''
this.lastScannedCode = ''
@ -737,10 +785,12 @@ export default {
}
const token = this.getWorkbenchToken()
if (!token) {
diagDrop('no-workbench-token', { code })
uni.showToast({ title: '工作台登录已失效', icon: 'none' })
return
}
if (this.orderQuerying) {
diagDrop('query-busy', { code })
return
}
this.orderQuerying = true
@ -754,6 +804,7 @@ export default {
.catch(() => {
// 查询失败允许重扫同一码
this.lastScannedCode = ''
diagNote('query-failed', { code })
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
})
.finally(() => {
@ -986,6 +1037,15 @@ export default {
// 商品明细
this.detailList = this.mapOrderItems(items)
// 诊断上下文:“应该接收到的条码”= 本单商品条码;“当前任务”= 波次/运单
diagSetContext({
'期望任务': this.isGroupOrder
? `团单 ${this.currentWaveNo || ''}`
: `散单 ${this.currentWaybillCode || ''}`,
'期望条码': this.expectedBarcodeText(10),
'商品明细数': this.detailList.length,
})
// 免验商品(need_recheck=N)直接标记为已核实(标绿),无需扫码/长按
this.detailList.forEach((item) => {
if (item.needRecheck === 'N') {
@ -1031,12 +1091,14 @@ export default {
)
if (target) {
if (this.isItemScanned(target)) {
diagDrop('barcode-already-verified', { code: barcode })
this.keyword = ''
this.speak('数据一致')
uni.showToast({ title: '数据一致', icon: 'none', silentVoice: true })
return
}
// 按商品种类:扫 1 次即标记为已核实,无需扫满数量
diagNote('barcode-matched', { code: barcode, name: target.name || '' })
target.scannedQty = Number(target.qty) || 0
this.addScanRecord(barcode)
this.keyword = ''
@ -1045,10 +1107,20 @@ export default {
// 全部核实后自动开始打包
this.maybeAutoSubmitGroupPack()
} else {
// 收到码但业务不匹配:把"收到的码"与"期望的码"同时记下来
diagDrop('barcode-not-matched', { code: barcode, 期望条码: this.expectedBarcodeText(10) })
this.speak('无记录')
uni.showToast({ title: '条码与待核实商品不匹配', icon: 'none', silentVoice: true })
}
},
/** 期望条码文本(诊断日志用):本单商品条码,最多 limit 个 */
expectedBarcodeText(limit = 8) {
return this.detailList
.map((item) => item.barcode)
.filter((code) => !!code)
.slice(0, limit)
.join(',')
},
isItemScanned(item) {
const qty = Number(item?.qty) || 0
const scanned = Number(item?.scannedQty) || 0
@ -1316,6 +1388,8 @@ export default {
// 波次范围与打包时长闸门倒计时复位
this.currentWaveScope = null
this.stopPackCountdown()
// 诊断上下文同步复位(避免日志里残留上一单的期望条码)
diagSetContext({ '期望任务': '', '期望条码': '', '商品明细数': 0 })
},
speak(text) {
const str = this.normalizeSpeakText(text)
@ -1827,7 +1901,9 @@ export default {
* 回车且有内容时立即提交;无回车结束符则静默防抖自动提交。
*/
handleGlobalKeydown(event) {
this.markScanKeyArrived('dom', { key: (event && event.key) || '' })
if (!this.isPageActive()) {
diagDrop('page-inactive', { source: 'dom' })
return
}
const key = event.key || ''
@ -1891,7 +1967,10 @@ export default {
return
}
if (this.isLikelyScannerCode(code, durationMs, true)) {
diagFlush({ trigger: 'enter', source: 'dom', length: code.length, durationMs })
this.submitScanCode(code, 'dom')
} else {
diagDrop('dom-not-scanner-code', { length: code.length, durationMs, trigger: 'enter' })
}
},
touchScanInput() {
@ -1957,15 +2036,37 @@ export default {
},
// 看门狗:即使 onShow 异常未触发也能自愈恢复扫码。
// App/H5 页面隐藏或后台时收不到按键,所以 pageActive=true 不会误处理。
// 长时间运行自愈:
// 1) 空闲超过 10 分钟无任何按键 → 强制重挂 plus/DOM 监听(防桥接回调静默失效);
// 2) 每次心跳刷新门控快照 + 触发 60s 健康心跳,事后可定位「哪一分钟开始收不到按键」。
startScanWatchdog() {
if (this.scanWatchdogTimer) {
return
}
this.scanWatchdogStartedAt = Date.now()
this.scanWatchdogTimer = setInterval(() => {
this.pageActive = true
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
this.ensureScanInputFocus()
this.maybeRearmScanListenersWhenIdle()
diagSetGates(
Object.assign(
{
scope: 'packaging',
pageActive: this.pageActive !== false,
plusListener: !!(this.plusKeyListener || this.plusKeyUpListener),
domListener: !!this.globalKeyListener,
eventTypeLock: this._plusKeyEventType || 'none',
idleSec: this.lastScanKeyArrivedAt
? Math.round((Date.now() - this.lastScanKeyArrivedAt) / 1000)
: 'never',
},
// 真机:Window 焦点 / 输入法状态(决定按键能否到达 WebView),H5 返回空对象
probeAppWindow()
)
)
diagHeartbeat({ intervalMs: 2000 })
}, 2000)
},
stopScanWatchdog() {
@ -1974,6 +2075,52 @@ export default {
this.scanWatchdogTimer = null
}
},
/** 记录「按键到达 JS」(任何门控之前调用),返回距上次按键的空闲时长 */
markScanKeyArrived(source, extra) {
const now = Date.now()
const gap = this.lastScanKeyArrivedAt ? now - this.lastScanKeyArrivedAt : 0
this.lastScanKeyArrivedAt = now
this.scanRearmedForIdle = false
diagKey(source, extra)
return gap
},
/**
* 空闲(默认 10 分钟无任何按键)时强制重挂监听:
* 只在空闲时执行,不会打断正在进行的扫码;
* 用于兜住「监听器还在、但桥接回调不再投递按键」这类长时间运行才出现的静默失效。
*/
maybeRearmScanListenersWhenIdle() {
if (this.scanRearmedForIdle) {
return
}
// 从未收到过按键时以看门狗启动时刻为基准,否则"一直收不到"永远不会触发重挂
const baseline = this.lastScanKeyArrivedAt || this.scanWatchdogStartedAt || Date.now()
const idleMs = Date.now() - baseline
if (idleMs < SCAN_LISTENER_REARM_IDLE_MS) {
return
}
this.scanRearmedForIdle = true
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
diagHeal('listener-rearmed-idle', { scope: 'packaging', idleMs, hint: '长时间无按键,强制重挂监听' })
console.log('[packaging][scan] 已重挂扫码监听(空闲)', idleMs)
},
/** 诊断面板隐藏入口:3 秒内连点标题 5 次(操作员不会误触) */
handleDiagTitleTap() {
const now = Date.now()
if (now - this.diagTitleTapAt > 3000) {
this.diagTitleTapCount = 0
}
this.diagTitleTapAt = now
this.diagTitleTapCount += 1
if (this.diagTitleTapCount >= 5) {
this.diagTitleTapCount = 0
this.diagPanelVisible = true
diagNote('diag-panel-opened')
}
},
isRealDevice() {
// #ifdef APP-PLUS
return true
@ -2040,7 +2187,10 @@ export default {
return
}
if (this.isLikelyScannerCode(code, durationMs, false)) {
diagFlush({ trigger: 'timer', source: 'dom', length: code.length, durationMs })
this.submitScanCode(code, 'dom')
} else {
diagDrop('dom-not-scanner-code', { length: code.length, durationMs })
}
},
attachGlobalKeyboardListener() {
@ -2170,10 +2320,20 @@ export default {
},
// 统一处理 plus.key 按键(keydown / keyup)
handlePlusKeyEvent(event, type) {
// 先记录「按键到达 JS」这一事实(任何门控之前),用于区分「按键根本没到」与「到了被门控丢掉」
const keyCode = Number((event && event.keyCode) || 0)
this.plusKeyLastCode = keyCode
const gap = this.markScanKeyArrived('plus', { keyCode, type })
// 空闲后重新锁定实际生效的事件类型:自愈「锁错就永久静默」
if (this._plusKeyEventType && gap > SCAN_IDLE_LOCK_RESET_MS) {
const locked = this._plusKeyEventType
this._plusKeyEventType = null
diagHeal('event-type-lock-idle-reset', { locked, gapMs: gap })
}
if (!this.isPageActive()) {
diagDrop('page-inactive', { source: 'plus' })
return
}
const keyCode = Number((event && event.keyCode) || 0)
// 跟踪 Shift 修饰键(Android KEYCODE_SHIFT_LEFT=59 / SHIFT_RIGHT=60)
if (keyCode === 59 || keyCode === 60) {
@ -2194,6 +2354,7 @@ export default {
this._plusShiftPrev = this._plusShiftDown
const isEnter = this.isPlusEnterKey(keyCode, text)
if (!text && !isEnter) {
diagDrop('unmapped-keycode', { keyCode, type })
return
}
@ -2202,6 +2363,13 @@ export default {
this._plusKeyEventType = type
}
if (this._plusKeyEventType !== type) {
// 这一类丢弃最致命(整串码会丢),必须带上已收到的内容
diagDrop('event-type-locked', {
keyCode,
type,
locked: this._plusKeyEventType,
dropped: (this.plusKeyBuffer || '').slice(-40),
})
return
}
@ -2209,7 +2377,10 @@ export default {
const now = Date.now()
if (!this.plusKeyBuffer) {
this.plusKeyStartedAt = now
// 新的一次扫码:按键数重新计数
this.plusKeyBurstCount = 0
}
this.plusKeyBurstCount += 1
this.plusKeyLastAt = now
this.plusKeyBuffer += text
this.clearPlusKeyTimer()
@ -2242,19 +2413,60 @@ export default {
},
flushPlusKeyBuffer(trigger = 'timer') {
if (!this.isPageActive()) {
diagDrop('page-inactive-flush', { source: 'plus', trigger })
return
}
const code = (this.plusKeyBuffer || '').trim()
const keyCount = this.plusKeyBurstCount
const durationMs = this.plusKeyStartedAt
? Math.max(0, (this.plusKeyLastAt || Date.now()) - this.plusKeyStartedAt)
: 0
this.plusKeyBuffer = ''
this.plusKeyBurstCount = 0
this.plusKeyStartedAt = 0
this.plusKeyLastAt = 0
this.clearPlusKeyTimer()
if (!code) {
return
}
console.log('[packaging][scan] plus-buffer trigger =', trigger, 'code =', code)
// 过短输入(误触/输入法/枪异常)不当运单:记录收到的内容与按键数,便于事后区分
// "本来就只有 1 个字符"与"扫了完整码但按键中途停止投递"
if (code.length < SCAN_CODE_MIN_LENGTH) {
diagDrop('too-short', { source: 'plus', code, length: code.length, keys: keyCount, trigger })
return
}
diagFlush({ trigger, source: 'plus', code, length: code.length, durationMs, keys: keyCount })
console.log('[packaging][scan] plus-buffer trigger =', trigger, 'code =', code, 'keys =', keyCount)
// 扫码枪通常以 Enter 结尾(真机日志 trigger=enter):没有结束符就靠空闲 flush,
// 优先怀疑按键流在结束符前中断(也可能枪未配置后缀,服务端按 10 分钟一条区分)
if (trigger !== 'enter' && keyCount >= 4 && durationMs > 0 && durationMs <= 1500) {
this.reportNoTerminatorScan(code, keyCount, durationMs)
}
this.submitScanCode(code, 'plus')
},
/**
* 扫码没收到结束符就被 flush:记一条 anomaly(本地逐次记录,服务端限流上报)。
* 服务端据此区分"枪无后缀"(常态化)与"按键中途停止投递"(异常)。
*/
reportNoTerminatorScan(code, keys, durationMs) {
const now = Date.now()
const shouldReport = now - (this.lastNoTerminatorAnomalyAt || 0) >= NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS
if (shouldReport) {
this.lastNoTerminatorAnomalyAt = now
}
diagAnomaly(
'partial-code-no-terminator',
{
code,
keys,
length: code.length,
durationMs,
lastKeyCode: this.plusKeyLastCode || 0,
reported: shouldReport ? 1 : 0,
},
{ report: shouldReport }
)
},
handleHiddenScanFocus() {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return
@ -2490,6 +2702,7 @@ export default {
},
submitScanCode(code, source) {
if (!this.isPageActive()) {
diagDrop('page-inactive-submit', { source })
return
}
const trimmed = this.dedupeRepeatedScan((code || '').trim())
@ -2502,9 +2715,11 @@ export default {
this.lastSubmittedScan.code === trimmed &&
now - this.lastSubmittedScan.at < 600
) {
diagDrop('dedupe-same-code', { source, length: trimmed.length })
return
}
this.lastSubmittedScan = { code: trimmed, at: now }
diagNote('submit-scan', { source, code: trimmed })
console.log('[packaging][scan] submitScanCode source =', source, 'code =', trimmed)
// 操作员弹窗打开时:弹窗已无输入框,关闭弹窗后扫码内容走主流程
if (this.operatorDialogVisible) {

View File

@ -7,7 +7,7 @@
<view class="rp-left">
<view class="rp-card">
<view class="rp-card-title-row">
<text class="rp-card-title">拆包工作台</text>
<text class="rp-card-title" @click="handleDiagTitleTap">拆包工作台</text>
<view class="rp-card-title-actions">
<button class="rp-btn rp-btn--mini rp-btn--plain" @click="openCameraSettings">摄像头设置</button>
</view>
@ -408,6 +408,9 @@
@confirm="handleHiddenScanConfirm"
@blur="handleHiddenScanBlur"
/>
<!-- 扫码诊断面板(隐藏入口:3 秒内连点标题 5 次) -->
<scan-diag-panel :visible="diagPanelVisible" @close="diagPanelVisible = false" />
</view>
</template>
@ -438,7 +441,9 @@ import {
cameraServerDetail,
getLiveStreamUrl,
} from '@/api/camera'
import { registerScanReceiver, unregisterScanReceiver, setScanPaused, setScanMinLength } from '@/core/scan'
import { registerScanReceiver, unregisterScanReceiver, setScanPaused, setScanMinLength, startScanSelfHeal, stopScanSelfHeal } from '@/core/scan'
import ScanDiagPanel from '@/components/scan-diag-panel.vue'
import { diagBegin, diagDrop, diagNote, diagPersistNow, diagSetContext } from '@/core/scan-diag'
// ==================== 扫码指令定义(与散单 Web 端 scan-commands.ts 一致) ====================
// 制式 Code 128,内容为简单单词,识别时 trim + 忽略大小写,与商品条码(纯数字)零冲突
@ -485,6 +490,7 @@ export default {
name: 'ReturnsPage',
components: {
TopNav,
ScanDiagPanel,
},
props: {
// 在布局壳内渲染时为 true,隐藏内嵌顶栏;独立访问时不传,显示顶栏
@ -572,6 +578,10 @@ export default {
// 扫码捕获状态
pageActive: false,
modalBusy: false,
// 诊断面板(隐藏入口:3 秒内连点标题 5 次)
diagPanelVisible: false,
diagTitleTapAt: 0,
diagTitleTapCount: 0,
scanHiddenFocused: false,
scanInputFocus: false,
scanHiddenValue: '',
@ -722,8 +732,11 @@ export default {
},
onShow() {
this.pageActive = true
diagBegin('returns')
diagNote('lifecycle', { hook: 'onShow' })
this.registerScanCapture()
this.resumePreviewIfNeeded()
startScanSelfHeal()
// APP:保持隐藏 input 聚焦(WebView 不聚焦不派发按键);H5 全局 DOM 监听无需焦点
// #ifdef APP-PLUS
this.requestScanFocus()
@ -731,31 +744,41 @@ export default {
},
onHide() {
this.pageActive = false
diagNote('lifecycle', { hook: 'onHide' })
this.unregisterScanCapture()
this.clearScanTimers()
this.stopPreviewStream()
stopScanSelfHeal()
},
onUnload() {
this.pageActive = false
diagNote('lifecycle', { hook: 'onUnload' })
this.unregisterScanCapture()
this.clearScanTimers()
this.stopPreviewStream()
stopScanSelfHeal()
diagPersistNow()
},
// keep-alive 内嵌模式(外壳菜单切换):页面级 onShow/onHide 不会触发,
// 扫码捕获必须挂在 keep-alive 的 activated/deactivated 上(与订单复核页一致)
activated() {
this.pageActive = true
diagBegin('returns')
diagNote('lifecycle', { hook: 'activated' })
this.registerScanCapture()
this.resumePreviewIfNeeded()
startScanSelfHeal()
// #ifdef APP-PLUS
this.requestScanFocus()
// #endif
},
deactivated() {
this.pageActive = false
diagNote('lifecycle', { hook: 'deactivated' })
this.unregisterScanCapture()
this.clearScanTimers()
this.stopPreviewStream()
stopScanSelfHeal()
},
methods: {
// ==================== 通用 ====================
@ -849,11 +872,30 @@ export default {
return this.pageActive
},
/** 诊断面板隐藏入口:3 秒内连点标题 5 次(操作员不会误触) */
handleDiagTitleTap() {
const now = Date.now()
if (now - this.diagTitleTapAt > 3000) {
this.diagTitleTapCount = 0
}
this.diagTitleTapAt = now
this.diagTitleTapCount += 1
if (this.diagTitleTapCount >= 5) {
this.diagTitleTapCount = 0
this.diagPanelVisible = true
diagNote('diag-panel-opened')
}
},
registerScanCapture() {
setScanMinLength(SCAN_MIN_LENGTH)
registerScanReceiver({
scope: 'returns',
onScanCode: (code, meta) => {
if (!this.isPageActive()) return
if (!this.isPageActive()) {
diagDrop('page-inactive-receiver', { source: 'receiver' })
return
}
this.handleScanCode(code, meta)
},
onScanDebug: (...args) => {
@ -992,9 +1034,21 @@ export default {
/** 扫码路由(全局捕获的完整码) */
handleScanCode(code, meta) {
const barcode = String(code || '').trim()
if (!barcode || this.modalBusy) return
console.log('[scan-returns] route', barcode, meta)
if (!barcode) {
return
}
if (this.modalBusy) {
// 弹窗期间收到的码被丢弃:记下内容,避免现场"扫了没反应"无法解释
diagDrop('modal-busy', { code: barcode, source: String((meta && meta.source) || '') })
return
}
const cmd = resolveScanCommand(barcode)
diagNote('scan-code', {
code: barcode,
cmd: cmd || 'code',
hasOrder: !!(this.createResult && this.createResult.id),
})
console.log('[scan-returns] route', barcode, meta)
this.routeScan(cmd, barcode)
},
@ -1085,6 +1139,12 @@ export default {
this.detailPage = 1
this.lastScannedBarcode = ''
this.orderDetailItems = []
// 诊断上下文:当前拆包单(现场对照"扫的码属于哪一单")
diagSetContext({
'当前运单': (this.createResult.record && this.createResult.record.waybill_code) || code,
'拆包单ID': data.id,
'拆包状态': (this.createResult.record && this.createResult.record.status) || '',
})
uni.showToast({ title: `拆包单创建成功,ID ${data.id}`, icon: 'none' })
this.pushOsdText()
this.loadDetailList()
@ -2072,6 +2132,8 @@ export default {
this.defaultProductStatus = 'normal'
this.orderDetailItems = []
this.lastScannedBarcode = ''
// 诊断上下文同步复位
diagSetContext({ '当前运单': '', '拆包单ID': 0, '拆包状态': 'idle' })
// 删除/取消/提交/清除后直接推「无任务」待命文字
this.pushOsdText(OSD_IDLE_TEXT)
// APP:隐藏输入框保持焦点(H5 全局监听无需焦点)