feat: 打包模式工牌扫码上线/下线、多成员管理与30分钟自动登出等

打包模式(pages/packaging):
- 工牌(base64 JSON)扫码识别,经 index.queryUserByToken 查询用户:同用户已在线则下线,否则绑定为在线成员
- 多成员模型 workbenchMembers:弹窗仅展示成员列表+逐个下线;上报打包携带全部在线成员(users)
- 成员列表以服务端 getWorkbenchInfo.members 为准,绑定/下线后静默重拉
- 无在线成员时非工牌码拦截提示需要先登录,不走查询用户
- 带打包台 token 请求 401/403 统一清除工作台状态回登录(请求守卫)
- 30 分钟无新打包任务:结束打包任务+下线全部成员(不退出工作台模式,留在当前页)
- 移除手动退出工作台入口;扫描记录持久化 localStorage(50 条出入栈)
- 操作员列表弹窗重新排版(头像/姓名/下线按钮)

其他:
- 登录页扫码/更新流程、导航守卫与路由封装、Electron 主进程/预加载、发布脚本与配置模板(deploy.example.json)等调整
This commit is contained in:
liufumingren 2026-09-19 01:05:54 +08:00
parent 01599d1716
commit 0adaaa5bd6
31 changed files with 2014 additions and 392 deletions

View File

@ -1,4 +1,5 @@
# 环境变量模板:复制本文件为 .env.local 并填写真实值(.env.local 不提交 git)
# 详见 config/README.md
# 仅开发环境生效:生产构建(electron/Android 打包)固定使用 https://qimen.wms.gztbyc.com,见 env.js
VITE_API_BASE_URL=http://your-server-ip:6060
VITE_IMG_URL=https://your-img-domain.com

2
.gitignore vendored
View File

@ -14,6 +14,7 @@ dist
# build artifacts (exe under release/windows, apk under release/android)
release
build/.icon-ico
# Android offline packaging
# keystore files and local config (contains secrets) are NOT tracked.
@ -21,6 +22,7 @@ release
# See config/README.md for all config conventions.
android-offline/keystore/
config/android.json
config/deploy.json
# Android SDK project: sources are tracked (ensure consistent build base),
# only local build outputs are excluded.

View File

@ -8,11 +8,13 @@
# .\pack.ps1 -VersionName "1.0.2" # override version (written back to package.json; versionCode auto-derived)
# .\pack.ps1 -VersionCode 10002 # manually set versionCode (rarely needed)
# .\pack.ps1 -NoInject # skip prepare.cjs injection (already injected)
# .\pack.ps1 -NoUpload # package only, skip publish upload (scp + latest.json)
# .\pack.ps1 -JavaHome '...' -AndroidSdk '...'
param(
[switch]$Clean,
[switch]$Timestamp,
[switch]$NoInject,
[switch]$NoUpload,
[string]$VersionName = "",
[string]$VersionCode = "",
[string]$JavaHome = "",
@ -221,4 +223,80 @@ Write-Host " size : ${apkSize} MB"
Write-Host " version : $verName ($verCode)"
Write-Host "===================================================" -ForegroundColor Green
# ============ publish upload (scp + latest.json, same flow as sandan project) ============
$deployCfgPath = Join-Path $projRoot 'config\deploy.json'
if ($NoUpload) {
Write-Host ""
Write-Host "[hint] -NoUpload specified, skip publish upload" -ForegroundColor DarkGray
} elseif (-not (Test-Path $deployCfgPath)) {
Write-Host ""
Write-Host "[hint] config/deploy.json not found, skip publish upload (copy config/deploy.example.json and fill real values)" -ForegroundColor DarkGray
} else {
$dcfg = Get-Content $deployCfgPath -Raw -Encoding UTF8 | ConvertFrom-Json
$dcfg = $dcfg.android
if (-not $dcfg) {
Write-Host "[error] config/deploy.json missing android section" -ForegroundColor Red
exit 1
}
$dHost = [string]$dcfg.host
$dUser = [string]$dcfg.user
$dKey = [string]$dcfg.keyPath
$dRemDir = ([string]$dcfg.remoteDir).TrimEnd('/')
$dUrlPre = [string]$dcfg.downloadUrlPrefix
$dPort = 22
if ($dcfg.port) { $dPort = [int]$dcfg.port }
$dLatest = 'latest.json'
if ($dcfg.latestJsonName) { $dLatest = [string]$dcfg.latestJsonName }
if ($dUrlPre -and -not $dUrlPre.EndsWith('/')) { $dUrlPre = $dUrlPre + '/' }
$missing = @()
if (-not $dHost) { $missing += 'host' }
if (-not $dUser) { $missing += 'user' }
if (-not $dRemDir) { $missing += 'remoteDir' }
if (-not $dUrlPre) { $missing += 'downloadUrlPrefix' }
if ($missing.Count -gt 0) {
Write-Host "[error] config/deploy.json missing fields: $($missing -join ', ')" -ForegroundColor Red
exit 1
}
if ($dKey -and -not (Test-Path $dKey)) {
Write-Host "[error] SSH key not found: $dKey" -ForegroundColor Red
exit 1
}
# generate latest.json (same directory as the APK)
$sha256 = (Get-FileHash -Path $apkDest -Algorithm SHA256).Hash
$dlUrl = "$dUrlPre$apkName"
$publishedAt = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
$latest = [ordered]@{
version = $verName
file = $apkName
url = $dlUrl
sha256 = $sha256
publishedAtUtc = $publishedAt
}
$latestPath = Join-Path $distDir $dLatest
[System.IO.File]::WriteAllText($latestPath, ($latest | ConvertTo-Json), (New-Object System.Text.UTF8Encoding($false)))
Write-Host ""
Write-Host "[publish] upload to ${dUser}@${dHost}:${dRemDir}/ ..." -ForegroundColor Yellow
$scpArgs = @('-i', $dKey, '-P', "$dPort", '-o', 'StrictHostKeyChecking=accept-new')
& scp @scpArgs $apkDest "${dUser}@${dHost}:${dRemDir}/"
if ($LASTEXITCODE -ne 0) {
Write-Host "[error] APK upload failed (scp exit code $LASTEXITCODE)" -ForegroundColor Red
exit 1
}
& scp @scpArgs $latestPath "${dUser}@${dHost}:${dRemDir}/"
if ($LASTEXITCODE -ne 0) {
Write-Host "[error] $dLatest upload failed (scp exit code $LASTEXITCODE)" -ForegroundColor Red
exit 1
}
Write-Host ""
Write-Host "================== publish done ==================" -ForegroundColor Green
Write-Host " download : $dlUrl"
Write-Host " sha256 : $sha256"
Write-Host " updated : ${dRemDir}/${dLatest}"
Write-Host "=================================================" -ForegroundColor Green
}
exit 0

View File

@ -8,16 +8,20 @@
|---|---|---|
| `android.json` | Android 离线打包本地配置(包名、签名密码、AppKey 等) | ❌ 不提交(敏感) |
| `android.example.json` | 上述配置的模板,首次使用复制为 `android.json` | ✅ 提交 |
| `deploy.json` | 发布配置(服务器 IP/账号/SSH 密钥路径/上传目录,分 android/windows 两段) | ❌ 不提交 |
| `deploy.example.json` | 发布配置模板,首次使用复制为 `deploy.json` | ✅ 提交 |
`android.json` 字段说明:appId(uni-app appid)、appKey(dev.dcloud.net.cn 申请)、appName(应用名)、packageName(Android 包名)、abis(CPU 架构)、icon/splash(图标启动图路径,相对项目根)、wwwSource(可选:指定 App 资源目录,留空则自动用 dist/build/app 或 unpackage/resources)、signing(keystore 路径/密码)。
`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)。
## 根目录其他配置
| 文件 | 说明 | git |
|---|---|---|
| `.env` / `.env.electron` | Vite 构建目标(web/electron),无敏感信息 | ✅ 提交 |
| `.env.example` | 环境变量模板(接口地址等),复制为 `.env.local` 填写 | ✅ 提交 |
| `.env.local` | 本地环境变量(含内网接口地址,勿提交) | ❌ 不提交(匹配 `*.local`) |
| `.env.local` | 本地开发环境变量(含内网测试接口地址,勿提交;**仅 dev 生效**,生产构建固定走 `https://qimen.wms.gztbyc.com`,见 `env.js`) | ❌ 不提交(匹配 `*.local`) |
| `env.js` | 前端环境模块(读 Vite 环境变量,不写死敏感地址) | ✅ 提交 |
| `electron-builder.config.cjs` | exe 打包配置(无敏感) | ✅ 提交 |
@ -33,6 +37,7 @@
## 新机器初始化清单
1. `cp config/android.example.json config/android.json` 并填写(签名密钥放入 `android-offline/keystore/`)
2. `cp .env.example .env.local` 并填写接口地址
2. `cp config/deploy.example.json config/deploy.json` 并填写(仅发布 APK 时需要)
3. `cp .env.example .env.local` 并填写接口地址
3. `npm install`
4. 打包:`npm run build:exe`(Windows)、`npm run android:pack`(Android)
4. 打包:`npm run build:exe`(Windows,发布到 worker_station_windows)、`npm run android:pack`(Android,发布到 worker_station)

View File

@ -0,0 +1,21 @@
{
"_comment": "发布配置模板:复制本文件为 config/deploy.json 并填写真实值(deploy.json 已 git 忽略,不提交;本模板不含真实服务器信息)。android 段用于 APK 发布,windows 段用于 exe 发布,各字段含义见 config/README.md。",
"android": {
"host": "your-server-ip",
"port": 22,
"user": "your-ssh-user",
"keyPath": "C:/Users/yourname/.ssh/your_key",
"remoteDir": "/your/www/upload/dir",
"downloadUrlPrefix": "https://your-download-domain/your-project/",
"latestJsonName": "latest.json"
},
"windows": {
"host": "your-server-ip",
"port": 22,
"user": "your-ssh-user",
"keyPath": "C:/Users/yourname/.ssh/your_key",
"remoteDir": "/your/www/upload/dir",
"downloadUrlPrefix": "https://your-download-domain/your-project/",
"latestJsonName": "latest.json"
}
}

BIN
electron/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View File

@ -1,14 +1,97 @@
const { app, BrowserWindow, session } = require('electron')
const { app, BrowserWindow, session, ipcMain, shell, Tray, Menu, nativeImage } = require('electron')
const path = require('path')
const fs = require('fs')
const os = require('os')
const https = require('https')
const http = require('http')
const devServerUrl = process.env.ELECTRON_RENDERER_URL
const rendererEntry = path.join(__dirname, '..', 'dist', 'build', 'h5', 'index.html')
let tray = null
let isQuitting = false
if (devServerUrl) {
app.commandLine.appendSwitch('disable-http-cache')
}
function createWindow() {
// ---------- 本地静态服务:history 模式路由需要 http 协议(file:// 下 pushState 被禁用) ----------
const STATIC_MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.mp3': 'audio/mpeg',
'.map': 'application/json; charset=utf-8',
}
let staticServer = null
let staticServerPort = 0
function serveFile(filePath, res) {
const ext = path.extname(filePath).toLowerCase()
res.writeHead(200, { 'Content-Type': STATIC_MIME[ext] || 'application/octet-stream' })
fs.createReadStream(filePath).pipe(res)
}
function startStaticServer() {
if (staticServer) {
return Promise.resolve(staticServerPort)
}
const rootDir = path.dirname(rendererEntry)
const server = http.createServer((req, res) => {
let urlPath = '/'
try {
urlPath = decodeURIComponent(String(req.url || '/').split('?')[0])
} catch (e) {
urlPath = '/'
}
if (!urlPath || urlPath === '/') {
serveFile(path.join(rootDir, 'index.html'), res)
return
}
// 防目录穿越
const filePath = path.normalize(path.join(rootDir, urlPath))
if (!filePath.startsWith(rootDir)) {
res.writeHead(403)
res.end('Forbidden')
return
}
fs.stat(filePath, (err, stat) => {
if (!err && stat.isDirectory()) {
serveFile(path.join(filePath, 'index.html'), res)
return
}
if (err || !stat.isFile()) {
// SPA 回退:history 路由统一返回 index.html
serveFile(path.join(rootDir, 'index.html'), res)
return
}
serveFile(filePath, res)
})
})
return new Promise((resolve, reject) => {
server.on('error', reject)
server.listen(0, '127.0.0.1', () => {
staticServer = server
staticServerPort = server.address().port
resolve(staticServerPort)
})
})
}
async function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
@ -23,12 +106,170 @@ function createWindow() {
win.webContents.session.clearCache().catch(() => {})
win.loadURL(devServerUrl)
win.webContents.openDevTools({ mode: 'detach' })
return
} else {
const port = await startStaticServer()
win.loadURL(`http://127.0.0.1:${port}/`)
}
win.loadFile(rendererEntry)
// 不显示窗口标题栏下的菜单
win.removeMenu()
// 点关闭按钮时不退出,隐藏到托盘;托盘菜单退出时才真正退出
win.on('close', (event) => {
if (!isQuitting) {
event.preventDefault()
win.hide()
}
})
// 外部链接(更新下载地址等)交给系统浏览器打开
win.webContents.setWindowOpenHandler(({ url }) => {
if (url && url.startsWith('http')) {
require('electron').shell.openExternal(url)
}
return { action: 'deny' }
})
return win
}
function getTrayIconPath() {
const candidates = [
path.join(__dirname, 'icon.png'),
path.join(__dirname, '..', 'src', 'static', 'images', '1.png'),
path.join(__dirname, '..', 'dist', 'build', 'h5', 'static', 'images', '1.png'),
]
return candidates.find((p) => fs.existsSync(p)) || ''
}
function createTray(mainWindow) {
if (tray) {
return tray
}
const iconPath = getTrayIconPath()
let image = nativeImage.createEmpty()
if (iconPath) {
const loaded = nativeImage.createFromPath(iconPath)
if (!loaded.isEmpty()) {
image = loaded.resize({ width: 16, height: 16 })
}
}
tray = new Tray(image)
tray.setToolTip('WMS工作台')
const showWindow = () => {
if (!mainWindow || mainWindow.isDestroyed()) {
return
}
mainWindow.show()
if (mainWindow.isMinimized()) {
mainWindow.restore()
}
mainWindow.focus()
}
tray.on('click', showWindow)
tray.setContextMenu(
Menu.buildFromTemplate([
{ label: '显示主界面', click: showWindow },
{ type: 'separator' },
{
label: '退出',
click: () => {
isQuitting = true
app.quit()
},
},
])
)
return tray
}
function setupCorsHeaders() {
// 允许渲染进程跨域读取发布服务器上的 latest.json 等文件
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Access-Control-Allow-Origin': ['*'],
},
})
})
}
// ---------- 内置更新下载(主进程,支持重定向/重试与进度回传) ----------
function downloadUpdateFile(url, dest, onProgress) {
return new Promise((resolve, reject) => {
const maxAttempts = 3
let attempt = 0
const tryOnce = () => {
attempt++
const start = (target, redirects) => {
if (redirects > 5) {
reject(new Error('重定向次数过多'))
return
}
const request = https.get(
target,
{ headers: { 'User-Agent': 'wms-worker-station-updater' } },
(res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume()
start(new URL(res.headers.location, target).toString(), redirects + 1)
return
}
if (res.statusCode !== 200) {
res.resume()
reject(new Error(`HTTP ${res.statusCode}`))
return
}
const total = Number(res.headers['content-length'] || 0)
let received = 0
const file = fs.createWriteStream(dest)
res.on('data', (chunk) => {
received += chunk.length
onProgress(received, total)
})
res.pipe(file)
file.on('finish', () => {
file.close(() => resolve(dest))
})
file.on('error', (error) => reject(error))
}
)
request.on('error', (error) => {
if (attempt < maxAttempts) {
console.warn(`[updater] 下载失败,重试 ${attempt}/${maxAttempts}: ${error.message}`)
tryOnce()
} else {
reject(error)
}
})
}
start(url, 0)
}
tryOnce()
})
}
ipcMain.handle('download-update', async (event, url) => {
const tmpPath = path.join(os.tmpdir(), `wms-worker-station-${Date.now()}-setup.exe`)
await downloadUpdateFile(url, tmpPath, (received, total) => {
if (!event.sender.isDestroyed()) {
event.sender.send('download-progress', { received, total })
}
})
return tmpPath
})
ipcMain.handle('open-installer', async (_event, filePath) => {
const result = await shell.openPath(filePath)
return result
})
function setupMediaPermissions() {
const ses = session.defaultSession
if (!ses) {
@ -55,19 +296,51 @@ function setupMediaPermissions() {
}
}
app.whenReady().then(() => {
setupMediaPermissions()
createWindow()
// ---------- 单实例锁:防止同时打开两个应用实例 ----------
const gotTheLock = app.requestSingleInstanceLock()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
if (!gotTheLock) {
app.quit()
} else {
// 用户再次启动应用时,唤起已有实例的窗口
app.on('second-instance', () => {
const win = BrowserWindow.getAllWindows()[0]
if (win) {
if (win.isMinimized()) {
win.restore()
}
win.show()
win.focus()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.whenReady().then(async () => {
setupMediaPermissions()
setupCorsHeaders()
const win = await createWindow()
createTray(win)
app.on('activate', async () => {
const allWindows = BrowserWindow.getAllWindows()
if (allWindows.length === 0) {
try {
await createWindow()
} catch (error) {
console.error('[static-server] 启动失败:', error)
}
} else {
allWindows[0].show()
}
})
})
app.on('before-quit', () => {
isQuitting = true
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
}

View File

@ -1,5 +1,15 @@
const { contextBridge } = require('electron')
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
platform: process.platform,
// 内置下载更新安装包(主进程下载,返回本地临时文件路径)
downloadUpdate: (url) => ipcRenderer.invoke('download-update', url),
// 监听下载进度,返回取消监听函数
onDownloadProgress: (callback) => {
const listener = (_event, data) => callback(data)
ipcRenderer.on('download-progress', listener)
return () => ipcRenderer.removeListener('download-progress', listener)
},
// 打开本地安装包(启动 NSIS 安装向导)
openInstaller: (filePath) => ipcRenderer.invoke('open-installer', filePath),
})

10
env.js
View File

@ -1,4 +1,10 @@
// 环境地址统一走 Vite 环境变量(见 .env.example / .env.local,敏感地址勿提交 git)
export const BASE_URL = import.meta.env.VITE_API_BASE_URL || '' // 接口根地址,由 .env.local 注入
// 生产接口根地址:所有 production 构建(electron 打包 / Android 打包)统一指向生产域名,
// 避免构建机上残留的 .env.local 测试地址被带进生产包
const PROD_API_BASE = 'https://qimen.wms.gztbyc.com'
// 开发环境地址走 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 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.1",
"version": "1.0.18",
"description": "WMS仓库工作台桌面端",
"author": "tianbao",
"main": "electron/main.js",

View File

@ -1,13 +1,20 @@
/**
* 一键打包 Windows exe:
* 1. 编译前端资源到 dist/build/h5(uni build --mode electron)
* 2. 调用 electron-builder 生成 NSIS 安装包,输出到 release/
* 一键打包 Windows exe 并发布:
* 1. 编译前端资源(uni build --mode electron)
* 2. electron-builder 生成 NSIS 安装包,输出 release/windows/
* 3. 可选:读取 config/deploy.json 的 windows 段,scp 上传安装包与 latest.json
* 用法:node scripts/build-exe.cjs [--no-upload]
*/
const { spawnSync } = require('child_process')
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const ROOT = path.resolve(__dirname, '..')
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm'
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx'
const useShell = process.platform === 'win32'
const noUpload = process.argv.includes('--no-upload')
function run(cmd, args) {
const command = `${cmd} ${args.join(' ')}`
@ -22,7 +29,85 @@ function run(cmd, args) {
console.log('[1/2] 编译前端资源 -> dist/build/h5')
run(npmCmd, ['run', 'build:h5:electron'])
console.log('\n[2/2] electron-builder 打包 exe -> release/')
console.log('\n[2/2] electron-builder 打包 exe -> release/windows/')
run(npxCmd, ['electron-builder', '--config', 'electron-builder.config.cjs'])
// ---------- 3. 发布上传(config/deploy.json 的 windows 段) ----------
if (noUpload) {
console.log('\n[跳过] --no-upload 已指定,跳过发布上传')
} else {
const deployPath = path.join(ROOT, 'config', 'deploy.json')
if (!fs.existsSync(deployPath)) {
console.log('\n[跳过] 未找到 config/deploy.json,跳过发布上传(复制 config/deploy.example.json 并填写)')
} else {
let deploy
try {
deploy = JSON.parse(fs.readFileSync(deployPath, 'utf-8'))
} catch (error) {
console.error(`\n[x] config/deploy.json 解析失败: ${error.message}`)
process.exit(1)
}
const win = deploy.windows
if (!win || !win.host || !win.user || !win.remoteDir || !win.downloadUrlPrefix) {
console.log('\n[跳过] config/deploy.json 缺少 windows 段或字段不全,跳过发布上传')
} else {
const keyPath = win.keyPath || ''
if (keyPath && !fs.existsSync(keyPath)) {
console.error(`\n[x] SSH 密钥不存在: ${keyPath}`)
process.exit(1)
}
const port = String(win.port || 22)
const remoteDir = String(win.remoteDir).replace(/\/$/, '')
const urlPrefix = String(win.downloadUrlPrefix).replace(/\/?$/, '/')
const latestName = win.latestJsonName || 'latest.json'
// 定位 NSIS 安装包(按当前版本精确匹配,避免目录残留旧包被误选)
const outDir = path.join(ROOT, 'release', 'windows')
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8'))
const version = pkg.version
const productName = 'WMS工作台'
const expectedName = `${productName}-${version}-setup.exe`
const setupExe = fs.existsSync(path.join(outDir, expectedName))
? expectedName
: fs.readdirSync(outDir).find(
(file) => file.endsWith('.exe') && file.includes('setup') && !file.includes('__uninstaller')
)
if (!setupExe) {
console.error('\\n[x] 未在 release/windows 找到安装包')
process.exit(1)
}
const exePath = path.join(outDir, setupExe)
const sha256 = crypto.createHash('sha256').update(fs.readFileSync(exePath)).digest('hex')
const latest = {
version,
file: setupExe,
url: `${urlPrefix}${setupExe}`,
sha256,
publishedAtUtc: new Date().toISOString(),
}
const latestPath = path.join(outDir, latestName)
fs.writeFileSync(latestPath, JSON.stringify(latest, null, 2) + '\n', 'utf-8')
console.log(`\n[3/3] 发布上传 -> ${win.user}@${win.host}:${remoteDir}/ ...`)
const scpArgs = [
...(keyPath ? ['-i', keyPath] : []),
'-P', port,
'-o', 'StrictHostKeyChecking=accept-new',
]
const target = `${win.user}@${win.host}:${remoteDir}/`
const uploadExe = spawnSync('scp', [...scpArgs, exePath, target], { stdio: 'inherit' })
if (uploadExe.status !== 0) {
console.error(`\n[x] 安装包上传失败(scp 退出码 ${uploadExe.status})`)
process.exit(uploadExe.status || 1)
}
const uploadLatest = spawnSync('scp', [...scpArgs, latestPath, target], { stdio: 'inherit' })
if (uploadLatest.status !== 0) {
console.error(`\n[x] ${latestName} 上传失败(scp 退出码 ${uploadLatest.status})`)
process.exit(uploadLatest.status || 1)
}
console.log(`\n[ok] 发布完成: ${urlPrefix}${setupExe}`)
}
}
}
console.log('\n[ok] 打包完成,安装包位于 release/windows/ 目录')

View File

@ -137,6 +137,13 @@ function New-Splash([string]$path) {
$iconPath = 'd:\wms_worker_station\android-offline\icon\app-icon.png'
$splashPath = 'd:\wms_worker_station\android-offline\splash\splash.png'
$buildIconDir = 'd:\wms_worker_station\build'
$buildIconPath = Join-Path $buildIconDir 'icon.png'
New-AppIcon $iconPath
New-Splash $splashPath
# Windows exe icon: electron-builder auto-converts build/icon.png (>=256x256) to .ico
if (-not (Test-Path $buildIconDir)) { New-Item -ItemType Directory -Path $buildIconDir -Force | Out-Null }
Copy-Item -Path $iconPath -Destination $buildIconPath -Force
Write-Host "windows icon saved: $buildIconPath"

4
shims-uni.d.ts vendored
View File

@ -1,6 +1,10 @@
/// <reference types='@dcloudio/types' />
import 'vue'
declare const __APP_BUILD_TARGET__: string
declare const __APP_IS_ELECTRON__: boolean
declare const __APP_VERSION__: string
declare module '@vue/runtime-core' {
type Hooks = App.AppInstance & Page.PageInstance;

View File

@ -1,10 +1,12 @@
<script>
import { guardCurrentPage } from './core/nav-guard'
// rem 基准:以 1920×1280 设计稿为准,100px = 1rem,按宽高取小(contain)缩放
const DESIGN_WIDTH = 1920
const DESIGN_HEIGHT = 1280
const BASE_FONT_SIZE = 100
// 整体缩放系数:<1 整体缩小,>1 整体放大(布局偏大就调小这个值)
const REM_SCALE = 0.45
// 0.45 平板触摸尺寸基准偏大;桌面全屏(1920×1080)统一调整为 0.28
const REM_SCALE = 0.28
function logScreenInfo () {
try {
@ -69,6 +71,8 @@ export default {
onShow: function () {
console.log('App Show')
setRemBase()
// 页面级守卫:覆盖直接打开/刷新进入受保护页面的场景(跳转 API 已由 installNavGuard 接管)
guardCurrentPage()
},
onHide: function () {
console.log('App Hide')

View File

@ -81,7 +81,7 @@ export function logout() {
/**
* 按 token(ye4s 登录临时码)查询用户信息(免登录、免鉴权)
* - 以 ye4s 库 ye4s_user 表 tmp_code 字段为入参查询用户
* - 以 ye4s 库 ye4s_user 表 tmp_code 字段为入参查询用户;工牌码(base64)也走此接口,由后端自行识别
* - 命中返回 flag=success、code=200 与 real_name(真实姓名)、wms_account_id(WMS 账号 ID)
* - 未命中返回 flag=failure、code=404(用户不存在);token 为空返回 code=400
*/

View File

@ -1,4 +1,5 @@
import { API_URL } from '@/config/api'
import { appEnv } from '@/config/env'
/** 与后端约定的通用响应结构(字段名因接口可能略有差异) */
export type ApiBody<T = unknown> = {
@ -27,6 +28,9 @@ const DEFAULT_HEADERS: Record<string, string> = {
'content-type': 'application/json',
platform: 'workerstation',
project: 'warehouse',
// 透传应用版本与打包类型,便于后端按端统计/控制
'app-version': appEnv.version,
'pack-type': appEnv.packType,
}
function getAuthHeader(): Record<string, string> {

View File

@ -49,6 +49,7 @@ import { changeUserRole, fetchUserInfo, logout } from '@/api/index'
export default {
name: 'TopNav',
emits: ['menu-click', 'user-changed'],
props: {
menus: {
type: Array,
@ -66,6 +67,16 @@ export default {
type: String,
default: '未登录用户',
},
// 外部传入的用户信息(user.info 响应),传了就由父组件负责拉取,组件内不再重复请求
userInfo: {
type: Object,
default: null,
},
// 无 userInfo 时是否自行拉取 user.info(独立页面保持自行拉取)
fetchUser: {
type: Boolean,
default: true,
},
},
data() {
return {
@ -123,10 +134,22 @@ export default {
this.syncActiveIndex()
},
},
userInfo: {
deep: true,
handler(val) {
if (val && typeof val === 'object') {
this.currentUser = val
}
},
},
},
created() {
this.syncActiveIndex()
this.loadCurrentUserInfo()
if (this.userInfo) {
this.currentUser = this.userInfo
} else if (this.fetchUser) {
this.loadCurrentUserInfo()
}
},
mounted() {
this.lastRoutePath = this.getCurrentRoutePath()
@ -302,16 +325,32 @@ export default {
this.closeMinePopup()
},
getTopNavRealName() {
const employees = this.currentUser?.employees || []
if (employees.length && employees[0]?.real_name) {
return employees[0].real_name
const user = this.currentUser
// 优先后端返回的当前激活身份名称(employees_name / employees_id)
if (user?.employees_name) {
return user.employees_name
}
const employees = user?.employees || []
if (user?.employees_id != null && user?.employees_id !== '') {
const matched = employees.find((e) => String(e?.id) === String(user.employees_id))
if (matched?.real_name) {
return matched.real_name
}
}
const primary = employees.find((e) => Number(e?.is_primary) === 1)
if (primary?.real_name) {
return primary.real_name
}
if (this.userName && this.userName !== '未登录用户') {
return this.userName
}
return this.currentUser?.real_name || '未命名用户'
return user?.real_name || '未命名用户'
},
isCurrentRole(employee) {
const currentId = this.currentUser?.employees_id
if (currentId != null && currentId !== '' && employee?.id != null) {
return String(employee.id) === String(currentId)
}
return Number(employee?.is_primary) === 1
},
openMinePopup() {
@ -347,7 +386,11 @@ export default {
return
}
this.loadCurrentUserInfo()
this.$emit('user-changed')
// 由父组件负责重新拉取用户信息;独立使用(无 userInfo)时自行刷新
if (!this.userInfo) {
this.loadCurrentUserInfo()
}
this.closeMinePopup()
uni.showToast({
title: '角色切换成功',

View File

@ -8,6 +8,26 @@ const fromRuntime =
const isElectron = fromBuildTarget || fromRuntime
// #ifdef APP-PLUS
const isApp = true
// #endif
// #ifndef APP-PLUS
const isApp = false
// #endif
// 应用版本(构建时由 vite define 从 package.json 注入)
const version = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.0.0'
// 打包类型:electron=桌面端 / android=App / web=浏览器
const packType = isElectron ? 'electron' : isApp ? 'android' : 'web'
const packTypeLabel = isElectron ? '桌面端' : isApp ? 'Android端' : 'Web端'
// 更新检测地址(公开下载服务器;web 端无安装包不检测)
const updateLatestUrl = isElectron
? 'https://dl.wms.gztbyc.com/worker_station_windows/latest.json'
: isApp
? 'https://dl.wms.gztbyc.com/worker_station/latest.json'
: ''
export const appEnv = {
mode: import.meta.env.MODE,
buildTarget: import.meta.env.VITE_BUILD_TARGET || 'web',
@ -15,6 +35,11 @@ export const appEnv = {
isProd: import.meta.env.PROD,
isH5,
isElectron,
isApp,
version,
packType,
packTypeLabel,
updateLatestUrl,
}
export default appEnv

131
src/core/nav-guard.js Normal file
View File

@ -0,0 +1,131 @@
/**
* 轻量路由前置守卫(替代 uni-simple-router 的 beforeEach)
* - 统一接管 uni.navigateTo / redirectTo / reLaunch
* - 未登录访问受保护页面时自动跳转登录页
* - 支持 beforeEach 注册自定义钩子,用法与 uni-simple-router 类似:
* beforeEach((to, from, next) => { ...; next() 放行 / next(false) 拦截 })
*/
// 需要登录才能进入的页面(与 pages.json 中的 path 对应)
const AUTH_PAGES = [
'/pages/index/index',
'/pages/packaging/index',
'/pages/order/index',
'/pages/weighing/index',
'/pages/returns/index',
]
const LOGIN_PATH = '/pages/login/login'
/** 自定义前置钩子 */
const beforeHooks = []
/** 注册前置钩子:钩子内必须同步调用 next()(放行)或 next(false)(拦截) */
export function beforeEach(fn) {
if (typeof fn === 'function') {
beforeHooks.push(fn)
}
}
/** 是否已登录(token 或 workbench_token 任一存在) */
export function hasLoginToken() {
return !!(uni.getStorageSync('token') || uni.getStorageSync('workbench_token'))
}
/** 归一化跳转路径:去 query、保证以 / 开头 */
export function normalizeNavUrl(url) {
const raw = String(url || '').trim()
if (!raw) {
return ''
}
const path = raw.split('?')[0]
return path.startsWith('/') ? path : `/${path}`
}
/** 该路径是否受登录保护 */
export function isAuthedPath(url) {
const path = normalizeNavUrl(url)
return AUTH_PAGES.some((p) => path === p)
}
/**
* 前置守卫:依次执行 beforeHooks,全部放行后再做登录校验
* @returns {boolean} true 放行,false 拦截本次跳转
*/
export function navGuard(url) {
const path = normalizeNavUrl(url)
if (!path) {
return true
}
let pass = true
for (const hook of beforeHooks) {
hook({ path }, {}, (ok = true) => {
pass = !!ok
})
if (!pass) {
return false
}
}
if (isAuthedPath(path) && !hasLoginToken()) {
uni.reLaunch({ url: LOGIN_PATH })
return false
}
return true
}
/**
* 页面级守卫:检查当前页面栈栈顶页面。
* 覆盖「直接打开 URL / 刷新 / 深链进入」等不经过 uni 跳转 API 的场景,
* 建议在 App.onShow 中调用(启动、刷新、回前台时都会触发)。
*/
export function guardCurrentPage() {
let path = ''
// #ifdef H5
if (typeof window !== 'undefined' && window.location) {
const loc = window.location
const hashMatched = String(loc.hash || '').match(/^#?(\/[^\s?#]+)/)
if (hashMatched) {
// hash 模式:路由在 # 后
path = hashMatched[1]
} else if (loc.pathname && loc.pathname !== '/') {
// history 模式:路由即 pathname
path = loc.pathname
}
}
// #endif
const pages = getCurrentPages()
const top = pages && pages[pages.length - 1]
if (!path && top && top.route) {
path = `/${String(top.route).replace(/^\//, '')}`
}
if (path && isAuthedPath(path) && !hasLoginToken()) {
uni.reLaunch({ url: LOGIN_PATH })
}
}
let installed = false
/** 安装守卫:重写 uni 原生跳转 API(需在 createApp 中、任何跳转发生前调用) */
export function installNavGuard() {
if (installed) {
return
}
installed = true
;['navigateTo', 'redirectTo', 'reLaunch'].forEach((method) => {
const origin = uni[method]
if (typeof origin !== 'function') {
return
}
uni[method] = function (options) {
const url = typeof options === 'string' ? options : (options && options.url) || ''
if (!url || !navGuard(url)) {
return
}
return origin.call(uni, options)
}
})
}

385
src/core/scan.js Normal file
View File

@ -0,0 +1,385 @@
/**
* 通用全局扫码捕获模块
* - H5/Electron: document 捕获阶段 keydown 缓冲字符
* - APP-PLUS: plus.key keydown/keyup 缓冲(兼容 Android 原生 keycode)
* - 页面通过 registerScanReceiver 注册接收;同一时刻仅一个接收者
* - Enter 或超时(380ms/420ms)flush;长度 < minLength 的码直接丢弃
* - setScanPaused(true) 暂停捕获(如账号/密码输入框聚焦时)
*/
// Android KeyEvent 符号键映射(KEYCODE_* → 字符)。
// 这些 keyCode 与 ASCII 字母/数字区间重叠,必须优先于 ASCII 分支判断,
// 否则 KEYCODE_EQUALS=70 会被 ASCII 的 [65..90] 分支误读为 'F'。
const ANDROID_PUNCT_MAP = {
55: ',', // KEYCODE_COMMA
56: '.', // KEYCODE_PERIOD
62: ' ', // KEYCODE_SPACE
68: '`', // KEYCODE_GRAVE
69: '-', // KEYCODE_MINUS
70: '=', // KEYCODE_EQUALS
71: '[', // KEYCODE_LEFT_BRACKET
72: ']', // KEYCODE_RIGHT_BRACKET
73: '\\', // KEYCODE_BACKSLASH
74: ';', // KEYCODE_SEMICOLON
75: "'", // KEYCODE_APOSTROPHE
76: '/', // KEYCODE_SLASH
77: '@', // KEYCODE_AT
81: '+', // KEYCODE_PLUS
}
let receiver = null
let paused = false
let minLength = 5
let buffer = ''
let startedAt = 0
let lastAt = 0
let timer = null
let domListenerAttached = false
let plusAttached = false
let plusKeyStyle = null // 'android' | 'ascii'
let plusShiftDown = false
let plusShiftPrev = false
let plusLetterCase = 'auto'
let plusLetterCaseLag = 1
let plusKeyEventType = null
function debug(...args) {
if (receiver && typeof receiver.onScanDebug === 'function') {
try {
receiver.onScanDebug(...args)
} catch (e) {
// ignore
}
return
}
console.log('[scan-global]', ...args)
}
function clearTimer() {
if (timer) {
clearTimeout(timer)
timer = null
}
}
function resetBuffer() {
clearTimer()
buffer = ''
startedAt = 0
lastAt = 0
}
function flush(trigger, source) {
clearTimer()
const code = buffer.trim()
const durationMs = startedAt ? Math.max(0, (lastAt || Date.now()) - startedAt) : 0
buffer = ''
startedAt = 0
lastAt = 0
if (!code) {
return
}
// 少于最小长度的码直接丢弃(可能是键盘误按/短码)
if (code.length < minLength) {
debug('code-dropped', { reason: 'too-short', code, length: code.length, minLength, trigger, source })
return
}
debug('flush-buffer', { code, length: code.length, durationMs, trigger, source })
if (receiver && typeof receiver.onScanCode === 'function') {
try {
receiver.onScanCode(code, { trigger, source, durationMs })
} catch (e) {
debug('receiver-error', { message: e && e.message })
}
}
}
function appendChar(ch) {
const now = Date.now()
if (!buffer) {
startedAt = now
}
lastAt = now
buffer += ch
clearTimer()
timer = setTimeout(() => flush('timer', 'dom'), 380)
}
// ---------- DOM(H5/Electron) ----------
function onDomKeydown(event) {
if (!receiver || paused) {
return
}
const key = event?.key || ''
const isPrintable = key.length === 1
const isEnter = key === 'Enter'
if (!isPrintable && !isEnter) {
return
}
debug('key-captured', { key, paused })
if (isPrintable) {
appendChar(key)
return
}
flush('enter', 'dom')
}
function ensureDomListener() {
if (domListenerAttached) {
return
}
const target = typeof document !== 'undefined' ? document : typeof window !== 'undefined' ? window : null
if (!target) {
return
}
target.addEventListener('keydown', onDomKeydown, true)
domListenerAttached = true
debug('dom-listener-attached')
}
function removeDomListener() {
if (!domListenerAttached) {
return
}
const target = typeof document !== 'undefined' ? document : typeof window !== 'undefined' ? window : null
if (target) {
target.removeEventListener('keydown', onDomKeydown, true)
}
domListenerAttached = false
}
// ---------- APP-PLUS(plus.key) ----------
function hasPlusKeyboardSupport() {
// #ifdef APP-PLUS
return typeof plus !== 'undefined' && !!plus?.key?.addEventListener
// #endif
// #ifndef APP-PLUS
return false
// #endif
}
function parsePlusKeyCodeToChar(keyCode) {
// Android Enter=66 在 ASCII 里是 'B',必须先排除,交给 isPlusEnterKey 处理
if (keyCode === 66) {
plusKeyStyle = plusKeyStyle || 'android'
return ''
}
// ---- Android 原生 keycode ----
if (keyCode >= 7 && keyCode <= 16) {
plusKeyStyle = plusKeyStyle || 'android'
return String(keyCode - 7) // 0-9
}
if (keyCode >= 29 && keyCode <= 54) {
plusKeyStyle = plusKeyStyle || 'android'
return String.fromCharCode(keyCode - 29 + 65) // A-Z
}
// Android 符号键:必须放在 ASCII 分支之前(防止 70('=') → 'F' 这类误读)
if (plusKeyStyle !== 'ascii' && ANDROID_PUNCT_MAP[keyCode] !== undefined) {
plusKeyStyle = plusKeyStyle || 'android'
return ANDROID_PUNCT_MAP[keyCode]
}
// ---- ASCII/DOM 风格(其它设备兑底)----
if (keyCode >= 48 && keyCode <= 57) {
plusKeyStyle = plusKeyStyle || 'ascii'
return String.fromCharCode(keyCode)
}
if (keyCode >= 65 && keyCode <= 90) {
plusKeyStyle = plusKeyStyle || 'ascii'
return String.fromCharCode(keyCode)
}
if (keyCode >= 96 && keyCode <= 105) {
plusKeyStyle = plusKeyStyle || 'ascii'
return String(keyCode - 96)
}
if (keyCode === 189 || keyCode === 109) {
return '-'
}
if (keyCode === 190 || keyCode === 110) {
return '.'
}
if (keyCode === 191 || keyCode === 111) {
return '/'
}
return ''
}
// 应用字母大小写策略(仅对 A-Z 生效)
function applyLetterCase(ch, shifted) {
if (!ch || ch.length !== 1 || ch < 'A' || ch > 'Z') {
return ch
}
const mode = plusLetterCase || 'upper'
if (mode === 'lower') {
return ch.toLowerCase()
}
if (mode === 'auto') {
return shifted ? ch : ch.toLowerCase()
}
return ch // 'upper'
}
// 判断是否为 Enter:Android 原生 Enter=66;ASCII 风格为 13
function isPlusEnterKey(keyCode, text) {
if (text) {
return false
}
if (keyCode === 66) {
return true
}
if (keyCode === 13) {
return plusKeyStyle !== 'android'
}
return false
}
function handlePlusKeyEvent(event, type) {
if (!receiver || paused) {
return
}
const keyCode = Number((event && event.keyCode) || 0)
// 跟踪 Shift 修饰键(Android KEYCODE_SHIFT_LEFT=59 / SHIFT_RIGHT=60)
if (keyCode === 59 || keyCode === 60) {
if (type === 'keydown') {
plusShiftDown = true
} else if (type === 'keyup') {
plusShiftDown = false
}
return
}
const rawChar = parsePlusKeyCodeToChar(keyCode)
// Shift 状态滞后补偿:本机实测 Shift 状态比字符滞后 1 个字符
const lag = Number(plusLetterCaseLag) || 0
const isFirstChar = !buffer
const shifted = lag > 0 && !isFirstChar ? !!plusShiftPrev : !!plusShiftDown
const text = applyLetterCase(rawChar, shifted)
plusShiftPrev = plusShiftDown
const isEnter = isPlusEnterKey(keyCode, text)
if (!text && !isEnter) {
return
}
// 锁定实际生效的事件类型,避免 keydown/keyup 都触发时把一个键记两次
if (!plusKeyEventType) {
plusKeyEventType = type
}
if (plusKeyEventType !== type) {
return
}
if (text) {
const now = Date.now()
if (!buffer) {
startedAt = now
}
lastAt = now
buffer += text
clearTimer()
timer = setTimeout(() => flush('timer', 'plus'), 420)
return
}
flush('enter', 'plus')
}
function onPlusKeyDown(event) {
handlePlusKeyEvent(event, 'keydown')
}
function onPlusKeyUp(event) {
handlePlusKeyEvent(event, 'keyup')
}
function ensurePlusListener() {
if (plusAttached || !hasPlusKeyboardSupport()) {
return
}
// #ifdef APP-PLUS
plus.key.addEventListener('keydown', onPlusKeyDown)
plus.key.addEventListener('keyup', onPlusKeyUp)
plusAttached = true
debug('plus-listener-attached')
// #endif
}
function removePlusListener() {
if (!plusAttached) {
return
}
// #ifdef APP-PLUS
if (hasPlusKeyboardSupport()) {
plus.key.removeEventListener('keydown', onPlusKeyDown)
plus.key.removeEventListener('keyup', onPlusKeyUp)
}
// #endif
plusAttached = false
plusKeyEventType = null
plusShiftDown = false
plusShiftPrev = false
}
// ---------- 公共 API ----------
/**
* 注册扫码接收者(页面 onShow/onReady 时调用)
* receiver: { onScanCode(code, meta), onScanDebug(...args)? }
*/
export function registerScanReceiver(next) {
if (receiver === next) {
resetBuffer()
return
}
unregisterScanReceiver(receiver)
receiver = next || null
if (receiver) {
ensureDomListener()
ensurePlusListener()
debug('receiver-registered')
}
}
/** 注销扫码接收者(页面 onHide/onUnload 时调用) */
export function unregisterScanReceiver(target) {
if (target && receiver !== target) {
return
}
receiver = null
resetBuffer()
removeDomListener()
removePlusListener()
setScanPaused(false)
}
/** 暂停/恢复捕获(账号/密码等输入框聚焦时暂停,并清空已缓冲的按键) */
export function setScanPaused(value) {
paused = !!value
if (paused) {
resetBuffer()
} else {
plusKeyEventType = null
}
}
/** 设置最小码长(默认 5),少于该长度的码丢弃 */
export function setScanMinLength(value) {
const num = Number(value)
if (num >= 1) {
minLength = Math.floor(num)
}
}
/** 清空当前缓冲 */
export function resetScanBuffer() {
resetBuffer()
}
/** 获取当前最小码长 */
export function getScanMinLength() {
return minLength
}

133
src/core/update.js Normal file
View File

@ -0,0 +1,133 @@
import { appEnv } from '@/config/env'
/** 三段版本比较:a > b 返回 1,a < b 返回 -1,相等返回 0 */
export function compareVersion(a, b) {
const pa = String(a || '').split('.').map((x) => Number(x) || 0)
const pb = String(b || '').split('.').map((x) => Number(x) || 0)
for (let i = 0; i < 3; i++) {
const x = pa[i] || 0
const y = pb[i] || 0
if (x > y) return 1
if (x < y) return -1
}
return 0
}
/**
* 检查是否有新版本(读取发布服务器 latest.json 与当前版本对比)
* 返回 null:无更新 / 不支持平台 / 网络失败;
* 否则 { version, url, sha256, canSkip }:canSkip===1 可选更新,否则(0 或缺失)强制更新
*/
export function checkAppUpdate() {
return new Promise((resolve) => {
const url = appEnv.updateLatestUrl
if (!url) {
resolve(null)
return
}
uni.request({
// 加时间戳绕过 CDN/浏览器缓存,确保拿到最新发布信息
url: `${url}${url.indexOf('?') >= 0 ? '&' : '?'}_t=${Date.now()}`,
method: 'GET',
timeout: 8000,
success: (res) => {
try {
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
const latestVersion = data && data.version
if (latestVersion && compareVersion(latestVersion, appEnv.version) > 0) {
resolve({
version: latestVersion,
url: data.url || '',
sha256: data.sha256 || '',
canSkip: data.canSkip === 1 ? 1 : 0,
})
return
}
resolve(null)
} catch (error) {
resolve(null)
}
},
fail: () => resolve(null),
})
})
}
/** 格式化下载大小 */
export function formatUpdateSize(bytes) {
const num = Number(bytes) || 0
if (num <= 0) {
return '0 KB'
}
const mb = num / 1024 / 1024
if (mb >= 1) {
return `${mb.toFixed(1)} MB`
}
return `${Math.round(num / 1024)} KB`
}
/**
* 内置下载更新安装包(带进度)
* - Electron:主进程下载(https + 重定向),通过 electronAPI 回传进度
* - App:plus.downloader
* resolve(本地文件路径)
*/
export function startUpdateDownload(url, onProgress) {
return new Promise((resolve, reject) => {
const safeProgress = onProgress || (() => {})
if (appEnv.isElectron && typeof window !== 'undefined' && window.electronAPI && window.electronAPI.downloadUpdate) {
const off = window.electronAPI.onDownloadProgress((data) => {
safeProgress(data.received || 0, data.total || 0)
})
window.electronAPI
.downloadUpdate(url)
.then((filePath) => {
if (off) off()
resolve(filePath)
})
.catch((error) => {
if (off) off()
reject(error)
})
return
}
if (appEnv.isApp && typeof plus !== 'undefined') {
const task = plus.downloader.createDownload(
url,
{},
(download, status) => {
if (status === 200) {
resolve(download.filename)
} else {
reject(new Error(`download failed: ${status}`))
}
}
)
task.addEventListener('statechanged', (download) => {
if (download.state === 3) {
safeProgress(download.downloadedSize || 0, download.totalSize || 0)
}
})
task.start()
return
}
reject(new Error('当前平台不支持内置下载'))
})
}
/** 安装已下载的安装包 */
export function installUpdatePackage(filePath) {
if (appEnv.isElectron && typeof window !== 'undefined' && window.electronAPI && window.electronAPI.openInstaller) {
window.electronAPI.openInstaller(filePath)
return
}
if (appEnv.isApp && typeof plus !== 'undefined') {
plus.runtime.install(filePath, {}, () => {}, () => {})
return
}
}
export default checkAppUpdate

View File

@ -3,10 +3,13 @@ import {
} from "vue";
import App from "./App.vue";
import appEnv from './config/env'
import { installNavGuard } from './core/nav-guard'
export function createApp() {
const app = createSSRApp(App);
app.config.globalProperties.$env = appEnv
app.provide('appEnv', appEnv)
// 路由前置守卫:必须在任何页面跳转发生前安装
installNavGuard()
return {
app,
};

View File

@ -73,5 +73,11 @@
"uniStatistics" : {
"enable" : false
},
"h5" : {
"router" : {
"mode" : "history",
"base" : "/"
}
},
"vueVersion" : "3"
}

View File

@ -4,7 +4,10 @@
:menus="topMenus"
:active-path="activeMenuPath"
:use-redirect="false"
:user-info="currentUser"
:fetch-user="false"
@menu-click="handleMenuClick"
@user-changed="handleUserChanged"
/>
<view class="layout-main">
@ -53,7 +56,15 @@ export default {
return
}
this.activeMenuPath = normalizeMenuPath(options?.menu)
// 刷新恢复时优先取 hash 路由参数,其次取 URL 外层 query(见 syncMenuToUrl)
let menu = options?.menu
if (!menu && typeof window !== 'undefined') {
const fromQuery = new URLSearchParams(window.location.search).get('menu')
if (fromQuery) {
menu = fromQuery
}
}
this.activeMenuPath = normalizeMenuPath(menu)
this.loadCurrentUserInfo()
},
data() {
@ -94,6 +105,7 @@ export default {
// #ifdef H5
if (typeof window !== 'undefined' && window.history?.replaceState) {
const query = normalizedPath ? `?menu=${encodeURIComponent(normalizedPath)}` : ''
// history 模式:pathname 即当前路由,仅替换 query,不再拼接 hash
const base = window.location.pathname || '/'
window.history.replaceState(null, '', `${base}${query}`)
}
@ -128,8 +140,11 @@ export default {
this.setActiveMenu(firstPath)
}
},
handleUserChanged() {
// 角色切换后重新拉取用户信息,再经 user-info 传给 top-nav
this.loadCurrentUserInfo()
},
handleMenuClick(menu) {
const rawPath = (menu?.path || '').trim()
if (!rawPath) {
uni.showToast({
title: '菜单路径为空',
@ -190,7 +205,8 @@ export default {
<script module="remInject" lang="renderjs">
export default {
mounted() {
const REM_SCALE = 0.45 // 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小)
// 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小);0.45 平板基准偏大,全站统一 0.28
const REM_SCALE = 0.28
const setFontSize = () => {
const docEl = document.documentElement
const width = docEl.clientWidth || window.innerWidth || 1920

View File

@ -109,6 +109,37 @@
</view>
</view>
<!-- 更新弹窗:canSkip!=1 时“跳过”置灰不可点;点击“立即更新”后才开始下载 -->
<view v-if="updateDialogVisible" class="update-mask">
<view class="update-dialog">
<view class="update-dialog__head">
<text class="update-dialog__title">发现新版本 v{{ updateInfo.version }}</text>
</view>
<text class="update-dialog__desc">
{{ updateInstalling ? '下载完成,正在打开安装程序...' : (updateError || (updateInfo.canSkip === 1 ? '检测到新版本,建议及时更新' : '为保证功能一致与数据安全,需更新后才能继续使用')) }}
</text>
<block v-if="updateDownloading">
<view class="update-progress-track">
<view class="update-progress-fill" :style="{ width: updatePercent() + '%' }"></view>
</view>
<text class="update-progress-text">{{ updatePercent() }}% · {{ updateSizeText() }}</text>
</block>
<view v-else-if="!updateInstalling" class="update-dialog__actions">
<button
class="update-dialog__btn update-dialog__btn--skip"
:class="{ 'update-dialog__btn--disabled': updateInfo.canSkip !== 1 }"
:disabled="updateInfo.canSkip !== 1"
@click="skipUpdate"
>
跳过
</button>
<button class="update-dialog__btn" type="primary" @click="handleUpdatePrimary">
{{ updateError ? '重试下载' : '立即更新' }}
</button>
</view>
</view>
</view>
<input
class="scan-hidden-input"
v-if="enableHiddenInputCapture"
@ -126,6 +157,14 @@
<script>
import { getLoginWechatCode, loginByCode, loginByAccount, getWorkbenchBindCode } from '@/api/index'
import { appEnv } from '@/config/env'
import { checkAppUpdate, startUpdateDownload, installUpdatePackage, formatUpdateSize } from '@/core/update'
import {
registerScanReceiver,
unregisterScanReceiver,
setScanPaused,
resetScanBuffer,
} from '@/core/scan'
const qrBaseUrl = 'https://ye4s.wms.gztbyc.com/grcode/build?text='
const qrFallbackBaseUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=280x280&data='
@ -212,6 +251,12 @@ export default {
workbenchRequestTimeout: 120000,
workbenchRequestAbort: null,
autoEnterPackTimer: null,
updateInfo: null,
updateDialogVisible: false,
updateDownloading: false,
updateInstalling: false,
updateError: '',
updateProgress: { received: 0, total: 0 },
}
},
onUnload() {
@ -222,8 +267,7 @@ export default {
this.abortWorkbenchRequest()
this.scanLoading = false
this.workbenchLoading = false
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.unregisterScanCapture()
this.clearScanFocusResumeTimer()
this.clearKeyboardSuppressTimers()
this.clearHiddenRefocusTimer()
@ -234,16 +278,15 @@ export default {
this.pageActive = true
this.hasStoredWorkbench = !!uni.getStorageSync('workbench_token')
this.setupScanCaptureMode()
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
this.registerScanCapture()
this.suppressSoftKeyboardBurst()
this.scheduleScanInputFocus(260)
this.checkAppUpdate()
},
onShow() {
this.pageActive = true
this.setupScanCaptureMode()
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
this.registerScanCapture()
this.suppressSoftKeyboardBurst()
this.scheduleScanInputFocus(320)
this.resumeWorkbenchFlow()
@ -257,8 +300,7 @@ export default {
this.abortWorkbenchRequest()
this.scanLoading = false
this.workbenchLoading = false
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.unregisterScanCapture()
this.clearScanFocusResumeTimer()
this.clearKeyboardSuppressTimers()
this.clearHiddenScanTimer()
@ -276,8 +318,7 @@ export default {
this.abortWorkbenchRequest()
this.scanLoading = false
this.workbenchLoading = false
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.unregisterScanCapture()
this.clearScanFocusResumeTimer()
this.clearKeyboardSuppressTimers()
this.clearHiddenRefocusTimer()
@ -293,6 +334,78 @@ export default {
isPageActive() {
return this.pageActive !== false
},
/** 检测发布服务器上是否有新版本;有新版本则弹窗提示(不自动下载) */
checkAppUpdate() {
if (!appEnv.updateLatestUrl) {
return
}
checkAppUpdate().then((info) => {
if (!info || !this.isPageActive()) {
return
}
this.updateInfo = info
this.updateDialogVisible = true
})
},
/** 点击“立即更新”:内置下载(带进度),完成后自动安装 */
startUpdateDownload() {
const info = this.updateInfo
if (!info || !info.url || this.updateDownloading || this.updateInstalling) {
return
}
this.updateDownloading = true
this.updateError = ''
this.updateProgress = { received: 0, total: 0 }
startUpdateDownload(info.url, (received, total) => {
if (this.isPageActive()) {
this.updateProgress = { received, total }
}
})
.then((filePath) => {
this.updateDownloading = false
this.updateInstalling = true
installUpdatePackage(filePath)
})
.catch((error) => {
if (!this.isPageActive()) {
return
}
this.updateDownloading = false
const reason = error && error.message ? error.message : '网络异常'
this.updateError = `下载失败(${reason}),请检查网络后重试`
})
},
retryUpdateDownload() {
this.startUpdateDownload()
},
/** 主按钮:下载失败时重试,否则开始下载 */
handleUpdatePrimary() {
if (this.updateError) {
this.retryUpdateDownload()
} else {
this.startUpdateDownload()
}
},
/** 跳过更新:仅 canSkip===1 且未在下载/安装中时可点 */
skipUpdate() {
if (!this.updateInfo || this.updateInfo.canSkip !== 1) {
return
}
if (this.updateDownloading || this.updateInstalling) {
return
}
this.updateDialogVisible = false
},
updatePercent() {
const { received, total } = this.updateProgress
if (!total || total <= 0) {
return 0
}
return Math.min(100, Math.round((received / total) * 100))
},
updateSizeText() {
return `${formatUpdateSize(this.updateProgress.received)} / ${formatUpdateSize(this.updateProgress.total)}`
},
switchMode(mode) {
if (!this.isPageActive()) {
return
@ -314,6 +427,7 @@ export default {
this.scanGlobalKeyBuffer = ''
this.scanPlusKeyBuffer = ''
this.scanHiddenValue = ''
resetScanBuffer()
} else if (mode === 'scan') {
this.stopWorkbenchLongPolling()
this.abortWorkbenchRequest()
@ -389,6 +503,24 @@ export default {
logScanDebug(...args) {
console.log('[scan-login]', ...args)
},
// 注册/注销通用全局扫码接收(捕获与最小长度过滤由 src/core/scan.js 统一处理)
registerScanCapture() {
registerScanReceiver({
onScanCode: (code, meta) => {
if (!this.isPageActive()) {
return
}
if (this.loginMode !== 'account' && this.loginMode !== 'scan') {
return
}
this.handleScanBadgeLogin(code, meta)
},
onScanDebug: (...args) => this.logScanDebug(...args),
})
},
unregisterScanCapture() {
unregisterScanReceiver()
},
// 窗口级软键盘模式设为 ALWAYS_HIDDEN:input 聚焦也不会自动弹软键盘。
// 真机上不要用 uni.hideKeyboard()——它会断开输入框的按键连接,
// 导致“扫一次后就不再接收输入”;用 Android 窗口软键盘模式彻底压制。
@ -605,6 +737,10 @@ export default {
if (this.loginMode !== 'account' && this.loginMode !== 'scan') {
return
}
// 账号/密码输入框聚焦时不参与扫码捕获
if (this.focusedField === 'username' || this.focusedField === 'password') {
return
}
const keyCode = Number((event && event.keyCode) || 0)
// 跟踪 Shift 修饰键(Android KEYCODE_SHIFT_LEFT=59 / SHIFT_RIGHT=60)
@ -681,8 +817,7 @@ export default {
},
// 离开页面前释放全局键盘/扫码监听,确保下一页面能重新“切换”为唯一监听者
releaseScanListenersBeforeLeave() {
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.unregisterScanCapture()
this.clearScanFocusResumeTimer()
this.clearKeyboardSuppressTimers()
this.clearHiddenRefocusTimer()
@ -719,6 +854,13 @@ export default {
return
}
// 少于最小长度的码直接丢弃(与全局扫码模块一致)
if (code.length < 5) {
this.logScanDebug('hidden-code-dropped', { reason: 'too-short', code, length: code.length })
this.scanHiddenValue = ''
return
}
this.logScanDebug('hidden-input-captured', {
trigger,
code,
@ -892,6 +1034,17 @@ export default {
return
}
// 账号/密码输入框聚焦时不参与扫码捕获,避免手动输入被记录/缓冲
if (this.focusedField === 'username' || this.focusedField === 'password') {
if (this.scanGlobalKeyBuffer) {
this.scanGlobalKeyBuffer = ''
this.scanGlobalKeyStartedAt = 0
this.scanGlobalKeyLastAt = 0
this.clearGlobalKeyTimer()
}
return
}
const key = event?.key || ''
const isPrintable = key.length === 1
const isEnter = key === 'Enter'
@ -1001,6 +1154,8 @@ export default {
return
}
this.focusedField = field
// 输入框聚焦时暂停全局扫码捕获,避免手动输入被记录/缓冲
setScanPaused(true)
this.clearScanFocusResumeTimer()
this.clearHiddenRefocusTimer()
this.scanInputFocus = false
@ -1012,6 +1167,8 @@ export default {
return
}
this.focusedField = ''
// 输入框失焦后恢复全局扫码捕获
setScanPaused(false)
this.scheduleScanInputFocus(220)
},
buildMiniProgramUrlByCode(code) {
@ -1606,7 +1763,8 @@ export default {
<script module="remInject" lang="renderjs">
export default {
mounted() {
const REM_SCALE = 0.45 // 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小)
// 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小);0.45 平板基准偏大,全站统一 0.28
const REM_SCALE = 0.28
const setFontSize = () => {
const docEl = document.documentElement
const width = docEl.clientWidth || window.innerWidth || 1920
@ -1629,6 +1787,108 @@ export default {
</script>
<style>
.update-mask {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.55);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.update-dialog {
width: 15.36rem;
max-width: 90%;
background-color: #ffffff;
border-radius: 0.307rem;
padding: 0.819rem;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
}
.update-dialog__head {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.512rem;
}
.update-dialog__title {
font-size: 0.768rem;
font-weight: 600;
color: #333;
}
.update-dialog__close {
font-size: 1.024rem;
color: #999;
line-height: 1;
padding: 0 0.205rem;
}
.update-dialog__desc {
font-size: 0.563rem;
color: #666;
text-align: center;
margin-bottom: 0.512rem;
}
.update-progress-track {
width: 100%;
height: 0.307rem;
background-color: #eef1f6;
border-radius: 0.154rem;
overflow: hidden;
margin-bottom: 0.256rem;
}
.update-progress-fill {
height: 100%;
background-color: #2f7dff;
border-radius: 0.154rem;
transition: width 0.2s ease;
}
.update-progress-text {
font-size: 0.512rem;
color: #888;
margin-bottom: 0.256rem;
}
.update-dialog__actions {
width: 100%;
display: flex;
justify-content: center;
gap: 0.512rem;
margin-top: 0.256rem;
}
.update-dialog__btn {
width: 5.5rem;
margin: 0;
font-size: 0.563rem;
}
.update-dialog__btn--skip {
background-color: #f2f4f8;
color: #666;
}
.update-dialog__btn--skip::after {
border: 0.026rem solid #dcdfe6;
}
.update-dialog__btn--disabled {
opacity: 0.45;
}
.page {
min-height: 100vh;
min-width: 19.2rem;

View File

@ -3153,7 +3153,8 @@ export default {
<script module="remInject" lang="renderjs">
export default {
mounted() {
const REM_SCALE = 0.45 // 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小)
// 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小);0.45 平板基准偏大,全站统一 0.28
const REM_SCALE = 0.28
const setFontSize = () => {
const docEl = document.documentElement
const width = docEl.clientWidth || window.innerWidth || 1920

File diff suppressed because it is too large Load Diff

View File

@ -33,7 +33,8 @@ export default {
<script module="remInject" lang="renderjs">
export default {
mounted() {
const REM_SCALE = 0.45 // 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小)
// 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小);0.45 平板基准偏大,全站统一 0.28
const REM_SCALE = 0.28
const setFontSize = () => {
const docEl = document.documentElement
const width = docEl.clientWidth || window.innerWidth || 1920

View File

@ -33,7 +33,8 @@ export default {
<script module="remInject" lang="renderjs">
export default {
mounted() {
const REM_SCALE = 0.45 // 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小)
// 整体缩放系数:<1 缩小,>1 放大(布局偏大就调小);0.45 平板基准偏大,全站统一 0.28
const REM_SCALE = 0.28
const setFontSize = () => {
const docEl = document.documentElement
const width = docEl.clientWidth || window.innerWidth || 1920

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,12 @@
import { defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import { readFileSync } from 'fs'
import { fileURLToPath } from 'url'
import { dirname, resolve } from 'path'
const rootDir = dirname(fileURLToPath(import.meta.url))
const pkg = JSON.parse(readFileSync(resolve(rootDir, 'package.json'), 'utf-8'))
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
@ -7,10 +14,12 @@ export default defineConfig(({ mode }) => {
return {
plugins: [uni()],
base: isElectron ? './' : '/',
// history 模式路由,Electron 生产改由本地 HTTP 服务加载,统一绝对 base
base: '/',
define: {
__APP_BUILD_TARGET__: JSON.stringify(env.VITE_BUILD_TARGET || 'web'),
__APP_IS_ELECTRON__: JSON.stringify(isElectron),
__APP_VERSION__: JSON.stringify(pkg.version),
},
}
})