23 Commits
Author SHA1 Message Date
ouyangxq 10d9896b6b Merge remote-tracking branch 'origin/release/test' into release/test 2026-11-05 16:30:50 +08:00
ouyangxq 1b66aeb4aa fix: display dispatch review times in eastern and pacific zones 2026-11-05 16:30:49 +08:00
liuyihe 30f370dd94 Merge branch 'release/test' of http://8.163.30.128:10082/html/pda-overseas-uniapp into release/test 2026-11-05 16:03:24 +08:00
liuyihe 3cc77c98b5 优化 2026-11-05 16:03:22 +08:00
ouyangxq 2b6f512daa Merge branch 'release/test' of http://git.buggoglobal.com/html/pda-overseas-uniapp into release/test 2026-11-05 14:53:59 +08:00
ouyangxq cc280338f1 优化 2026-11-05 14:53:57 +08:00
liuyihe 48602becd1 优化 2026-11-05 11:56:04 +08:00
liuyihe c1706685f5 Merge branch 'release/test' of http://8.163.30.128:10082/html/pda-overseas-uniapp into release/test 2026-11-04 19:27:36 +08:00
liuyihe a584fbfb91 优化 2026-11-04 19:27:34 +08:00
ouyangxq 173bbe2d02 优化 2026-11-04 18:08:34 +08:00
ouyangxq 8199234bd7 保留待确认箱后的排队扫码并阻止提前结束收货 2026-11-04 14:47:41 +08:00
liuyihe a42ecf4a59 Merge branch 'release/test' of http://8.163.30.128:10082/html/pda-overseas-uniapp into release/test 2026-11-04 14:39:30 +08:00
liuyihe b298a4b69d 优化 2026-11-04 14:39:28 +08:00
ouyangxq ed39421cdf 修复海外收货连续扫码步骤并提示本票预留托盘 2026-11-04 14:11:29 +08:00
liuyihe 55cdca5444 优化 2026-11-04 10:39:27 +08:00
ouyangxq 09ada7a441 优化 2026-11-03 17:15:11 +08:00
liuyihe bab96743d7 优化 2026-11-03 11:44:04 +08:00
liuyihe 8857faf457 Merge branch 'release/test' of http://8.163.30.128:10082/html/pda-overseas-uniapp into release/test 2026-11-02 17:16:29 +08:00
liuyihe 436393d4ea 优化 2026-11-02 17:16:15 +08:00
ouyangxq 2fc2956e6d Merge branch 'release/test' of http://git.buggoglobal.com/html/pda-overseas-uniapp into release/test 2026-11-02 17:10:11 +08:00
ouyangxq 1c18631813 优化 2026-11-02 17:03:38 +08:00
liuyihe 63407d176f Merge branch 'release/test' of http://8.163.30.128:10082/html/pda-overseas-uniapp into release/test 2026-10-30 17:59:59 +08:00
liuyihe f814453f40 优化 2026-10-30 17:59:57 +08:00
32 changed files with 925 additions and 141 deletions
+10 -9
View File
@@ -10,8 +10,8 @@
## 项目定位
- “柏悦物流海外版”面向海外仓现场人员,uni-app Vue 3 独立安装/构建/发布,不依赖 `apps/pda-uniapp/` 或仓库外 `pda-shared`。
- 业务/任务完成见下表;派送/客户回访归 Admin/Client,国内集装箱拣货/装柜归国内 PDA。
- “柏悦物流海外版”:海外仓现场 uni-app Vue 3 独立应用,不依赖国内 PDA 或仓外 `pda-shared`。
- 派送/客户回访归 Admin/Client,国内集装箱装柜归国内 PDA;其他作业见下表。
## 服务与发布边界
@@ -24,11 +24,11 @@
- Android启动仅在 `APP-PLUS` 调 `src/utils/app-update.js`,以独立 `VITE_PDA_UPDATE_URL` 查HTTPS APK/WGT;强更禁跳过,WGT安装即重启。更新服务/标识/签名/版本序列不得与国内 PDA 混用。
- 源码根 `src/`;扫码广播 Action=`android.intent.action.SCANRESULT`,Extra=`value`。
- 均接真实PDA API;入仓账号锁柜、逐码核平;退货号/SKU候选进入,按本包实收生成退货箱/计费批次。换标含收货/执行/复核;盘点页面/API保留、工作台隐藏。
- 退货号/SKU候选进入,按本包实收生成退货箱/计费批次;其他作业范围见下表及对应接口边界。
## 页面与能力快速索引
路径相对应用根;[业务索引](docs/business-index.md)存API/字段/状态/恢复。应用根 `rg -n -F '任务词或文件名' docs/business-index.md`;涉及业务行为变更时必须核对对应细则及最近指引,定位不全文读。
路径相对应用根;[业务索引](docs/business-index.md)存 API/字段/状态/恢复;涉及业务行为变更时必须核对对应细则,只读命中段,纯展示不读。
| 目标 | 首个入口 |
|---|---|
@@ -36,10 +36,11 @@
| AppID、平台图标与打包资源 | `src/manifest.json`、`static/app-icons/` |
| Android APK/WGT 在线更新 | `src/App.vue`、`src/utils/app-update.js`、`.env.example` |
| 登录、刷新与会话 | `src/pages/login/login.vue`、`src/api/auth.js`、`src/stores/session.js` |
| 海外仓工作台与作业入口 | `src/pages/home/home.vue`;首页直接进入各作业,页面刷新后返回首页 |
| 海外仓工作台与待办统计 | `src/pages/home/home.vue`、`src/api/workbench.js` |
| 中英西语言设置 | `src/i18n/index.js`、`src/i18n/locales/`、`src/pages/profile/profile.vue` |
| 柜号签收、照片与入仓真实作业 | `src/pages/operation/operation.vue`、`src/components/ReceivingSessionSummary.vue`、`src/api/inbound.js` |
| 柜号签收、私人地址收货与照片 | `src/pages/operation/operation.vue`、`src/components/ReceivingSessionSummary.vue`、`src/api/inbound.js` |
| 退货入库签收与合箱 | `src/pages/return-receipt/return-receipt.vue`、`src/pages/return-packing/return-packing.vue`、`src/api/return-receipt.js` |
| 派送异常回仓签收 | `src/pages/return-receipt/return-receipt.vue` → `src/components/ExceptionReturnWork.vue`、`src/api/exception-returns.js` |
| 退货箱内清点 | `src/pages/return-counting/return-counting.vue`、`src/api/return-counting.js` |
| 仓储转运测量、打托与标签 | `src/pages/warehouse-transfer/warehouse-transfer.vue`、`src/api/warehouse-transfers.js` |
| 托盘管理真实作业 | `src/pages/pallet/pallet.vue`、`src/api/pallet.js` |
@@ -86,10 +87,10 @@
## 质量门禁
- 已发车详情按需挂载 `src/components/DispatchHandoverStatus.vue`,经 `src/api/trip-handover.js` 读当前派送资源/最近交接;进入/刷新各一次GET,列表不逐行请求。只读;后台确认交接,已完成派送留完成时资源。回归 `tests/trip-handover.test.mjs`。
- 发车后 `src/components/DispatchHandoverStatus.vue` 经 `src/api/trip-handover.js` 只读资源/交接;进入和刷新各一 GET,列表不逐行请求。交接由后台确认,完成后保留当时资源;回归 `tests/trip-handover.test.mjs`。
- 验证按 `../../docs/AI工程执行与协作约束.md`;文案看差异,小逻辑定向测试,不默认全量/构建/真机验收。`npm test` 为全量入口。
- 专项用 `node --test`:转运测量/打托/照片/标签行为变更选 `tests/warehouse-transfer-api.test.mjs`;退货签收/合箱行为变更选对应 `tests/return-receipt-api.test.mjs` / `tests/return-packing-api.test.mjs`;项目结构/工作台入口变化才加 `tests/project-contract.test.mjs` / `tests/workbench-availability.test.mjs`。离线不替代真实API、真机扫码/绑定/打印。
- 分层验证见 `../../docs/AI工程执行与协作约束.md`;`npm test` 为全量,不默认跑。
- 按行为用 `node --test`:转运选 `tests/warehouse-transfer-api.test.mjs`,退货签收/合箱选 `tests/return-receipt-api.test.mjs` / `tests/return-packing-api.test.mjs`;结构/工作台入口变更才加 `tests/project-contract.test.mjs` / `tests/workbench-availability.test.mjs`。离线不替代真实 API/扫码/绑定/打印。
- H5编译链 `vue-i18n` 固定 `9.1.9`,禁范围版本/单独升级;依赖变更同步 `package.json`、`package-lock.json`、现有 `pnpm-lock.yaml`,至少跑H5编译。
- 产品为海外PDA App;`npm run build:h5` 仅浏览器调试/模板门禁,App资源用 `npm run build:app`。APK/IPA须在HBuilderX/正式原生打包环境以独立AppID/签名验证,资源编译非APK真机验收。
- 改 `src/manifest.json` 图标映射或 `static/app-icons/` 跑 `node --test tests/app-icons.test.mjs`;禁缺声明尺寸、同一错尺寸占位、复制国内AppID/签名。
+2
View File
@@ -54,6 +54,8 @@ npm run build:app
Android App 启动后会读取 `VITE_PDA_UPDATE_URL` 并检查海外 PDA 的独立更新通道,员工也可在“个人中心 → 检查更新”手动触发;H5 仅展示 App 操作提示,不执行更新。更新服务接收 `appid`、`platform`、`appVersion`、`appVersionCode`、`wgtVersion` 查询参数,无更新返回 `{ "update": false }`,有更新返回:
HBuilderX 真机调试及标准基座使用当前工程 `src/manifest.json` 中的 AppID、版本名和版本码模拟更新检查,避免把 HBuilderX 基座版本作为业务版本上报;正式 APK 仍使用实际安装包版本码及独立的 WGT 资源版本。调试检查同样只读取后台已发布版本,上传草稿不会触发更新;调试基座不能代替正式 APK 的覆盖安装与签名验收。
```json
{
"update": true,
+2 -2
View File
@@ -25,7 +25,7 @@
| 商品移库真实作业 | `src/pages/move/move.vue`、`src/api/warehouse-operations.js`、`src/stores/warehouse-work.js` | 扫描来源托盘与目标库位执行同仓移库;冲突后重新读取服务端事实 |
| 换标真实作业 | `src/pages/relabel/relabel.vue`、`src/api/relabel.js` | 同一页面按操作参数承载换标收货、执行与复核;执行页按当前单明细切换 SKU/箱唛 Tab,组合明细同时显示两类需求。SKU 逐条扫码旧新SKU并携带审批件数,箱唛扫码仓库唛头/新FBA箱唛;组合单按同箱保留两个Tab的核对输入,全部核对后只提交一次箱事实。认领同步处理中;支持拍照、异常/返工和幂等恢复 |
| 现场查询真实作业 | `src/pages/query/query.vue`、`src/api/warehouse-operations.js` | 同一页面按操作参数承载库存、库位与托盘查询,只展示稳定业务标识 |
| 排车拣货与发车/理货审核 | `src/pages/dispatch/dispatch.vue`、`src/api/fulfillment.js`、`src/stores/fulfillment.js` | 普通进入展示任务列表和“上次作业”,不因本地草稿自动打开详情;明确跳转 `?resume=1` 才恢复排车。默认任务列表含待理货排车,详情展示服务端车辆/司机快照、计划发车及预计送达时间、当前有效FBA收货确认、调度审核状态/意见和货物;时间明确标注北京时间。预约或审核依据失效时 `APPROVAL_BLOCKED` 禁止批准但保留驳回。仅 `actions.LOADING_REVIEW.allowed=true` 时可调用 `POST /api/pda/v1/last-leg/dispatches/{dispatchNo}/loading-review`,提交原 `recordVersion/idempotencyKey/decision/reason`;驳回原因必填,任一级拒绝统一回客服处理(车辆信息),重新提交后再次逐级审核。PDA 不执行调度审核;理货通过并重读资格后才允许按实物托盘码或来源箱唛真实拣货,服务端 `actions.PICK/LOADING_COMPLETE` 分别决定真实拣货和装车完成资格;按已扫托数、箱数整车一次确认装车,不逐托填重量、体积或托位,资料未齐进入 `AFTER_LOADING`、已齐直接进入 `DELIVERING`;详情采用“拣货作业/装车拍照”两个 Tab,打开任务默认拣货;切换保留拣货草稿与照片状态,拍照页不响应拣货扫码,同单照片保存刷新保留当前 Tab。装车中即可在拍照 Tab 通过 `src/components/DispatchLoadingDocuments.vue` 上传五类整车照片(司机驾驶证、车牌照片、装车完成、封车照片、BOL司机签字,每类1至5张),照片齐全且确认装车完成后由服务端在最后一项完成的事务自动生成派送并发车;不额外安排派送或确认发车。公网前缀 `/api/pda/v1/last-leg/dispatches/**`。回归 `tests/dispatch-workflow.test.mjs tests/fulfillment-workflows.test.mjs` |
| 排车拣货与发车/理货审核 | `src/pages/dispatch/dispatch.vue`、`src/api/fulfillment.js`、`src/stores/fulfillment.js` | 普通进入展示任务列表和“上次作业”,不因本地草稿自动打开详情;明确跳转 `?resume=1` 才恢复排车。默认任务列表含待理货排车,详情展示服务端车辆/司机快照、计划发车及预计送达时间、当前有效FBA收货确认、调度审核状态/意见和货物;时间同时展示美东(America/New_York)与美西(America/Los_Angeles),按地区时区处理夏令时;只换算带时区的真实时间点,缺失时不补造时间。预约或审核依据失效时 `APPROVAL_BLOCKED` 禁止批准但保留驳回。仅 `actions.LOADING_REVIEW.allowed=true` 时可调用 `POST /api/pda/v1/last-leg/dispatches/{dispatchNo}/loading-review`,提交原 `recordVersion/idempotencyKey/decision/reason`;驳回原因必填,任一级拒绝统一回客服处理(车辆信息),重新提交后再次逐级审核。PDA 不执行调度审核;理货通过并重读资格后才允许按实物托盘码或来源箱唛真实拣货,服务端 `actions.PICK/LOADING_COMPLETE` 分别决定真实拣货和装车完成资格;按已扫托数、箱数整车一次确认装车,不逐托填重量、体积或托位,资料未齐进入 `AFTER_LOADING`、已齐直接进入 `DELIVERING`;详情采用“拣货作业/装车拍照”两个 Tab,打开任务默认拣货;切换保留拣货草稿与照片状态,拍照页不响应拣货扫码,同单照片保存刷新保留当前 Tab。装车中即可在拍照 Tab 通过 `src/components/DispatchLoadingDocuments.vue` 上传五类整车照片(司机驾驶证、车牌照片、装车完成、封车照片、BOL司机签字,每类1至5张),照片齐全且确认装车完成后由服务端在最后一项完成的事务自动生成派送并发车;不额外安排派送或确认发车。公网前缀 `/api/pda/v1/last-leg/dispatches/**`。回归 `tests/dispatch-workflow.test.mjs tests/fulfillment-workflows.test.mjs` |
| 装车确认、自动派送与证照提醒 | `src/pages/dispatch/dispatch.vue`、`src/api/fulfillment.js` 的 `completeDispatchLoading` | 一单一趟,使用 `dispatchNo`、公开 `recordVersion`(0 合法)及本次 `idempotencyKey`。只在请求中锁定,结束即释放;保留表单,不持久化或重放失败命令,下次点击按当前输入和版本生成新键。结果不明或 409 先刷新权威任务,不以超时推断未执行或成功。结果核对单号、动作、请求键和版本;理货审核通过须 `stage=LOADING`,驳回须 `stage=BEFORE_LOADING`;`LOADING_COMPLETE` 返回 `stage=AFTER_LOADING|DELIVERING`、Loaded 结果,提交版本、manifestHash 和幂等键,不逐托填测量。成功后重读任务,版本不得早于已确认结果;重读失败只刷新,不自动重复 POST。司机证照、资源及各客户派送资格由服务端校验;正式流程见工作区 `docs/海外仓业务/排车列表统一作业改造契约.md`,不使用独立车次发车请求 |
| 普通/一件代发出库 | `src/pages/outbound/outbound.vue`、`src/api/fulfillment.js`、`src/stores/fulfillment.js` | 首次进入清空扫描框并展示任务列表和“上次作业”标记,不自动恢复旧详情;详情提供独立返回列表入口。逐箱扫码、DP 托盘整托拣取及幂等完成保持不变;扫描排车业务号显式跳转排车 `?resume=1`。公网前缀 `/api/pda/v1/last-leg/outbound-tasks/**`;派送由 Admin/Client 承载 |
| 扫码设备与诊断 | `src/utils/scan-broadcast.js`、`src/pages/scanner-test/scanner-test.vue` | `src/components/ScanTargetInput.vue`、声音反馈工具;广播 Action/Extra 见本文件服务边界 |
@@ -62,6 +62,6 @@
- 柜号签收入仓调用 Lastleg `/api/pda/v1/last-leg/receiving-containers/**`;退货签收与合箱分别调用 `/api/pda/v1/last-leg/return-receipts/**`、`/api/pda/v1/last-leg/return-inventory/**`,具体入口见上表。浏览器或设备请求必须经统一 `gateway` 的显式 PDA 路由,不得直连 Lastleg。
- 海外业务 Token、PDA 权限和可信身份最终由 Gateway 与服务端校验;前端不得用工作台 `available`、本地客户 ID 或仓库 ID 代替授权和资源归属校验。
- 排车和出库入口只调用专用 PDA 接口;客户与绑定海外仓由 Token、Gateway 和服务端解析,前端不提交 `customerId`、`warehouseId`,也不展示内部数据库 ID 作为业务编号。动作资格、版本和失败处理见本文件排车条目,装车中可同步上传五类照片,每类1至5张,装车确认与资料齐全两项均完成后服务端自动生成派送并发车,装完但资料未齐时留在装车后;照片API为 `/pda/v1/last-leg/dispatches/{dispatchNo}/loading-documents`,前端不补派送费用。完成成功后不得重复提交;PDA 不直接创建派送单,平台与客户的读取范围遵循现行契约。
- 生产仓租功能尚未配套发布,当前 main 的排车拣货、普通出库、整托出库和废弃确认直接调用既有库存命令,不请求 `/storage-rent/preparations`。保留原始货源参数、箱数、版本和 `idempotencyKey`;实际库存接口的业务失败与网络错误照常上报,不吞掉 404、不自动重试或伪造成功。未来启用仓租须以后端接口、数据库及资金链路配套上线为前提。定向回归为 `tests/fulfillment-stock-commands.test.mjs`,覆盖四类命令单次提交、参数保留、版本/防重校验与失败传播;离线测试不代替生产实货验收。
- 排车拣货在提交库存扣减前调用 `/storage-rent/preparations` 完成仓租预校验和资金预占,预占回执未就绪或失败时不提交拣货;成功后仍只提交原排车库存命令,保留货源参数、箱数、版本和 `idempotencyKey`。预校验失败会释放未消费预占并保留错误诊断,不自动重放拣货。普通出库、整托出库和废弃确认沿各自现有流程;定向回归为 `tests/fulfillment-stock-commands.test.mjs`,覆盖排车仓租预校验、库存命令参数和失败传播。
- 废弃出库展示客户废弃备注。无关联箱唛库存扫描本单托盘后扫描现场箱唛,自动去重计数;多SKU先选择本次扫描货物,不手填实际数。每条 lines.scannedCartonMarks 与 actualPackages 一并提交,失败留箱唛/照片供刷新重试;后台保存实际扫描清单并回显废弃详情。有箱唛关联任务仍核对本单所选箱唛。
+7
View File
@@ -0,0 +1,7 @@
import { overseasRequest, overseasUpload } from './overseas.js'
const base = '/pda/v1/last-leg/return-receipts/exceptions'
const path = (number) => `${base}/${encodeURIComponent(number)}`
export const listExceptionReturns = () => overseasRequest('GET', base)
export const startExceptionReturn = (number) => overseasRequest('POST', `${path(number)}/start`, {})
export const uploadExceptionReturnEvidence = (number, filePath) => overseasUpload(`${path(number)}/evidence`, filePath)
export const receiveExceptionReturn = (number, body) => overseasRequest('POST', `${path(number)}/receive`, body)
+16 -4
View File
@@ -97,7 +97,7 @@ function dispatchWrite(path, request) {
requireDispatchVersion(request?.recordVersion)
return overseasRequest('POST', path, request)
}
// 生产仓租接口尚未配套发布,直接提交既有库存命令,仍保留原请求的防重标识。
// 库存命令与仓租预校验共用本次请求的防重标识。
function requireStockCommandIdentity(request) {
if (!request?.idempotencyKey) throw new Error('出库请求标识缺失,请重新进入任务')
}
@@ -105,8 +105,19 @@ function requireStockCommandIdentity(request) {
export async function pickDispatchItem(dispatchNo, dispatchItemId, request) {
requireDispatchVersion(request?.recordVersion)
requireStockCommandIdentity(request)
await prepareStockRent({
mode: 'DISPATCH',
businessNo: dispatchNo,
itemId: dispatchItemId,
positionId: request.positionId,
packages: request.packages,
cartonMark: request.cartonMark || null,
idempotencyKey: request.idempotencyKey,
productQuantity: request.productQuantity || 0
})
return dispatchWrite(`${DISPATCH_BASE}/${encoded(dispatchNo)}/items/${encoded(dispatchItemId)}/pick`, request)
}
export function completeDispatchLoading(dispatchNo, request) {
return dispatchWrite(`${DISPATCH_BASE}/${encoded(dispatchNo)}/loading-complete`, request)
}
@@ -175,6 +186,7 @@ export function normalizeCargoDiscardTask(value) {
plannedPackages: count(sku?.plannedPackages),
actualPackages: sku?.actualPackages == null ? null : count(sku.actualPackages),
actualQuantityEditable: sku?.actualQuantityEditable === true,
allowedCartonMarks: asList(sku?.allowedCartonMarks).map(String),
status: String(sku?.status || 'PENDING')
}))
}
@@ -192,12 +204,12 @@ export async function confirmCargoDiscard(discardNo, palletNo, lines, photoFileI
const body = { lines, photoFileIds, scannedCartonMarks, confirmAllCartons, idempotencyKey: request.idempotencyKey }
requireStockCommandIdentity(request)
// 出库前按同一份货物、照片和幂等键校验仓租,资金就绪后才提交库存扣减。
await prepareDiscardRent({ mode: 'DISCARD', businessNo: discardNo, palletNo, ...body })
await prepareStockRent({ mode: 'DISCARD', businessNo: discardNo, palletNo, ...body })
return normalizeCargoDiscardTask(await overseasRequest('POST', `${CARGO_DISCARD_BASE}/${encoded(discardNo)}/pallets/${encoded(palletNo)}/confirm`, body))
}
/** 本次点击内只查询资金回执,不缓存或自动重放失败的出库命令。 */
async function prepareDiscardRent(body) {
async function prepareStockRent(body) {
const base = '/pda/v1/last-leg/storage-rent/preparations'
let preparationId
try {
@@ -215,7 +227,7 @@ async function prepareDiscardRent(body) {
// 尚未发送出库命令时释放已知的未使用预占,释放失败保留原错误诊断。
if (preparationId) {
try { await overseasRequest('DELETE', `${base}/${encoded(preparationId)}`) }
catch (releaseError) { console.error('[Overseas PDA discard] rent preparation release failed', { code: releaseError?.code, requestId: releaseError?.requestId, traceId: releaseError?.traceId }) }
catch (releaseError) { console.error('[Overseas PDA stock] rent preparation release failed', { code: releaseError?.code, requestId: releaseError?.requestId, traceId: releaseError?.traceId }) }
}
throw error
}
+1
View File
@@ -118,6 +118,7 @@ export function toReceivingError(error, fallback = '海外仓作业失败') {
const receivingMessages = {
'Carton mark must contain a non-empty inbound code prefix': '请扫描箱码或国内DP码',
'Pallet code is not part of the current FBA destination group': '托盘不属于当前目的仓,请重扫',
'Pallet code is not reserved for this inbound code': '该托盘未预留给当前入仓码,请扫描本票已预留托盘',
'Reserved pallet binding is incomplete': '预留托盘资料不完整,请联系管理员检查入仓计划',
'Reserved pallet customer binding is invalid': '预留托盘与当前客户不匹配,请联系管理员检查入仓计划',
'Scanned pallet does not match the reserved inbound plan resource': '扫描托盘与入仓计划预留资源不一致,请扫描已预留的托盘',
@@ -5,8 +5,6 @@
<text class="heading-progress">{{ busy ? '同步中' : snapshot ? `${completedCategories}/5 类已保存` : '待同步' }}</text>
<button class="heading-refresh" :disabled="busy" @tap="refresh">刷新</button>
</view>
<text class="section-hint">每类至少 1 张、最多 5 张,上传后自动保存,可逐张更换。</text>
<text class="section-hint">司机驾驶证、车牌照片在理货审核通过后自动带入,可补拍或更换;PDF 驾驶证可点击查看。</text>
<text v-if="needsRefresh" class="section-hint">保存状态尚未核实,请先刷新资料后再上传。</text>
<view v-if="error" class="error" role="alert"><text>{{ error.message }}</text><text v-if="error.requestId">requestId:{{ error.requestId }}</text><text v-if="error.traceId">traceId:{{ error.traceId }}</text></view>
<view class="photo-list">
+82
View File
@@ -0,0 +1,82 @@
<template>
<scroll-view class="work-scroll" scroll-y><view class="portal-content work-content">
<view v-if="error" class="work-card"><text role="alert">{{ error }}</text><button :disabled="busy" @tap="refresh">刷新任务</button></view>
<template v-if="!current">
<view class="row-head"><button class="refresh-button" :disabled="busy" @tap="refresh">刷新</button></view>
<text v-if="!busy && !tasks.length" class="empty-copy">当前仓没有待验收异常退货任务</text>
<view v-for="task in tasks" :key="task.exceptionNo" class="work-card">
<text class="business-code">{{ task.exceptionNo }}</text>
<text class="meta-line">车牌号:{{ task.vehiclePlate || '未登记' }}</text>
<text class="meta-line">客户:{{ task.customerName || '—' }} · 待收 {{ task.packageCount - task.receivedPackages }} 箱</text>
<button class="primary-button" :disabled="busy" @tap="start(task)">开始作业</button>
</view>
</template>
<template v-else>
<view class="work-card"><text class="business-code">{{ current.order.exceptionNo }}</text><text class="meta-line">车牌号:{{ selectedTask.vehiclePlate || '未登记' }}</text><button :disabled="busy" @tap="leave">返回任务列表</button></view>
<view v-for="(item,index) in current.returnSources" :key="`${item.outboundPalletItemId}:${item.inventoryPositionId}:${item.returnCartonId}`" class="work-card">
<text class="card-title">{{ item.skuCode || '货物' }}</text><text class="meta-line">原托盘 / 箱唛:{{ item.cartonMark || item.palletNo || '—' }}</text>
<text class="meta-line">剩余可收 {{ item.maxReturnPackages }} 箱</text>
<input v-model="quantities[index]" type="number" placeholder="本批实收箱数" :disabled="busy" />
</view>
<view class="work-card"><text class="card-title">上架位置</text><input v-model="palletCode" placeholder="目标托盘号" :disabled="busy" /><input v-model="locationCode" placeholder="目标库位号" :disabled="busy" /></view>
<view class="work-card"><text class="card-title">实收照片</text><text v-for="photo in photos" :key="photo.fileId" class="meta-line">{{ photo.fileName }}</text><button :disabled="busy || photos.length >= 20" @tap="photo">拍照 / 选择照片</button></view>
<button class="primary-button" :disabled="busy || !ready" @tap="receive">{{ busy ? '处理中…' : '确认本批入库' }}</button>
</template>
<text v-if="message" class="meta-line" role="status">{{ message }}</text>
</view></scroll-view>
</template>
<script>
import { listExceptionReturns, startExceptionReturn, uploadExceptionReturnEvidence, receiveExceptionReturn } from '@/api/exception-returns.js'
export default {
emits: ['working-change'],
watch: {
current(value) { this.$emit('working-change', Boolean(value)) },
},
data() { return { tasks: [], current: null, selectedTask: null, quantities: [], palletCode: '', locationCode: '', photos: [], busy: false, error: '', message: '', revision: 0 } },
computed: {
ready() { return this.current && this.palletCode.trim() && this.locationCode.trim() && this.photos.length && this.quantities.some(value => Number(value) > 0) },
},
mounted() { this.refresh() },
beforeUnmount() { this.revision++ },
methods: {
// 页面切换后不再用迟到响应覆盖另一张作业单。
async run(action) { if (this.busy) return; const revision = this.revision; this.busy = true; this.error = ''; try { await action(() => revision === this.revision) } catch (error) { if (revision === this.revision) this.error = error.message || '操作失败,请刷新核对实际进度' } finally { if (revision === this.revision) this.busy = false } },
async refresh() { await this.run(async valid => { const tasks = await listExceptionReturns(); if (valid()) this.tasks = tasks }) },
async start(task) { await this.run(async valid => { const value = await startExceptionReturn(task.exceptionNo); if (valid()) { this.current = value; this.selectedTask = task; this.quantities = []; this.photos = []; this.palletCode = ''; this.locationCode = ''; this.message = '' } }) },
async leave() { if (this.busy) return; this.current = null; this.photos = []; await this.refresh() },
async photo() { await this.run(async valid => { const result = await new Promise((resolve,reject) => uni.chooseImage({ count: 1, sourceType: ['camera','album'], success: resolve, fail: reject })); const uploaded = await uploadExceptionReturnEvidence(this.current.order.exceptionNo,result.tempFilePaths[0]); if (valid()) this.photos.push(uploaded) }) },
async receive() {
if (!this.ready) return
await this.run(async valid => {
const items = this.current.returnSources.flatMap((item,index) => {
const packages = Number(this.quantities[index] || 0)
if (!Number.isSafeInteger(packages) || packages < 0 || packages > item.maxReturnPackages || item.returnCartonId && packages > 1) throw new Error('实收箱数必须为整数且不超过剩余可收数量')
return packages ? [{ outboundPalletItemId: item.outboundPalletItemId, inventoryPositionId: item.inventoryPositionId, returnCartonId: item.returnCartonId, packages }] : []
})
const number = this.current.order.exceptionNo
const result = await receiveExceptionReturn(number,{ expectedVersion: this.current.order.version, idempotencyKey: `exception-return-${Date.now()}-${Math.random().toString(36).slice(2)}`, palletCode: this.palletCode.trim(), locationCode: this.locationCode.trim(), items, evidenceFileIds: this.photos.map(photo => photo.fileId) })
if (!valid()) return
this.quantities = []; this.photos = []; this.message = `本批已入库 ${result.restoredPackages} 箱${result.status === 'COMPLETED' ? ',异常处理完成' : ',还有货物待收'}`
if (result.status === 'COMPLETED') { this.current = null; this.tasks = await listExceptionReturns() }
else this.current = await startExceptionReturn(number)
})
// 结果不明时重新读取权威版本,禁止使用旧快照重复累计数量。
if (this.error && this.current) {
try { this.current = await startExceptionReturn(this.current.order.exceptionNo); this.quantities = [] }
catch (_) { this.current = null; this.tasks = []; }
}
},
},
}
</script>
<style scoped>
.work-scroll { flex: 1; height: 0; min-height: 0; }
.work-content { padding-bottom: calc(24px + env(safe-area-inset-bottom)); }
.row-head { display: flex; justify-content: flex-end; margin-bottom: 12px; }
.refresh-button { margin: 0; padding: 0 16px; border: 1px solid #b8d1f5; border-radius: 8px; color: #135ee8; background: #f8fbff; }
.work-card { margin: 12px 0; padding: 14px; border: 1px solid #dfe7ef; border-radius: 12px; background: #fff; }
.business-code,.meta-line,.card-title { display: block; margin-bottom: 10px; }
.business-code,.card-title { font-weight: 700; }.meta-line { color: #61758b; font-size: 13px; }
input { height: 44px; margin: 8px 0; padding: 0 10px; border: 1px solid #cbd7e4; border-radius: 8px; }
button { margin-top: 10px; font-size: 14px; }.primary-button { color: #fff; background: #1668dc; }.primary-button[disabled] { background: #a2b2c8; }
</style>
-2
View File
@@ -13,7 +13,6 @@
<view class="header-menu-sheet">
<view class="header-menu-content">
<PopupHeader title="功能菜单" @close="closeMenu" />
<button class="header-menu-item" @tap="goHistory"><uni-icons type="list" color="#334155" size="22" /><text>作业记录</text><uni-icons type="right" color="#94a3b8" size="18" /></button>
<button class="header-menu-item" @tap="goProfile"><uni-icons type="person" color="#334155" size="22" /><text>个人中心</text><uni-icons type="right" color="#94a3b8" size="18" /></button>
<button class="header-menu-close" @tap="closeMenu">关闭</button>
</view>
@@ -39,7 +38,6 @@
methods: {
goBack() { navigateBackOr(this.fallbackUrl) },
goProfile() { this.closeMenu(); navigateToUnique('/pages/profile/profile') },
goHistory() { this.closeMenu(); navigateToUnique('/pages/history/history') },
openMenu() { this.$refs.menuPopup.open() },
closeMenu() { if (this.$refs.menuPopup) this.$refs.menuPopup.close() },
handleMenuChange(event) { this.$emit('menu-change', Boolean(event.show)) }
+21 -13
View File
@@ -10,7 +10,7 @@
</view>
<view v-if="!current || activeTab === 'picking'" class="fulfillment-card dispatch-scan-card">
<text class="card-title">{{ current ? '扫码拣货' : '扫码查询排车' }}</text>
<ScanTargetInput name="dispatch" :model-value="scanCode" label="排车单号/实物托盘码/来源箱唛" placeholder="扫描业务单号或实物码" :active="activeTab === 'picking'" @update:modelValue="scanCode = $event" @submit="handleScan" />
<ScanTargetInput name="dispatch" :model-value="scanCode" label="排车单号/实物托盘码/来源箱唛" placeholder="扫托盘码" :active="activeTab === 'picking'" @update:modelValue="scanCode = $event" @submit="handleScan" />
<button class="secondary-button" :disabled="busy || loading || !scanCode" @tap="handleScan(scanCode)">匹配扫描</button>
</view>
<view v-if="loading" class="fulfillment-state"><text>正在加载排车事实…</text></view>
@@ -32,9 +32,7 @@
<DispatchHandoverStatus v-if="departed" :dispatch-no="current.dispatchNo" :record-version="current.recordVersion" />
<view class="fulfillment-card summary-card">
<text class="card-title">任务摘要</text>
<view class="task-head"><text class="business-code">{{ current.dispatchNo }}</text><text class="status-badge">{{ stageLabel(current) }}</text></view>
<text class="task-meta">任务号 {{ current.taskNo || '—' }}</text>
<text v-if="!gate('PICK') && current.stage === 'LOADING'" class="gate-warning">{{ current.actions.PICK?.blockReason || '拣货资格尚未允许,请核对两级审核及当前作业状态' }}</text>
<view class="task-head"><text class="status-badge">{{ stageLabel(current) }}</text></view>
<text class="picking-section-label">拣货进度</text>
<view class="metrics" aria-label="拣货进度"><view><text class="metric-value">{{ plannedPackages }}</text><text>计划箱数</text></view><view><text class="metric-value success">{{ pickedPackages }}</text><text>真实已拣</text></view><view><text class="metric-value warning">{{ remainingPackages }}</text><text>未拣箱数</text></view></view>
</view>
@@ -45,18 +43,17 @@
<view class="review-fact"><text class="review-label">托车公司</text><text>{{ current.resources?.vehicle?.carrierName || '—' }}</text></view>
<view class="review-fact"><text class="review-label">司机</text><text>{{ current.resources?.driver?.name || '—' }}</text></view>
<view class="review-fact"><text class="review-label">电话</text><text>{{ current.resources?.driver?.phone || '—' }}</text></view>
<view class="review-fact"><text class="review-label">计划发车</text><text>{{ reviewTime(current.plannedDepartureAt) }}(北京时间)</text></view>
<view class="review-fact"><text class="review-label">预计送达</text><text>{{ reviewTime(current.estimatedArrivalAt) }}(北京时间)</text></view>
<view v-for="appointment in current.fbaAppointments || []" :key="appointment.destinationKey" class="review-fact"><text class="review-label">{{ appointment.destinationWarehouseCode }}</text><view class="review-appointment"><text>{{ appointment.appointmentNo || '—' }}</text><text>{{ appointment.status === 'SUCCESS' ? '已确认' : appointment.status === 'REGISTERED' ? '已登记' : '未填写' }}:{{ reviewTime(appointment.confirmedAt) }}(北京时间)</text></view></view>
<view class="review-fact"><text class="review-label">计划发车</text><text class="review-time">{{ reviewTime(current.plannedDepartureAt) }}</text></view>
<view class="review-fact"><text class="review-label">预计送达</text><text class="review-time">{{ reviewTime(current.estimatedArrivalAt) }}</text></view>
<view v-for="appointment in current.fbaAppointments || []" :key="appointment.destinationKey" class="review-fact"><text class="review-label">{{ appointment.destinationWarehouseCode }}</text><view class="review-appointment"><text>{{ appointment.appointmentNo || '—' }}</text><text>{{ appointment.status === 'SUCCESS' ? '已确认' : appointment.status === 'REGISTERED' ? '已登记' : '未填写' }}</text><text class="review-time">{{ reviewTime(appointment.confirmedAt) }}</text></view></view>
<view class="review-fact"><text class="review-label">驾驶证号</text><text>{{ current.resources?.driver?.evidence?.licenseNo || '—' }}</text></view>
<view class="review-fact"><text class="review-label">有效期</text><text>{{ current.resources?.driver?.evidence?.licenseExpiresOn || '—' }}</text></view>
<view class="review-fact"><text class="review-label">调度审核</text><text>{{ reviewLabel(current.reviews?.dispatchReview) }} · {{ reviewTime(current.reviews?.dispatchReview?.reviewedAt) }}</text></view>
<view class="review-fact"><text class="review-label">调度审核</text><view class="review-appointment"><text>{{ reviewLabel(current.reviews?.dispatchReview) }}</text><text class="review-time">{{ reviewTime(current.reviews?.dispatchReview?.reviewedAt) }}</text></view></view>
<view v-if="current.reviews?.dispatchReview?.reason" class="review-fact"><text class="review-label">调度意见</text><text>{{ current.reviews.dispatchReview.reason }}</text></view>
</view>
<text v-if="rejectionReason" class="gate-warning">已退回客服处理(车辆信息):{{ rejectionReason }}。修改后须重新提交审核。</text>
<template v-if="canReview">
<text v-if="current.actions.LOADING_REVIEW?.blockCode === 'APPROVAL_BLOCKED'" class="gate-warning">{{ current.actions.LOADING_REVIEW.blockReason }}</text>
<text class="task-meta">请核对车辆、司机及下方货物;通过后才能开始真实拣货。驳回将回到客服处理(车辆信息)。</text>
<textarea :value="reviewReason" maxlength="1000" placeholder="审核意见(驳回时必填)" :disabled="busy || loading" @input="updateReviewReason" />
<view class="review-actions"><button :disabled="busy || loading || !reviewReason.trim()" @tap="submitReview('REJECTED')">驳回</button><button class="primary-button" :disabled="busy || loading || current.actions.LOADING_REVIEW?.blockCode === 'APPROVAL_BLOCKED'" @tap="submitReview('APPROVED')">审核通过</button></view>
</template>
@@ -186,7 +183,7 @@ export default {
this.sourceChoices = []; this.choiceCartonCode = ''; this.error = null
},
async submitPick() { if (!this.canPick) return; try { const body = { recordVersion: requireDispatchVersion(this.current.recordVersion), positionId: this.selectedReturnCarton ? null : this.selectedPosition.positionId, packages: this.selectedReturnCarton ? 1 : Number(this.packages), productQuantity: this.selectedReturnCarton?.productQuantity || 0, cartonMark: this.selectedReturnCarton?.cartonMark || null, remark: null }; await this.submitCommand(this.current.dispatchNo, 'PICK', { ...body, dispatchItemId: this.selectedItem.dispatchItemId }) } catch (cause) { this.setError(cause, '拣货未提交') } },
async prepareLoading() { if (!this.canComplete) return; await this.run(async () => { const data = await getDispatchLoading(this.current.dispatchNo); if (data.dispatchNo !== this.current.dispatchNo || data.pickingReconciled !== true || data.loadingComplete?.allowed !== true) throw new Error(data.loadingComplete?.blockReason || '装车前置未满足'); requireDispatchVersion(data.recordVersion); this.loadingPreview = data; this.loadingRows = data.pallets }) },
async prepareLoading() { if (!this.canComplete || this.busy || this.loading) return; await this.run(async () => { const data = await getDispatchLoading(this.current.dispatchNo); if (data.dispatchNo !== this.current.dispatchNo || data.pickingReconciled !== true || data.loadingComplete?.allowed !== true) throw new Error(data.loadingComplete?.blockReason || '装车前置未满足'); requireDispatchVersion(data.recordVersion); this.loadingPreview = data; this.loadingRows = data.pallets }) },
async completeLoading() { if (!this.loadingPreview || this.busy) return; try { if (!this.loadingRows.length || this.loadingRows.some(row => row.deliveryIndex == null || !Number.isInteger(row.deliveryIndex) || row.deliveryIndex < 1)) throw new Error('托盘卸货站尚未匹配,请后台核对'); await this.submitCommand(this.loadingPreview.dispatchNo, 'LOADING_COMPLETE', { recordVersion: requireDispatchVersion(this.loadingPreview.recordVersion), manifestHash: this.loadingPreview.manifestHash, remark: null }) } catch (cause) { this.setError(cause, '装车完成未确认') } },
updateReviewReason(event) { if (this.busy || this.loading) return; this.reviewReason = String(event.detail.value || '') },
async submitReview(decision) {
@@ -228,9 +225,19 @@ export default {
},
async retry() { if (this.current?.dispatchNo) await this.openTask(this.current.dispatchNo); else await this.loadTasks() },
async run(work, loading = false) { if (this.busy || this.loading) return; this.clearScanNotice(); this.error = null; this.successMessage = ''; if (loading) this.loading = true; else this.requestBusy = true; try { await work() } catch (cause) { this.setError(cause, '排车操作失败') } finally { this.loading = false; this.requestBusy = false } },
setError(cause, fallback) { this.clearScanNotice(); this.error = toDispatchError(cause, fallback); playErrorSound() },
setError(cause, fallback) { this.clearScanNotice(); this.error = toDispatchError(cause, fallback); playErrorSound(); if (typeof uni !== 'undefined') uni.showToast?.({ title: this.error.message || fallback, icon: 'none', duration: 3000 }) },
stageLabel(task) { if (task.status === 'CANCELLED') return '已取消'; if (task.stage === 'BEFORE_LOADING') { if (task.actions?.LOADING_REVIEW?.allowed === true) return '待理货审核'; if ([task.reviews?.dispatchReview, task.reviews?.loadingReview].some(review => review?.status === 'REJECTED')) return '已退回客服处理' }; return ({ BEFORE_LOADING: '装车前', LOADING: '装车中', AFTER_LOADING: '装车后', DELIVERING: '派送中', DELIVERED: '派送完成' })[task.stage] || '状态待核实' },
reviewTime(value) { if (!value) return '未填写'; const date = new Date(new Date(value).getTime() + 8 * 60 * 60 * 1000); return Number.isNaN(date.getTime()) ? '时间无效' : date.toISOString().slice(0, 16).replace('T', ' ') },
reviewTime(value) {
if (!value) return '未填写'
const instant = typeof value === 'string' && /(?:Z|[+-]\d{2}:\d{2})$/i.test(value) ? Date.parse(value) : NaN
if (!Number.isFinite(instant)) return '时间无效'
return [['美东', 'America/New_York'], ['美西', 'America/Los_Angeles']].map(([label, timeZone]) => {
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', {
timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
}).formatToParts(instant).map(part => [part.type, part.value]))
return `${label} ${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`
}).join('\n')
},
reviewLabel(review) { return ({ NOT_SUBMITTED: '未提交', PENDING: '待审核', APPROVED: '已通过', REJECTED: '已驳回' })[review?.status] || '待核对' },
routeLabel(item) { return [item.destination?.warehouseCode, item.destination?.warehouseName, item.destination?.address].filter(Boolean).join(' · ') || '目的仓未关联' }, itemProgress(item) { return item.scheduledPackages ? Math.min(100, Math.round(item.pickedPackages / item.scheduledPackages * 100)) : 0 }
}
@@ -274,11 +281,12 @@ export default {
.review-label { flex: 0 0 132rpx; color: #718095; overflow-wrap: anywhere; }
.review-fact > :last-child { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.review-appointment { display: flex; flex-direction: column; gap: 4rpx; }
.review-time { white-space: pre-line; }
.review-actions { display: flex; gap: 20rpx; margin-top: 24rpx; }
.review-actions button { flex: 1; min-width: 0; margin: 0; padding: 0 16rpx; min-height: 88rpx; line-height: 88rpx; font-size: 28rpx; }
.review-actions .primary-button { min-height: 88rpx; line-height: 88rpx; font-size: 28rpx; }
.review-card textarea { box-sizing: border-box; width: 100%; height: 160rpx; min-height: 160rpx; margin-top: 20rpx; padding: 16rpx; border: 1px solid #cbd5e1; border-radius: 8rpx; }
.loading-overlay { position: fixed; inset: 0; background: rgba(15, 23, 42, .46); display: flex; align-items: center; justify-content: center; z-index: 100; padding: 40rpx; box-sizing: border-box; }
.loading-overlay { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background: rgba(15, 23, 42, .46); display: flex; align-items: center; justify-content: center; z-index: 100; padding: 40rpx; box-sizing: border-box; }
.loading-dialog { width: 100%; max-width: 620rpx; max-height: 88vh; overflow-y: auto; box-sizing: border-box; background: #fff; border-radius: 28rpx; padding: 36rpx 32rpx 32rpx; box-shadow: 0 24rpx 80rpx rgba(15, 23, 42, .18); }
.loading-dialog-heading { display: flex; flex-direction: column; gap: 10rpx; }
.loading-dialog-title { color: #142c49; font-size: 36rpx; font-weight: 700; line-height: 1.4; }
+17 -5
View File
@@ -122,7 +122,7 @@
</template>
</view>
<view v-if="lastReceipt" class="success-card">本次已收 {{ lastReceipt.acceptedPackages }} 箱,整柜剩余 {{ current.pendingPackages }} 箱</view>
<view v-if="canFinishOnsite" class="sticky-action-dock"><view class="sticky-action one"><button class="primary-button complete-button" :disabled="busy || activeTarget === 'quantity' || scanQueue.length" @tap="completeContainer">{{ allInboundsReconciled ? '完成整柜入库' : '现场收货结束(标记差异)' }}</button></view></view>
<view v-if="canFinishOnsite" class="sticky-action-dock"><view class="sticky-action one"><button class="primary-button complete-button" :disabled="busy || canSubmitReceipt || activeTarget === 'quantity' || scanQueue.length" @tap="completeContainer">{{ allInboundsReconciled ? '完成整柜入库' : '现场收货结束(标记差异)' }}</button></view></view>
</template>
<template v-else-if="phase === 'completed'">
@@ -191,8 +191,18 @@
photoStateLabel(photo) { if (photo?.status === 'uploading') return '正在上传…'; if (photo?.status === 'error') return photo.errorMessage || (photo.fileId ? '重拍失败,已保留原图' : '上传失败,请重试'); return '' },
startScanner() { this.stopScanner(); this._stopScanner = startScanBroadcast({ onScan: (value) => this.handleHardwareScan(value), onError: (error) => { this.error = error; this.showToast('硬件扫码接收器异常,请检查扫描服务', 'warning') } }) }, stopScanner() { if (typeof this._stopScanner === 'function') this._stopScanner(); this._stopScanner = null },
handleHardwareScan(value) { if (!this._pageActive || this.loading) return; const scan = { value: String(value || '').trim(), target: this.activeTarget }; if (!scan.value) return; if (!this.inboundMode) return this.showToast('该功能缺少海外 PDA 专用接口,扫码未提交', 'warning'); if (this.phase === 'candidates') return this.showToast('请直接点击待卸货集装箱进入详情', 'warning'); if (this.phase !== 'receive') return; if (this.busy || this.activeTarget === 'quantity') { if (this.scanQueue.length >= 100) return this.showToast('扫码队列已满,请先处理当前托盘', 'warning'); this.scanQueue.push(scan); return this.showToast(`已排队 ${this.scanQueue.length} 个扫码`, 'warning') } return this.dispatchHardwareScan(scan) },
dispatchHardwareScan(scan) { if (!this._pageActive || this.loading) return; const palletWorkflowActive = Boolean(this.activeInbound || this.resolvedPallet); const target = palletWorkflowActive ? 'pallet' : scan.target; console.info('[Overseas PDA scan] dispatch', { value: scan.value, target, queuedTarget: scan.target }); if (target === 'pallet') { this.palletInput = scan.value; return this.resolvePallet(scan.value) } this.cartonInput = scan.value; return this.resolveCarton(scan.value) },
drainScanQueue() { if (!this._pageActive || this.loading || this.busy || this.activeTarget === 'quantity' || !this.scanQueue.length || this.phase !== 'receive') return; const next = this.scanQueue.shift(); this.dispatchHardwareScan(next) },
dispatchHardwareScan(scan) {
if (!this._pageActive || this.loading) return
// 排队扫码按当前步骤处理,避免沿用上一请求开始时的扫描目标。
if (this.activeInbound && this.activeTarget === 'pallet') {
this.palletInput = scan.value
return this.resolvePallet(scan.value)
}
if (this.canSubmitReceipt) return this.showToast('请先确认当前箱收货,再扫描下一箱', 'warning')
this.cartonInput = scan.value
return this.resolveCarton(scan.value)
},
drainScanQueue() { if (!this._pageActive || this.loading || this.busy || this.canSubmitReceipt || this.activeTarget === 'quantity' || !this.scanQueue.length || this.phase !== 'receive') return; const next = this.scanQueue.shift(); this.dispatchHardwareScan(next) },
suspendReceiving() { this._pageActive = false; this._scanEpoch = (this._scanEpoch || 0) + 1; this._resumeReceiving = true; clearTimeout(this._drainTimer); clearTimeout(this._toastTimer); this.scanQueue = []; this.stopScanner() },
scheduleScanDrain() { clearTimeout(this._drainTimer); if (!this._pageActive) return; const epoch = this._scanEpoch || 0; this._drainTimer = setTimeout(() => { if (this._pageActive && epoch === (this._scanEpoch || 0)) this.drainScanQueue() }, 0) },
async run(action, work, isCurrent = () => true) {
@@ -255,7 +265,7 @@
} catch (error) { if (!this.error) this.error = error }
},
async submitReceipt() { const isFba = this.activeInbound?.destinationType === 'FBA'; if (isFba && Number(this.packageCount) > MAX_PACKAGES_PER_PALLET) { this.error = Object.assign(new Error(PALLET_CAPACITY_MESSAGE), { code: 'A0409' }); playErrorSound(); this.showToast(PALLET_CAPACITY_MESSAGE, 'error'); return } if (!this.canSubmitReceipt) return; const payload = isFba ? { inboundCode: this.activeInbound.inboundCode, palletCode: this.resolvedPallet.palletCode, packageCount: Number(this.packageCount), expectedPalletVersion: this.resolvedPallet.version } : { cartonMark: this.activeInbound.cartonMark, palletCode: this.resolvedPallet.palletCode }; const key = idempotencyKey(isFba ? 'bulk-receipt' : 'carton-receipt', { containerNo: this.current?.containerNo, groupKey: this.activeInbound.groupKey, ...payload }); try { const result = await this.run('提交实收', async () => { const receipt = isFba ? await receiveCurrentBulk({ ...payload, idempotencyKey: key.value }) : await receiveCurrentCarton({ ...payload, idempotencyKey: key.value }); const current = this.validateReceivingWarehouse(await getCurrentReceiving(), '当前接柜会话'); return { receipt, current } }); releaseIdempotencyKey(key.signature); receiving.lastReceipt = result.receipt; await this.applyCurrentReceiving(result.current); this.clearReceiptContext(); playSuccessSound() } catch (_) {} },
async completeContainer() { if (!this.canFinishOnsite || this.activeTarget === 'quantity' || this.scanQueue.length) return; const payload = { allowDifference: !this.allInboundsReconciled }; const key = idempotencyKey('complete', { containerNo: this.current.containerNo, ...payload }); try { const value = await this.run(this.allInboundsReconciled ? '完成入库' : '结束现场收货', async () => this.validateReceivingWarehouse(await completeCurrentReceiving({ ...payload, idempotencyKey: key.value }), '当前接柜会话')); releaseIdempotencyKey(key.signature); await this.applyCurrentReceiving(value) } catch (_) {} },
async completeContainer() { if (!this.canFinishOnsite || this.canSubmitReceipt || this.activeTarget === 'quantity' || this.scanQueue.length) return; const payload = { allowDifference: !this.allInboundsReconciled }; const key = idempotencyKey('complete', { containerNo: this.current.containerNo, ...payload }); try { const value = await this.run(this.allInboundsReconciled ? '完成入库' : '结束现场收货', async () => this.validateReceivingWarehouse(await completeCurrentReceiving({ ...payload, idempotencyKey: key.value }), '当前接柜会话')); releaseIdempotencyKey(key.signature); await this.applyCurrentReceiving(value) } catch (_) {} },
async finishAndReturn() { resetReceivingDraft(); await this.loadCandidates(false) },
showToast(message, type) { clearTimeout(this._toastTimer); this.toast = { visible: true, message, type }; this._toastTimer = setTimeout(() => { this.toast.visible = false }, 2600) }
}
@@ -300,7 +310,9 @@
@media(max-width:360px){.photo-role{grid-template-columns:68px minmax(0,1fr) 64px;gap:7px;padding:8px}.photo-preview{width:68px;height:64px}.photo-actions button{min-height:34px;padding:0 2px;line-height:34px}.photo-state{font-size:9px;line-height:13px}.domestic-photo-grid{grid-template-columns:repeat(3,minmax(0,1fr))}}
.receiving-page{padding-bottom:env(safe-area-inset-bottom,0px)}
.receiving-content{box-sizing:border-box;padding-bottom:calc(24px + env(safe-area-inset-bottom,0px))}
.receiving-content-with-action{padding-bottom:calc(152px + env(safe-area-inset-bottom,0px))}
.receiving-content-with-action{padding-bottom:calc(24px + env(safe-area-inset-bottom,0px))}
.sticky-action-dock{position:static;max-width:none;margin:12px 0 0;padding:0;background:transparent}
.sticky-action{padding:10px;box-shadow:none}
.primary-button,.secondary-button,.ghost-button{display:flex;box-sizing:border-box;align-items:center;justify-content:center;padding-top:0;padding-bottom:0;line-height:normal;text-align:center}
.sticky-action button{display:flex;align-items:center;justify-content:center;line-height:normal;text-align:center}
.receiving-list-page{background:#f1f5fd}
+1
View File
@@ -173,6 +173,7 @@
if ((this.discardCurrentTasks || []).some(task => task.palletNo === code)) { this.setError(new Error('请扫描箱唛,不能把托盘码作为箱唛'), '箱唛核对失败'); return }
const sku = this.discardQuantityLines.length === 1 ? this.discardQuantityLines[0] : this.discardQuantityLines.find(line => line.itemId === this.discardScanItemId)
if (!sku) { this.setError(new Error('请先选择当前扫描的货物'), '箱唛核对失败'); return }
if (!(sku.allowedCartonMarks || []).includes(code)) { this.setError(new Error('箱唛不属于本废弃单的原入仓库存'), '箱唛核对失败'); return }
if (this.discardUnboundScans.some(scan => scan.mark === code)) { this.discardCartonCode = ''; return }
if (code.length > 128 || this.discardUnboundScans.filter(scan => scan.itemId === sku.itemId).length >= sku.plannedPackages || this.discardUnboundScans.length >= (this.discardTask.remainingPackages ?? Infinity)) { this.setError(new Error('扫描箱数不能超过本托预留或申请剩余箱数'), '箱唛核对失败'); return }
this.discardUnboundScans = [...this.discardUnboundScans, { itemId: sku.itemId, mark: code }]
+62 -21
View File
@@ -7,12 +7,25 @@
<view class="profile-row"><text>作业仓库</text><text class="profile-value">{{ warehouseDisplay }}</text></view>
<view class="profile-row"><text>当前班次</text><text class="profile-value">以海外仓排班为准</text></view>
<view class="profile-row"><text>应用版本</text><text class="profile-value">{{ appVersion }}</text></view>
<button class="profile-row profile-row-action" @tap="checkUpdate"><text>检查更新</text><text class="profile-row-arrow">›</text></button>
<button class="profile-row profile-row-action" @tap="checkUpdate" :disabled="checkingUpdate"><text>{{ checkingUpdate ? '检查中…' : '检查更新' }}</text><text class="profile-row-arrow">›</text></button>
<button class="profile-row profile-row-action" @tap="showSettings"><text>系统设置</text><text class="profile-row-arrow">›</text></button>
<button class="profile-row profile-row-action" @tap="selectLanguage"><text>切换语言</text><view class="profile-row-end"><text class="profile-value">{{ languageLabel }}</text><text class="profile-row-arrow">›</text></view></button>
</view>
<button class="logout-action" @tap="openLogout">退出登录</button>
</view>
<uni-popup ref="languagePopup" type="bottom" background-color="transparent" :is-mask-click="true" @change="handleLanguageChange">
<view class="language-sheet" role="dialog" aria-modal="true" aria-label="选择语言">
<PopupHeader title="选择语言" @close="closeLanguage" />
<view class="language-options" role="radiogroup" aria-label="可选语言">
<button v-for="item in languageOptions" :key="item.value" class="language-option" :class="{ selected: locale === item.value }" role="radio" :aria-checked="locale === item.value" @tap="applyLanguage(item.value)">
<text class="language-option-name">{{ item.label }}</text>
<view v-if="locale === item.value" class="language-option-current"><text>已选择</text><uni-icons type="checkmarkempty" color="#135ee8" size="20" /></view>
</button>
</view>
<text class="language-sheet-hint">业务页面暂以中文显示,语言偏好将保存在本机。</text>
<button class="language-cancel" @tap="closeLanguage">取消</button>
</view>
</uni-popup>
<uni-popup ref="logoutPopup" type="center" :is-mask-click="true" @change="handleLogoutChange"><view class="logout-dialog-card" role="dialog" aria-modal="true" aria-label="确认退出登录"><PopupHeader title="确认退出登录?" tone="danger" @close="closeLogout" /><text class="logout-dialog-content">退出会撤销当前登录会话并清空本地作业草稿;未提交作业数据不得跨账号保留。</text><view class="logout-dialog-actions"><button class="logout-dialog-cancel" @tap="closeLogout">取消</button><button class="logout-dialog-confirm" @tap="logout">确认退出</button></view></view></uni-popup>
<view v-if="toast" class="app-toast warning" role="status">设置功能将在后续版本开放</view>
</view>
@@ -20,6 +33,7 @@
<script>
import PortalHeader from '@/components/PortalHeader.vue'
import PopupHeader from '@/components/PopupHeader.vue'
import appManifest from '@/manifest.json'
import { getCurrentWarehouseProfile } from '@/api/inbound.js'
import { currentLocale, LOCALE_OPTIONS, setLocale } from '@/i18n/index.js'
import { applyWarehouseProfile, session, requireSession, getSessionRevision } from '@/stores/session.js'
@@ -27,7 +41,7 @@
import { checkForAppUpdate } from '@/utils/app-update.js'
export default {
components: { PopupHeader, PortalHeader },
data() { return { user: session.currentUser, appVersion: '0.0.1', locale: currentLocale(), logoutOpen: false, toast: false } },
data() { return { user: session.currentUser, appVersion: appManifest.versionName, checkingUpdate: false, locale: currentLocale(), languageOptions: LOCALE_OPTIONS, languageOpen: false, logoutOpen: false, toast: false } },
computed: {
displayName() { const name = String(this.user?.name || ''); return name && !/^[a-z0-9._-]+$/i.test(name) ? name : '仓库作业员' },
avatar() { return this.displayName.slice(0, 1).toUpperCase() },
@@ -35,34 +49,47 @@
warehouseDisplay() { return String(this.user?.warehouseName || '').trim() || '海外仓未关联' },
languageLabel() { return LOCALE_OPTIONS.find((item) => item.value === this.locale)?.label || 'English' }
},
onShow() { if (!requireSession()) return; this.user = session.currentUser; this.loadAppVersion(); this.loadWarehouseProfile() },
onShow() { if (!requireSession()) return; this.user = session.currentUser; this.locale = currentLocale(); this.loadAppVersion(); this.loadWarehouseProfile() },
beforeUnmount() { clearTimeout(this._toastTimer) },
onBackPress() { if (!this.logoutOpen) return false; this.closeLogout(); return true },
onBackPress() { if (this.languageOpen) { this.closeLanguage(); return true }; if (!this.logoutOpen) return false; this.closeLogout(); return true },
methods: {
loadAppVersion() {
this.appVersion = appManifest.versionName
// #ifdef APP-PLUS
if (typeof plus === 'undefined' || !plus.runtime) return
this.appVersion = String(plus.runtime.version || this.appVersion)
plus.runtime.getProperty(plus.runtime.appid, (properties) => {
this.appVersion = String(properties?.version || plus.runtime.version || appManifest.versionName)
})
// #endif
},
checkUpdate() {
// #ifdef APP-PLUS
checkForAppUpdate({ manual: true })
return
// #endif
// #ifndef APP-PLUS
uni.showToast({ title: '请在 PDA App 中检查更新', icon: 'none' })
// #endif
async checkUpdate() {
if (this.checkingUpdate) return
this.checkingUpdate = true
try {
// #ifdef APP-PLUS
await checkForAppUpdate({ manual: true })
return
// #endif
// #ifndef APP-PLUS
uni.showToast({ title: '请在 PDA App 中检查更新', icon: 'none' })
// #endif
} finally { this.checkingUpdate = false }
},
selectLanguage() {
uni.showActionSheet({
itemList: LOCALE_OPTIONS.map((item) => item.label),
success: ({ tapIndex }) => {
const selected = LOCALE_OPTIONS[tapIndex]
if (!selected) return
this.locale = setLocale(selected.value)
uni.showToast({ title: `语言设置已保存:${selected.label}`, icon: 'none' })
}
})
this.languageOpen = true
this.$refs.languagePopup.open()
},
closeLanguage() { this.languageOpen = false; this.$refs.languagePopup.close() },
handleLanguageChange(event) { this.languageOpen = Boolean(event.show) },
applyLanguage(value) {
const selected = LOCALE_OPTIONS.find((item) => item.value === value)
if (!selected) return
if (selected.value !== this.locale) {
this.locale = setLocale(selected.value)
uni.showToast({ title: `语言偏好已保存:${selected.label}`, icon: 'none' })
}
this.closeLanguage()
},
async loadWarehouseProfile() { try { this.user = applyWarehouseProfile(await getCurrentWarehouseProfile()) } catch (_) { this.user = session.currentUser } },
openLogout() { this.logoutOpen = true; this.$refs.logoutPopup.open() }, closeLogout() { this.logoutOpen = false; this.$refs.logoutPopup.close() }, handleLogoutChange(event) { this.logoutOpen = Boolean(event.show) },
@@ -83,3 +110,17 @@
}
}
</script>
<style scoped>
.profile-row-end{flex-shrink:0}
.profile-row-end .profile-value{max-width:none;flex-shrink:0;white-space:nowrap;overflow-wrap:normal}
.language-sheet{box-sizing:border-box;width:100%;max-width:480px;margin:0 auto;padding:4px 16px calc(16px + env(safe-area-inset-bottom,0px));border-radius:20px 20px 0 0;background:#fff}
.language-options{display:flex;flex-direction:column;gap:8px;margin-top:8px}
.language-option{display:flex;box-sizing:border-box;align-items:center;justify-content:space-between;gap:12px;width:100%;min-height:52px;margin:0;padding:12px 14px;border:1px solid #dce5f0;border-radius:10px;color:#1f2937;font-size:15px;line-height:22px;text-align:left;background:#fff}
.language-option::after,.language-cancel::after{border:0}
.language-option.selected{border-color:#b8d1f5;color:#135ee8;background:#f1f6ff}
.language-option-name{min-width:0;white-space:nowrap}
.language-option-current{display:flex;flex-shrink:0;align-items:center;gap:6px;color:#135ee8;font-size:12px;line-height:20px}
.language-sheet-hint{display:block;margin:12px 2px;color:#718095;font-size:11px;line-height:18px}
.language-cancel{display:flex;align-items:center;justify-content:center;width:100%;min-height:44px;margin:0;padding:0 12px;border:1px solid #dce5f0;border-radius:10px;color:#526174;font-size:14px;line-height:22px;background:#f7f9fc}
</style>
+34 -8
View File
@@ -1,13 +1,26 @@
<template>
<view v-if="user" class="page-shell portal-page">
<view v-if="user" class="page-shell portal-page" :class="{ 'pda-task-list counting-list-page': !task }">
<PortalHeader title="退货箱内清点" :user="user" />
<view class="work-content counting-content">
<view class="work-card"><ScanTargetInput name="carton" v-model="scanCode" label="箱号或托盘号" placeholder="扫描箱号或托盘号" :active="true" @submit="scan" /><view class="actions"><button v-if="task || scanResult" class="secondary small" :disabled="busy" @tap="back">返回任务</button></view></view>
<view class="work-card counting-scan-card"><ScanTargetInput name="carton" v-model="scanCode" label="箱号或托盘号" placeholder="扫描箱号或托盘号" :active="true" @submit="scan" /><view v-if="task || scanResult" class="actions"><button class="secondary small" :disabled="busy" @tap="back">返回任务</button></view></view>
<view v-if="error" class="work-card error-card"><text>{{ error.message }}</text><text v-if="error.code" class="hint">错误码:{{ error.code }}</text><text v-if="error.requestId" class="hint">请求号:{{ error.requestId }}</text><text v-if="error.traceId" class="hint">跟踪号:{{ error.traceId }}</text></view>
<template v-if="!task">
<view v-if="activeTask" class="work-card"><text class="card-title">有未完成的清点任务</text><text class="hint">{{ activeTask.returnNo }} · {{ activeTask.palletCode }}</text><button class="secondary small" :disabled="busy" @tap="choose(activeTask)">继续未完成清点</button></view>
<view v-for="row in tasks" :key="row.receiptNo" class="work-card" @tap="choose(row)"><text class="card-title">{{ row.palletCode }}</text><text class="hint">{{ row.returnNo }}</text><text class="hint">{{ row.boxes.length }} 箱 · {{ row.status === 'COUNTING' ? '清点中' : '待清点' }}</text><text class="entry">{{ row.status === 'COUNTING' ? '继续清点' : '开始清点' }} ›</text></view>
<view v-if="!error && !busy && !tasks.length" class="work-card hint">{{ scanResult ? '无需清点' : '暂无待清点的托盘签收任务' }}</view>
<view class="pda-list-toolbar"><text>清点任务<text v-if="!listLoading && !error"> · {{ total }} 项</text></text><button v-if="!scanResult" :disabled="busy" @tap="load"><uni-icons type="refresh" color="#135ee8" size="18" /><text>{{ listLoading ? '刷新中…' : '刷新' }}</text></button></view>
<button v-if="activeTask && !activeTaskListed" class="pda-task-card current counting-resume-card" hover-class="pda-task-card-pressed" :disabled="busy" @tap="choose(activeTask)">
<text class="counting-resume-title">未完成的清点任务</text>
<view class="pda-task-head"><text class="pda-task-no">{{ activeTask.palletCode || '未关联托盘' }}</text><text class="pda-task-status counting-status-active">清点中</text></view>
<text class="pda-task-meta">退货单:{{ activeTask.returnNo || '—' }}</text>
<view class="pda-task-footer"><view class="pda-task-action"><text>{{ openingReceiptNo === activeTask.receiptNo ? '打开中…' : '继续清点' }}</text><uni-icons type="right" color="#135ee8" size="14" /></view></view>
</button>
<view v-if="tasks.length" class="pda-list-cards">
<button v-for="row in tasks" :key="row.receiptNo" class="pda-task-card counting-task-card" :class="{ current: activeTask?.receiptNo && activeTask.receiptNo === row.receiptNo }" hover-class="pda-task-card-pressed" :disabled="busy" @tap="choose(row)">
<view class="pda-task-head"><text class="pda-task-no">{{ row.palletCode || '未关联托盘' }}</text><text class="pda-task-status counting-status" :class="{ 'counting-status-active': row.status === 'COUNTING' }">{{ row.status === 'COUNTING' ? '清点中' : '待清点' }}</text></view>
<text class="pda-task-meta">退货单:{{ row.returnNo || '—' }}</text>
<view class="pda-task-footer"><view class="counting-task-facts"><text>{{ row.boxes.length }} 箱</text><text v-if="activeTask?.receiptNo && activeTask.receiptNo === row.receiptNo" class="counting-current-label">当前任务</text></view><view class="pda-task-action"><text>{{ openingReceiptNo === row.receiptNo ? '打开中…' : row.status === 'COUNTING' ? '继续清点' : '开始清点' }}</text><uni-icons type="right" color="#135ee8" size="14" /></view></view>
</button>
</view>
<view v-if="listLoading && !tasks.length && !activeTask" class="work-card hint">正在加载清点任务…</view>
<view v-if="!error && !busy && !tasks.length && !activeTask" class="work-card hint">{{ scanResult ? '无需清点' : '暂无待清点的托盘签收任务' }}</view>
<view v-if="!scanResult && total > 10" class="actions pager"><button class="secondary small" :disabled="busy || page <= 1" @tap="changePage(-1)">上一页</button><text>{{ page }} / {{ Math.max(1, Math.ceil(total / 10)) }}</text><button class="secondary small" :disabled="busy || page * 10 >= total" @tap="changePage(1)">下一页</button></view>
</template>
<template v-else>
@@ -29,8 +42,9 @@ import { startScanBroadcast } from '@/utils/scan-broadcast.js'
import { listReturnCountTasks, scanReturnCountTasks, getCurrentReturnCountTask, beginReturnCountTask, confirmReturnCount } from '@/api/return-counting.js'
export default {
components: { PortalHeader, ScanTargetInput, CartonCountFields },
data() { return { user: session.currentUser, busy: false, error: null, scanCode: '', scanResult: '', page: 1, total: 0, tasks: [], task: null, activeTask: null, selectedMark: '', requestKey: '', signature: '', scannerStop: null } },
data() { return { user: session.currentUser, busy: false, listLoading: false, openingReceiptNo: '', error: null, scanCode: '', scanResult: '', page: 1, total: 0, tasks: [], task: null, activeTask: null, selectedMark: '', requestKey: '', signature: '', scannerStop: null } },
computed: {
activeTaskListed() { return Boolean(this.activeTask?.receiptNo && this.tasks.some(row => row.receiptNo === this.activeTask.receiptNo)) },
skuCodes() { return this.task?.expectedItems.map(row => row.skuCode) || [] },
totals() { return (this.task?.expectedItems || []).map(row => ({ ...row, quantity: Number(row.quantity), actual: this.task.boxes.reduce((sum, box) => sum + box.items.filter(line => line.skuCode === row.skuCode).reduce((value, line) => value + (Number(line.quantity) || 0), 0), 0) })) },
ready() { return this.task?.status === 'COUNTING' && this.totals.length > 0 && this.totals.every(row => row.actual === row.quantity) && this.task.boxes.every(box => box.items.length && (!('length' in box) || (Number(box.length) > 0 && Number(box.width) > 0 && Number(box.height) > 0 && Number(box.weight) > 0)) && box.items.every(line => this.skuCodes.includes(line.skuCode) && Number.isSafeInteger(Number(line.quantity)) && Number(line.quantity) > 0) && new Set(box.items.map(line => line.skuCode)).size === box.items.length) },
@@ -44,11 +58,12 @@ export default {
stopScanner() { this.scannerStop?.(); this.scannerStop = null },
async run(work) { if (this.busy) return; this.busy = true; this.error = null; try { await work() } catch (error) { this.error = { message: error?.message || '清点操作失败', code: error?.code, requestId: error?.requestId, traceId: error?.traceId } } finally { this.busy = false } },
async fetchTasks() { const [active, value] = await Promise.all([getCurrentReturnCountTask(), listReturnCountTasks({ page: this.page })]); this.activeTask = active; this.tasks = value.records || []; this.total = Number(value.total) || 0 },
async load() { await this.run(() => this.fetchTasks()) },
async load() { await this.run(async () => { this.listLoading = true; try { await this.fetchTasks() } finally { this.listLoading = false } }) },
changePage(delta) { this.page += delta; this.load() },
ask(options) { return new Promise((resolve, reject) => uni.showModal({ ...options, success: resolve, fail: reject })) },
async choose(row) {
await this.run(() => this.enterTask(row, true));
if (!row?.receiptNo || this.busy) return;
await this.run(async () => { this.openingReceiptNo = row.receiptNo; try { await this.enterTask(row, true) } finally { this.openingReceiptNo = '' } });
},
async enterTask(row, confirmStart = false) {
const active = await getCurrentReturnCountTask(); this.activeTask = active;
@@ -91,4 +106,15 @@ export default {
.counting-content .primary{display:flex;align-items:center;justify-content:center;padding:0 12px;line-height:normal;text-align:center}
.actions{display:flex;align-items:center;gap:8px;margin-top:10px}.small{width:auto;min-height:32px;margin:0;padding:0 12px;font-size:12px;line-height:32px}.search{width:100%;font-size:12px}.pager{justify-content:center;font-size:12px}.entry,.success{color:#135ee8;font-size:12px}.total-row{display:flex;justify-content:space-between;gap:12px;font-size:11px;margin-top:8px;color:#c67716}.total-row.matched{color:#22804a}.box-mark{display:block;color:#65768b;font-size:11px;margin:6px 0;word-break:break-all}.count-line{display:flex;align-items:center;gap:8px;margin-top:8px}.sku-picker{flex:1;min-width:0;font-size:11px;word-break:break-all}.quantity{flex:none;width:70px;height:32px;text-align:center;font-size:12px}.box-card.selected{border-color:#135ee8}.row-head .card-title{font-size:13px}
.measure-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:7px;margin:10px 0 6px}.measure-grid label text{display:block;margin-bottom:4px;color:#65768b;font-size:10px}.measure-input{box-sizing:border-box;width:100%;height:34px;padding:0 8px;border:1px solid #cbd9e8;border-radius:8px;color:#203750;font-size:13px;text-align:center;background:#fbfdff}.volume-chip{display:flex;align-items:baseline;justify-content:flex-end;gap:4px;margin:4px 0 8px;color:#728197;font-size:10px}.volume-chip strong{color:#135ee8;font-size:14px}
@import '../../styles/task-list.scss';
.counting-list-page{background:#f1f5fd}
.counting-list-page .counting-content{padding:14px 14px calc(42px + env(safe-area-inset-bottom,0px))}
.counting-list-page .work-card{box-shadow:none}
.counting-list-page .pda-task-head{align-items:flex-start}
.counting-list-page .counting-resume-card{margin-bottom:11px}
.counting-resume-title{display:block;margin-bottom:8px;color:#526174;font-size:12px;line-height:18px}
.counting-status{color:#8a570c;background:#fff1dd}
.counting-status-active{color:#135ee8;background:#e4efff}
.counting-task-facts{display:flex;align-items:center;flex-wrap:wrap;gap:8px;min-width:0;color:#718095;font-size:12px;line-height:20px;overflow-wrap:anywhere}
.counting-current-label{color:#135ee8;font-size:11px}
</style>
+58 -23
View File
@@ -1,17 +1,29 @@
<template>
<view v-if="user" class="page-shell portal-page work-page">
<view v-if="user" class="page-shell portal-page work-page receipt-page" :class="{ 'pda-task-list receipt-lookup-page': receiptDomain === 'customer' && !current && !result }">
<PortalHeader title="退货入库" :user="user" />
<scroll-view class="work-scroll" scroll-y><view class="portal-content work-content">
<view v-if="!current && !result" class="work-card">
<view v-if="!current && !result && !exceptionWorking" class="receipt-domain-tabs" role="tablist" aria-label="退货入库类型">
<button :class="['receipt-domain-tab', { active: receiptDomain === 'customer' }]" role="tab" :aria-selected="receiptDomain === 'customer'" :disabled="busy" @tap="switchDomain('customer')">客户退货入库</button>
<button :class="['receipt-domain-tab', { active: receiptDomain === 'exception' }]" role="tab" :aria-selected="receiptDomain === 'exception'" :disabled="busy" @tap="switchDomain('exception')">异常退货入库</button>
</view>
<ExceptionReturnWork v-if="receiptDomain === 'exception'" @working-change="exceptionWorking = $event" />
<scroll-view v-if="receiptDomain === 'customer'" class="work-scroll" scroll-y><view class="portal-content work-content">
<view v-if="!current && !result" class="work-card receipt-lookup-card">
<text class="card-title">扫描 SKU 69 码</text>
<ScanTargetInput name="lookup" v-model="lookupCode" label="SKU 69 码" placeholder="扫描商品 69 码,自动带出退货单号" :active="activeTarget === 'lookup'" @activate="activeTarget = 'lookup'" @submit="lookup" />
<ScanTargetInput name="lookup" v-model="lookupCode" label="SKU 69 码" placeholder="扫描或输入69码" :active="activeTarget === 'lookup'" @activate="activeTarget = 'lookup'" @submit="lookup" />
<button class="secondary receipt-lookup-button" :disabled="busy || !lookupCode.trim()" @tap="lookup()">{{ busy ? '查询中…' : '查询退货单' }}</button>
</view>
<view v-if="!current && candidates !== null && !result" class="section-gap">
<view class="row-head candidate-heading"><text class="card-title">匹配退货单</text><text class="meta-line">{{ candidates.length }} 个候选</text></view>
<view v-if="!candidates.length" class="empty-box"><text class="empty-copy">{{ entryMode === 'SKU' ? '当前绑定仓没有包含该 SKU 的待签收退货单' : '当前绑定仓没有匹配的待签收或签收中退货单' }}</text></view>
<view v-else class="task-list"><button v-for="item in candidates" :key="item.returnNo" class="task-card candidate-card" @tap="selectCandidate(item)"><view class="row-head"><text class="business-code">{{ item.returnNo }}</text><text class="status-pill">{{ statusLabel(item.status) }}</text></view><text class="meta-line">客户参考号:{{ item.customerReferenceNo || '—' }}</text><view class="metric-row"><view class="metric"><strong>{{ item.skuReceivedQuantity }}/{{ item.skuExpectedQuantity }}</strong><text>该 SKU</text></view><view class="metric"><strong>{{ item.orderReceivedQuantity }}/{{ item.orderExpectedQuantity }}</strong><text>整单进度</text></view><text class="select-link">选择 ›</text></view></button></view>
<view class="pda-list-toolbar"><text>匹配退货单<text v-if="!busy && !error"> · {{ candidates.length }} 单</text></text></view>
<view v-if="!candidates.length && !busy && !error" class="empty-box receipt-candidate-empty"><text class="empty-copy">{{ entryMode === 'SKU' ? '当前绑定仓没有包含该 SKU 的待签收退货单' : '当前绑定仓没有匹配的待签收或签收中退货单' }}</text></view>
<view v-if="candidates.length" class="pda-list-cards">
<button v-for="item in candidates" :key="item.returnNo" class="pda-task-card receipt-candidate-card" hover-class="pda-task-card-pressed" :disabled="busy" @tap="selectCandidate(item)">
<view class="pda-task-head"><text class="pda-task-no">{{ item.returnNo }}</text><text class="status-pill pda-task-status" :class="{ 'receipt-status-active': item.status === 'PARTIALLY_RECEIVED', good: item.status === 'COMPLETED' }">{{ statusLabel(item.status) }}</text></view>
<text v-if="String(item.customerReferenceNo || '').trim() && String(item.customerReferenceNo || '').trim() !== String(item.returnNo || '').trim()" class="pda-task-meta">客户参考号:{{ item.customerReferenceNo }}</text>
<view class="pda-task-metrics"><view><strong>{{ item.skuReceivedQuantity }} / {{ item.skuExpectedQuantity }}</strong><text>SKU 实收 / 预期</text></view><view><strong>{{ item.orderReceivedQuantity }} / {{ item.orderExpectedQuantity }}</strong><text>整单实收 / 预期</text></view></view>
<view class="pda-task-footer"><view class="pda-task-action"><text>选择</text><uni-icons type="right" color="#135ee8" size="14" /></view></view>
</button>
</view>
</view>
<template v-if="current && !result">
<view class="work-card receipt-order-card"><view class="row-head"><text class="card-title">退货单</text><button class="link-button" @tap="clearCurrent">更换退货单</button></view><view class="receipt-order-line"><text class="business-code">{{ current.returnNo }}</text><text class="status-pill">{{ statusLabel(current.status) }}</text></view></view>
@@ -19,10 +31,10 @@
<view class="work-card">
<text class="card-title">本次实物单元</text>
<view class="unit-tabs"><button v-for="item in unitOptions" :key="item.value" :class="['unit-tab', {active: unitType === item.value}]" @tap="selectUnitType(item.value)">{{ item.label }}</button></view>
<view v-if="unitType === 'PARCEL'"><ScanTargetInput name="unit" v-model="unitCode" label="本批快递单号(选填,只填写一次)" placeholder="扫描本批快递面单,可留空" :active="activeTarget === 'unit'" @activate="activeTarget = 'unit'" @submit="acceptUnit" /><text class="hint">本批共用一个快递单号;填写包裹数,再逐包裹录入 SKU 数量,各包裹单独生成仓库标签。</text></view>
<view v-if="unitType === 'PARCEL'"><ScanTargetInput name="unit" v-model="unitCode" label="本批快递单号(选填,只填写一次)" placeholder="扫描本批快递面单,可留空" :active="activeTarget === 'unit'" @activate="activeTarget = 'unit'" @submit="acceptUnit" /></view>
<template v-else>
<view><text class="field-label">托盘码({{ unitType === 'BOX' ? '选填' : '必填' }})</text><ScanTargetInput name="pallet" v-model="palletCode" label="托盘码" placeholder="扫描已有托盘或新托盘标签" :active="activeTarget === 'pallet'" @activate="activeTarget = 'pallet'" @submit="acceptPallet" /><text v-if="palletCheck" class="scan-hint">{{ palletCheck.empty ? '空托盘,可绑定当前退货单和 SKU' : `当前单托盘,已有 ${palletCheck.skuCodes.join('、')},共 ${palletCheck.quantity} 件` }}</text><button class="secondary pallet-generate" :disabled="busy" @tap="generatePallet">生成新托盘</button></view>
<view v-if="unitType === 'PALLET'" class="dimension-grid"><label><text>托盘长(cm)</text><input class="number-input" type="digit" v-model="palletLength" placeholder="请输入长度(cm)" /></label><label><view class="dimension-label"><text>托盘宽(cm)</text><text class="volume-text">体积 {{ palletVolume }} cm³</text></view><input class="number-input" type="digit" v-model="palletWidth" placeholder="请输入宽度(cm)" /></label><label><text>托盘高(cm)</text><input class="number-input" type="digit" v-model="palletHeight" placeholder="请输入高度(cm)" /></label><label><text>托盘重量(kg)</text><input class="number-input" type="digit" v-model="palletWeight" placeholder="请输入重量(kg)" /></label></view>
<view v-if="unitType === 'PALLET'" class="dimension-grid"><label><text>托盘长(cm)</text><input class="number-input" type="digit" v-model="palletLength" placeholder="请输入长度(cm)" /></label><label><view class="dimension-label"><text>托盘宽(cm)</text><text class="volume-text">体积 {{ palletVolume }} m³</text></view><input class="number-input" type="digit" v-model="palletWidth" placeholder="请输入宽度(cm)" /></label><label><text>托盘高(cm)</text><input class="number-input" type="digit" v-model="palletHeight" placeholder="请输入高度(cm)" /></label><label><text>托盘重量(kg)</text><input class="number-input" type="digit" v-model="palletWeight" placeholder="请输入重量(kg)" /></label></view>
<view><text class="field-label">快递单号(选填)</text><ScanTargetInput name="tracking" v-model="trackingNo" label="快递单号" placeholder="扫描快递面单" :active="activeTarget === 'tracking'" @activate="activeTarget = 'tracking'" @submit="acceptTracking" /></view>
</template>
</view>
@@ -36,7 +48,7 @@
<template v-if="box.confirmed"><text class="meta-line">{{ box.length }} × {{ box.width }} × {{ box.height }} cm · {{ box.weight }} kg · {{ box.originalPackaging ? '原包装' : '新包装' }}</text><text v-for="item in selectedItems.filter(item => Number(box.items[item.skuCode]) > 0)" :key="item.skuCode" class="meta-line">{{ item.skuCode }} · {{ box.items[item.skuCode] }} 件</text></template>
<template v-else>
<view class="dimension-grid unit-dimension-grid"><label><text>长(cm)</text><input class="number-input" type="digit" v-model="box.length" placeholder="长" :disabled="busy" /></label><label><text>宽(cm)</text><input class="number-input" type="digit" v-model="box.width" placeholder="宽" :disabled="busy" /></label><label><text>高(cm)</text><input class="number-input" type="digit" v-model="box.height" placeholder="高" :disabled="busy" /></label><label><text>重量(kg)</text><input class="number-input" type="digit" v-model="box.weight" placeholder="重量" :disabled="busy" /></label></view>
<view class="unit-volume"><text>体积</text><strong>{{ rowVolume(box) }}</strong><text>cm³</text></view>
<view class="unit-volume"><text>体积</text><strong>{{ rowVolume(box) }}</strong><text>m³</text></view>
<view class="packaging-choice"><text>是否使用原{{ unitType === 'PARCEL' ? '包装' : '箱' }}</text><button :class="['choice-button', {selected: box.originalPackaging === true}]" :disabled="busy" @tap="setOriginalPackaging(index, true)">是</button><button :class="['choice-button', {selected: box.originalPackaging === false}]" :disabled="busy" @tap="setOriginalPackaging(index, false)">否</button></view>
<view v-for="item in selectedItems" :key="item.skuCode" class="quantity-row"><text>{{ item.skuCode }} · 数量</text><input class="number-input unit-quantity-input" type="number" :value="box.items[item.skuCode] || ''" :placeholder="'剩余 ' + boxRemaining(index, item)" :disabled="busy" @input="setBoxQuantity(index, item.skuCode, $event.detail.value)" /></view>
<button v-if="boxRowValid(index)" class="primary" :disabled="busy" @tap="confirmBoxRow(index)">确认第 {{ index + 1 }} {{ unitType === 'PARCEL' ? '包裹' : '箱' }}</button>
@@ -44,14 +56,12 @@
</view>
</template>
<view v-if="unitType === 'PALLET'" class="item-list receipt-sku-list"><view v-for="item in selectedItems" :key="item.skuCode" class="item-card"><view class="row-head"><view><text class="business-code">{{ item.skuCode }}</text><text class="meta-line">{{ item.productNameZh || '商品名称未填写' }}</text></view><text class="remaining-copy">剩余 {{ remaining(item) }}</text></view><view class="sku-quantity-fields"><view class="quantity-row"><text>数量</text><input class="number-input" type="number" :value="quantity(item.skuCode)" placeholder="0" @input="setQuantity(item, $event.detail.value)" /></view><view v-if="unitType === 'PALLET'" class="quantity-row"><text>SKU 箱数</text><input class="number-input" type="number" :value="boxCount(item.skuCode)" placeholder="0" @input="setBoxCount(item, $event.detail.value)" /></view></view></view></view></view>
<view v-if="unitType === 'PALLET'" class="summary-bar"><view><text class="summary-label">{{ unitType === 'PARCEL' ? '本次合计' : '本托合计' }}</text><text class="summary-value">{{ receiptQuantity }}</text></view><button class="primary submit-button" :disabled="!canConfirm || busy" @tap="confirmReceipt">{{ busy ? '提交中…' : unitType === 'PARCEL' ? '确认包裹签收' : '确认签收并入托' }}</button></view>
<view class="summary-bar"><view><text class="summary-label">{{ unitType === 'PALLET' ? '本托合计' : '本次合计' }}</text><text class="summary-value">{{ receiptQuantity }}</text></view><view class="receipt-action-buttons"><button class="primary submit-button" :disabled="busy || !canConfirm || (unitType !== 'PALLET' && !allBoxRowsConfirmed)" @tap="confirmReceipt">{{ busy ? '提交中…' : '确认签收' }}</button><button class="secondary manual-complete" :disabled="busy" @tap="manualComplete">缺货完结</button></view></view>
<view class="work-card"><view class="row-head"><view><text class="card-title">退货打托照片</text></view><text class="status-pill">{{ photoFileIds.length }} / 20 张</text></view><button class="secondary" :disabled="busy || photoFileIds.length >= 20" @tap="choosePhoto()">拍照或从相册选择</button><view v-if="photoFileIds.length" class="photo-grid"><view v-for="(fileId,index) in photoFileIds" :key="fileId" class="photo-tile"><image class="photo-thumbnail" :src="photoUrls[fileId]" mode="aspectFill" @tap="previewPhoto(fileId)" /><text class="photo-name">{{ photoNames[index] || '退货打托照片' }}</text><button class="link-button" :disabled="busy" @tap="removePhoto(index)">移除</button></view></view></view>
<view v-if="unitType !== 'PALLET'" class="summary-bar"><view><text class="summary-label">本次合计</text><text class="summary-value">{{ receiptQuantity }}</text></view><button class="primary submit-button" :disabled="busy || !canConfirm || !allBoxRowsConfirmed || !photoFileIds.length" @tap="confirmReceipt">{{ busy ? '提交中…' : '确认签收入库' }}</button></view>
<button v-if="current.status === 'PARTIALLY_RECEIVED'" class="secondary manual-complete" :disabled="busy" @tap="manualComplete">缺货手动完结</button>
<view v-if="current.completedPallets?.length" class="work-card"><text class="card-title">本单已完成打托</text><view class="item-list"><view v-for="pallet in current.completedPallets" :key="pallet.palletCode" class="item-card"><text class="business-code">{{ pallet.palletCode }}</text><text class="meta-line">{{ pallet.skuCode }} · {{ pallet.quantity }} 件</text><text class="meta-line">签收批次:{{ pallet.receiptBatchNo }}</text></view></view></view>
</template>
<view v-if="result" class="success-box result-card"><text class="success-title">退货签收成功</text><view v-if="result.labels?.length"><view v-for="(label,index) in result.labels" :key="label.cartonMark" class="item-card"><text class="business-code">第 {{ index + 1 }} {{ result.unitType === 'PARCEL' ? '包裹' : '箱' }} · {{ label.cartonMark }}</text><button class="secondary" @tap="printReturnCarton(label)">打印包裹/箱标签</button><text class="meta-line">签收已默认贴标</text></view></view><view v-else-if="result.printableHtml" class="item-card"><text class="business-code">{{ result.unitType === 'PALLET' ? '托盘标签' : '箱唛' }} · {{ result.cartonMark }}</text><button class="secondary" @tap="printReturnCarton(result)">打印{{ result.unitType === 'PALLET' ? '托盘标签' : '箱唛' }}</button></view><button v-if="result.unitType === 'PALLET' && result.labels?.length" class="secondary" :disabled="busy" @tap="goCount">去箱内清点</button><text v-if="result.palletCode" class="result-carton">托盘:{{ result.palletCode }}</text><text class="meta-line">签收单:{{ result.receiptNo }}</text><text class="meta-line">计费批次:{{ result.receiptBatchNo }}</text><view class="metric-row"><view class="metric"><strong>{{ result.receivedQuantity }}/{{ result.expectedQuantity }}</strong><text>整单累计</text></view><view class="metric"><strong>{{ result.fullyMatched ? '已完成' : '签收中' }}</strong><text>退货单状态</text></view></view><button class="primary" :disabled="busy" @tap="nextReceipt">{{ result.continuationReturnNo ? (unitType === 'PALLET' ? '新增托盘,继续签收剩余货物' : '继续签收本单剩余货物') : '签收下一单' }}</button><button v-if="unitType === 'PALLET' && result.continuationReturnNo" class="secondary" :disabled="busy" @tap="continueScanning">继续签收</button></view>
<view v-if="result" class="success-box result-card"><view v-if="result.labels?.length"><view v-for="(label,index) in result.labels" :key="label.cartonMark" class="item-card"><text class="business-code">第 {{ index + 1 }} {{ result.unitType === 'PARCEL' ? '包裹' : '箱' }} · {{ label.cartonMark }}</text><button class="secondary" @tap="printReturnCarton(label)">打印包裹/箱标签</button></view></view><view v-else-if="result.printableHtml" class="item-card"><text class="business-code">{{ result.unitType === 'PALLET' ? '托盘标签' : '箱唛' }} · {{ result.cartonMark }}</text><button class="secondary" @tap="printReturnCarton(result)">打印{{ result.unitType === 'PALLET' ? '托盘标签' : '箱唛' }}</button></view><button v-if="result.unitType === 'PALLET' && result.labels?.length" class="secondary" :disabled="busy" @tap="goCount">去箱内清点</button><text v-if="result.palletCode" class="result-carton">托盘:{{ result.palletCode }}</text><view class="metric-row"><view class="metric"><strong>{{ result.receivedQuantity }}/{{ result.expectedQuantity }}</strong></view><view class="metric"><strong>{{ result.fullyMatched ? '已完成' : '签收中' }}</strong></view></view><button class="primary" :disabled="busy" @tap="nextReceipt">{{ result.continuationReturnNo ? (unitType === 'PALLET' ? '新增托盘,继续签收剩余货物' : '继续签收本单剩余货物') : '签收下一单' }}</button><button v-if="unitType === 'PALLET' && result.continuationReturnNo" class="secondary" :disabled="busy" @tap="continueScanning">继续签收</button></view>
<view v-if="error" class="error-box" role="alert"><text class="error-title">{{ error.message }}</text><text v-if="error.code">错误码:{{ error.code }}</text><text v-if="error.requestId">requestId:{{ error.requestId }}</text><text v-if="error.traceId">traceId:{{ error.traceId }}</text><button v-if="current" class="secondary" :disabled="busy" @tap="reloadCurrent">刷新退货单</button></view>
</view></scroll-view>
@@ -59,7 +69,8 @@
</template>
<script>
import PortalHeader from '@/components/PortalHeader.vue'
import ExceptionReturnWork from '@/components/ExceptionReturnWork.vue'
import PortalHeader from '@/components/PortalHeader.vue'
import ScanTargetInput from '@/components/ScanTargetInput.vue'
import { checkReturnPallet, confirmReturnReceipt, createReturnPallet, downloadReturnPalletPhoto, findReturnSkuCandidates, manuallyCompleteReturnReceipt, startReturnReceipt, uploadReturnPalletPhoto } from '@/api/return-receipt.js'
import { session, requireSession } from '@/stores/session.js'
@@ -68,8 +79,8 @@
import { playErrorSound, playSuccessSound } from '@/utils/audio-feedback.js'
export default {
components: { PortalHeader, ScanTargetInput },
data() { return { user: session.currentUser, current: null, candidates: null, result: null, receiptResults: [], selectedSku: '', palletCheck: null, newPalletHtml: '', unitType: 'PALLET', unitCode: '', boxRows: [{ items: {}, length: '', width: '', height: '', weight: '', originalPackaging: true, confirmed: false }], palletLength: '', palletWidth: '', palletHeight: '', palletWeight: '', unitOptions: [{ value: 'PALLET', label: '托盘' }, { value: 'BOX', label: '箱子' }, { value: 'PARCEL', label: '包裹' }], photoFileIds: [], photoNames: [], photoUrls: {}, activeTarget: 'lookup', busy: false, error: null } },
components: { PortalHeader, ScanTargetInput, ExceptionReturnWork },
data() { return { receiptDomain: 'customer', exceptionWorking: false, user: session.currentUser, current: null, candidates: null, result: null, receiptResults: [], selectedSku: '', palletCheck: null, newPalletHtml: '', unitType: 'PALLET', unitCode: '', boxRows: [{ items: {}, length: '', width: '', height: '', weight: '', originalPackaging: true, confirmed: false }], palletLength: '', palletWidth: '', palletHeight: '', palletWeight: '', unitOptions: [{ value: 'PALLET', label: '托盘' }, { value: 'BOX', label: '箱子' }, { value: 'PARCEL', label: '包裹' }], photoFileIds: [], photoNames: [], photoUrls: {}, activeTarget: 'lookup', busy: false, error: null } },
computed: {
entryMode: { get() { return warehouseWork.returnReceipt.entryMode }, set(value) { updateWarehouseWork('returnReceipt', { entryMode: value }) } },
lookupCode: { get() { return warehouseWork.returnReceipt.lookupCode }, set(value) { updateWarehouseWork('returnReceipt', { lookupCode: value }) } },
@@ -84,16 +95,17 @@
canConfirm() { if (!this.current || !this.selectedItems.length || this.receiptQuantity <= 0) return false; if (this.unitType !== 'PALLET') return this.boxRows.length > 0 && this.boxRows.every(box => Object.values(box.items).some(quantity => Number(quantity) > 0) && (!('length' in box) || (Number(box.length) > 0 && Number(box.width) > 0 && Number(box.height) > 0 && Number(box.weight) > 0 && typeof box.originalPackaging === 'boolean'))) && this.selectedItems.every(item => this.boxRows.reduce((sum, box) => sum + (Number(box.items[item.skuCode]) || 0), 0) <= this.remaining(item)); return (this.palletCode.trim() && this.palletCheck && Number(this.palletLength) > 0 && Number(this.palletWidth) > 0 && Number(this.palletHeight) > 0 && Number(this.palletWeight) > 0 && this.palletBoxCount > 0) && this.selectedItems.every((item) => this.quantity(item.skuCode) <= this.remaining(item) && (this.quantity(item.skuCode) === 0 || this.boxCount(item.skuCode) > 0)); },
unitLabel() { return this.unitType === 'PALLET' ? '托盘码' : this.unitType === 'BOX' ? '箱号/箱唛' : '包裹码/快递单号' },
unitPlaceholder() { return this.unitType === 'PALLET' ? '扫描托盘标签' : this.unitType === 'BOX' ? '扫描箱唛或录入箱号' : '扫描包裹面单或录入包裹码' }
,palletVolume() { const l = Number(this.palletLength) || 0; const w = Number(this.palletWidth) || 0; const h = Number(this.palletHeight) || 0; return l > 0 && w > 0 && h > 0 ? (l * w * h).toFixed(2) : '—' }
,palletVolume() { const l = Number(this.palletLength) || 0; const w = Number(this.palletWidth) || 0; const h = Number(this.palletHeight) || 0; return l > 0 && w > 0 && h > 0 ? (l * w * h / 1000000).toFixed(6) : '—' }
},
onShow() { if (!requireSession()) return; this.user = session.currentUser; restoreWarehouseWork(`${this.user.id}:${this.user.warehouseId}`); this.entryMode = 'SKU'; this.startScanner(); if (warehouseWork.returnReceipt.currentReturnNo && !this.current && !this.busy) this.openOrder(warehouseWork.returnReceipt.currentReturnNo, 'SKU', false) },
onShow() { if (!requireSession()) return; this.user = session.currentUser; restoreWarehouseWork(`${this.user.id}:${this.user.warehouseId}`); this.entryMode = 'SKU'; if (this.receiptDomain === 'customer') this.startScanner(); if (this.receiptDomain === 'customer' && warehouseWork.returnReceipt.currentReturnNo && !this.current && !this.busy) this.openOrder(warehouseWork.returnReceipt.currentReturnNo, 'SKU', false) },
onHide() { this.stopScanner() }, onUnload() { this.stopScanner() }, beforeUnmount() { this.stopScanner() },
methods: {
switchDomain(value) { if (this.busy || this.receiptDomain === value) return; this.stopScanner(); this.receiptDomain = value; if (value === 'customer') this.startScanner() },
goCount() { const mark = this.result?.labels?.[0]?.cartonMark; if (mark) uni.navigateTo({ url: '/pages/return-counting/return-counting?cartonMark=' + encodeURIComponent(mark) }) },
selectUnitType(type) { if (this.busy) return; this.unitType = type; this.unitCode = ''; this.boxRows = [{ items: {}, length: '', width: '', height: '', weight: '', originalPackaging: true, confirmed: false }]; this.palletCheck = null; this.activeTarget = type === 'PALLET' ? 'pallet' : 'unit' },
resizeBoxRows(raw) { if (this.busy) return; const count = Math.floor(Number(raw) || 0); if (count < 1 || count > 100) return; this.boxRows = Array.from({ length: count }, (_, index) => this.boxRows[index] || { items: {}, length: '', width: '', height: '', weight: '', originalPackaging: true, confirmed: false }) },
setOriginalPackaging(index, value) { if (this.busy) return; this.boxRows[index].originalPackaging = value; this.boxRows[index].confirmed = false },
rowVolume(box) { const v = Number(box?.length) * Number(box?.width) * Number(box?.height); return Number.isFinite(v) && v > 0 ? v.toFixed(2) : '—' },
rowVolume(box) { const v = Number(box?.length) * Number(box?.width) * Number(box?.height); return Number.isFinite(v) && v > 0 ? (v / 1000000).toFixed(6) : '—' },
setBoxQuantity(index, skuCode, raw) { if (this.busy) return; this.boxRows[index].items = { ...this.boxRows[index].items, [skuCode]: raw }; this.boxRows[index].confirmed = false },
boxRemaining(index, item) { const allocated = this.boxRows.reduce((sum, box, rowIndex) => sum + (rowIndex === index ? 0 : Math.max(0, Number(box.items[item.skuCode]) || 0)), 0); return Math.max(0, this.remaining(item) - allocated) },
boxRowValid(index) {
@@ -129,7 +141,7 @@
printPallet() { if (!this.newPalletHtml) return; /* #ifdef H5 */ const view = window.open('', '_blank'); if (view) { view.document.write(this.newPalletHtml); view.document.close(); view.focus(); view.print() } else this.setError(new Error('请允许打开标签打印窗口'), '打印失败'); /* #endif */ /* #ifndef H5 */ this.setError(new Error('当前设备未配置打印服务'), '打印失败'); /* #endif */ },
printReturnCarton(label) { if (!label?.printableHtml) return; /* #ifdef H5 */ const view = window.open('', '_blank'); if (view) { view.document.write(label.printableHtml); view.document.close(); view.focus(); view.print() } else this.setError(new Error('请允许打开标签打印窗口'), '打印失败'); /* #endif */ /* #ifndef H5 */ this.setError(new Error('当前设备未配置打印服务'), '打印失败'); /* #endif */ },
acceptTracking(raw) { this.trackingNo = String(raw?.detail?.value ?? raw ?? '').trim(); playSuccessSound() },
async confirmReceipt() { if (this.busy) return; const totalBoxCount = this.palletBoxCount; if (this.unitType === 'PALLET' && totalBoxCount <= 0) { this.setError(new Error('请先填写各 SKU 的箱数'), '托盘签收校验失败'); return } if (!this.canConfirm || this.busy || (this.unitType !== 'PALLET' && !this.allBoxRowsConfirmed)) return; if (this.unitType !== 'PALLET' && !this.photoFileIds.length) { this.setError(new Error('请先拍照或上传签收照片,再确认签收入库'), '签收校验失败'); return } const willComplete = this.current.expectedItems.every((item) => (this.unitType !== 'PALLET' ? this.boxRows.reduce((sum, box) => sum + (Number(box.items[item.skuCode]) || 0), 0) : this.quantity(item.skuCode)) >= this.remaining(item)); if (willComplete && !this.photoFileIds.length) { const modal = await new Promise((resolve) => uni.showModal({ title: '缺少退货打托照片', content: '本次签收将完成整单入库,请先拍照并上传后再确认打托。', confirmText: '去拍照', cancelText: '取消', success: resolve })); if (modal?.confirm) this.error = { message: '请先拍照并上传退货打托照片后再确认' }; return }
async confirmReceipt() { if (this.busy) return; const totalBoxCount = this.palletBoxCount; if (this.unitType === 'PALLET' && totalBoxCount <= 0) { this.setError(new Error('请先填写各 SKU 的箱数'), '托盘签收校验失败'); return } if (!this.canConfirm || this.busy || (this.unitType !== 'PALLET' && !this.allBoxRowsConfirmed)) return; const willComplete = this.current.expectedItems.every((item) => (this.unitType !== 'PALLET' ? this.boxRows.reduce((sum, box) => sum + (Number(box.items[item.skuCode]) || 0), 0) : this.quantity(item.skuCode)) >= this.remaining(item)); if (!this.photoFileIds.length && (this.unitType !== 'PALLET' || willComplete)) { uni.showModal({ title: '请先拍照', content: '请先拍照或从相册上传签收照片,再点击确认签收。', showCancel: false, confirmText: '知道了' }); return }
await this.run(async () => {
const rows = this.unitType !== 'PALLET' ? this.boxRows : [null]
let expectedReceivedQuantity = this.current.expectedItems.reduce((sum, item) => sum + Number(item.receivedQuantity || 0), 0)
@@ -228,11 +240,34 @@
.dimension-grid label .dimension-label{display:flex;align-items:center;justify-content:space-between;gap:3px;margin-bottom:3px}.dimension-grid label .dimension-label>text{color:#65768b;font-size:10px;line-height:14px;font-weight:400;white-space:nowrap}.dimension-grid label .dimension-label>.volume-text{margin-left:auto;color:#135ee8;font-size:10px}
.receipt-order-card{padding:10px 14px!important}.receipt-order-card .row-head{align-items:center;margin-bottom:5px}.receipt-order-card .card-title{margin:0;font-size:12px}.receipt-order-card .link-button{margin:0;padding:0;font-size:11px;line-height:24px}.receipt-order-line{display:flex;align-items:center;gap:8px}.receipt-order-line .business-code{flex:1;min-width:0;font-size:12px;line-height:18px;white-space:nowrap;overflow-x:auto;word-break:normal}.receipt-order-line .status-pill{flex-shrink:0;font-size:10px;padding:3px 6px}
.receipt-sku-list .item-card{padding:10px 12px}.receipt-sku-list .row-head{align-items:flex-start;gap:8px}.receipt-sku-list .row-head>view{flex:1;min-width:0}.receipt-sku-list .business-code{font-size:12px;line-height:17px;word-break:break-all}.receipt-sku-list .meta-line{font-size:10px;line-height:15px;margin-top:3px}.receipt-sku-list .remaining-copy{flex-shrink:0;white-space:nowrap;font-size:10px}.sku-quantity-fields{display:flex;gap:14px;margin-top:8px}.sku-quantity-fields .quantity-row{flex:1;min-width:0;gap:6px;margin:0;justify-content:flex-start}.sku-quantity-fields .quantity-row>text{white-space:nowrap;font-size:10px}.sku-quantity-fields .quantity-row .number-input{box-sizing:border-box;width:64px;height:30px;min-height:30px;padding:0 5px;border-radius:6px;font-size:13px}
.candidate-heading .card-title{margin-bottom:0}.candidate-card{width:100%;text-align:left}.select-link{color:#135ee8;font-size:12px;font-weight:800}.field-label{display:block;margin:13px 0 6px;color:#52667e;font-size:11px;font-weight:700}.remaining-copy{color:#e53935;font-size:11px}.quantity-row{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:10px;color:#65768b;font-size:11px}.quantity-row .number-input{width:112px;text-align:center}.summary-bar{position:sticky;bottom:0;z-index:4;display:flex;align-items:center;gap:12px;margin-top:12px;padding:11px 13px;border:1px solid #d8e3f1;border-radius:13px;background:#fff;box-shadow:0 5px 20px rgba(22,55,96,.14)}.summary-bar>view{min-width:70px}.summary-label,.summary-value{display:block}.summary-label{color:#728197;font-size:10px}.summary-value{color:#135ee8;font-size:22px;font-weight:800}.submit-button{margin-top:0}.result-card{text-align:left}.result-carton{display:block;margin:9px 0;color:#135ee8;font-size:20px;font-weight:800;word-break:break-all}.link-button{width:auto}.work-card>.link-button{margin-top:8px;padding-left:0}.success-box .primary{margin-top:14px}.scan-hint{display:block;margin-top:9px;color:#65768b;font-size:11px;text-align:center}
.field-label{display:block;margin:13px 0 6px;color:#52667e;font-size:11px;font-weight:700}.remaining-copy{color:#e53935;font-size:11px}.quantity-row{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:10px;color:#65768b;font-size:11px}.quantity-row .number-input{width:112px;text-align:center}.summary-bar{position:sticky;bottom:0;z-index:4;display:flex;align-items:center;gap:12px;margin-top:12px;padding:11px 13px;border:1px solid #d8e3f1;border-radius:13px;background:#fff;box-shadow:0 5px 20px rgba(22,55,96,.14)}.summary-bar>view{min-width:70px}.summary-label,.summary-value{display:block}.summary-label{color:#728197;font-size:10px}.summary-value{color:#135ee8;font-size:22px;font-weight:800}.submit-button{margin-top:0}.result-card{text-align:left}.result-carton{display:block;margin:9px 0;color:#135ee8;font-size:20px;font-weight:800;word-break:break-all}.link-button{width:auto}.work-card>.link-button{margin-top:8px;padding-left:0}.success-box .primary{margin-top:14px}.scan-hint{display:block;margin-top:9px;color:#65768b;font-size:11px;text-align:center}
.photo-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:12px}.photo-tile{min-width:0;overflow:hidden;border:1px solid #d7e1ef;border-radius:8px}.photo-thumbnail{display:block;width:100%;height:130px;background:#f1f4f8}.photo-name{display:block;padding:6px 8px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:12px;color:#52647c}.photo-tile .link-button{margin:0 8px 6px}
.unit-tabs{display:flex;gap:8px;margin:10px 0}.unit-tab{flex:1!important;min-width:0!important;height:34px!important;min-height:34px!important;margin:0!important;padding:0 10px!important;border:1px solid #d6e1ef!important;border-radius:8px!important;background:#f7f9fc!important;color:#53677f!important;font-size:13px!important;line-height:34px!important}.unit-tab.active{border-color:#135ee8!important;background:#eaf2ff!important;color:#135ee8!important;font-weight:700}
.dimension-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:7px;margin-top:10px}.dimension-grid label>text{display:block;margin-bottom:3px;color:#65768b;font-size:10px}.dimension-grid .number-input{box-sizing:border-box;width:100%;height:34px;padding:0 8px;border:1px solid #d7e1ef;border-radius:7px;color:#24364b;font-size:13px;text-align:center;background:#fff}.dimension-grid .number-input:focus{border-color:#2167e8;box-shadow:0 0 0 2px rgba(33,103,232,.12)}.volume-box{display:flex;align-items:center;justify-content:center;gap:4px;height:34px;padding:0 6px;border:1px solid #b9d3f4;border-radius:7px;color:#65768b;font-size:10px;background:#f4f8ff}.volume-box strong{color:#135ee8;font-size:13px}
.work-card>.row-head .business-code{font-size:16px;line-height:20px}.work-card>.row-head .meta-line{font-size:10px;line-height:15px}.work-card>.row-head .status-pill{padding:4px 7px;font-size:10px}
.physical-unit-card{padding:12px!important;border:1px solid #d8e5f5!important;background:linear-gradient(145deg,#fff 0%,#f7faff 100%);box-shadow:0 4px 12px rgba(30,78,130,.08)}.unit-card-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}.unit-card-tag{padding:3px 7px;border-radius:10px;background:#eaf2ff;color:#135ee8;font-size:10px;font-weight:700}.unit-dimension-grid{margin-top:0}.unit-volume{display:flex;align-items:baseline;justify-content:flex-end;gap:4px;margin-top:7px;color:#728197;font-size:10px}.unit-volume strong{color:#135ee8;font-size:15px}.packaging-choice{display:flex;align-items:center;gap:7px;margin-top:10px;padding-top:9px;border-top:1px solid #e6edf6;color:#52667e;font-size:11px}.packaging-choice>text{flex:1}.choice-button{width:42px!important;min-width:42px!important;height:28px!important;min-height:28px!important;margin:0!important;padding:0!important;border:1px solid #d1ddeb!important;border-radius:7px!important;background:#fff!important;color:#65768b!important;font-size:11px!important;line-height:28px!important}.choice-button.selected{border-color:#135ee8!important;background:#eaf2ff!important;color:#135ee8!important;font-weight:700}
.receipt-quantity-heading{display:flex;align-items:center;flex-wrap:nowrap;gap:8px;margin-bottom:10px}.receipt-quantity-heading .card-title{margin-bottom:0;white-space:nowrap}.unit-count-row{display:flex;align-items:center;gap:6px;margin-left:auto;flex-shrink:0;white-space:nowrap;color:#65768b;font-size:10px}.unit-count-row .number-input{box-sizing:border-box;width:48px;min-width:48px;height:30px;min-height:30px;margin:0;padding:0 4px;border-radius:6px;text-align:center;font-size:13px}.quantity-row .unit-quantity-input{width:88px;flex-shrink:0;font-size:12px}.physical-unit-card .quantity-row>text{min-width:0;overflow-wrap:anywhere}.unit-card-head .link-button{margin:0;padding:0;font-size:10px}
@import '../../styles/task-list.scss';
.receipt-page{display:flex;flex-direction:column}
.receipt-page :deep(.portal-header-shell){flex-shrink:0}
.receipt-page>.work-scroll{flex:1;height:0;min-height:0}
.receipt-page .work-content{padding-bottom:calc(24px + env(safe-area-inset-bottom))}
.receipt-page .summary-bar{position:static;margin-bottom:10px}
.receipt-domain-tabs{display:flex;flex-shrink:0;gap:4px;margin:10px 14px 0;padding:4px;border:1px solid #d8e4f5;border-radius:10px;background:#e8eff9}
.receipt-domain-tab{box-sizing:border-box;flex:1;min-width:0;min-height:40px;margin:0;padding:0 8px;border-radius:7px;color:#52677f;background:transparent;font-size:14px;line-height:40px}
.receipt-domain-tab::after{border:0}
.receipt-domain-tab.active{color:#135ee8;background:#fff;font-weight:700;box-shadow:0 1px 5px rgba(28,69,121,.1)}
.receipt-domain-tab[disabled]{opacity:.6}
.summary-bar>.receipt-action-buttons{display:flex;flex:1;min-width:0;gap:8px}
.receipt-action-buttons>.primary,.receipt-action-buttons>.secondary{flex:1;min-width:0;width:auto;margin:0;padding:0 6px;white-space:nowrap}
.receipt-lookup-page{background:#f1f5fd}
.receipt-lookup-page .work-content{padding-top:14px}
.receipt-lookup-card,.receipt-candidate-empty{box-shadow:none}
.receipt-lookup-card .card-title{margin-bottom:10px;font-size:14px;line-height:20px}
.receipt-lookup-card .receipt-lookup-button{min-height:40px;margin-top:10px;font-size:13px;line-height:40px}
.receipt-lookup-page .section-gap{margin-top:0}
.receipt-candidate-card .pda-task-head{align-items:flex-start}
.receipt-candidate-card[disabled]{opacity:.6}
.receipt-candidate-card .receipt-status-active{color:#135ee8;background:#e4efff}
</style>
@@ -106,7 +106,7 @@
</template>
</template>
<view v-if="error" class="transfer-error" role="alert"><text class="feedback-title">操作失败</text><text>{{ error.message || error }}</text><text v-if="error.requestId">requestId:{{ error.requestId }}</text></view>
<view v-if="error" class="transfer-error" role="alert"><text class="feedback-title">操作失败</text><text>{{ simpleErrorMessage(error) }}</text></view>
<view v-if="success" class="transfer-success" role="status"><text class="feedback-title">提交成功</text><text>测量与托盘打托已完成</text></view>
<view v-if="completedPallets.length" class="print-card">
<view class="photo-head"><view><text class="measure-title">新托盘标签</text><text class="measure-hint">{{ completedDestinationLabel }} · 逐托打开 PDF 后打印并粘贴</text></view></view>
@@ -204,6 +204,7 @@ export default {
onHide() { this.stopScanner() },
beforeUnmount() { this.stopScanner() },
methods: {
simpleErrorMessage(error) { return String(error?.message || error || '操作失败,请重试').replace(/[((]\s*(?:错误码|code|requestId|traceId)\s*[::=][\s\S]*$/i, '').replace(/(?:requestId|traceId)\s*[::=][\s\S]*$/i, '').trim() || '操作失败,请重试' },
// 快照只包含业务数据;复制、批量修改或改托后会自动失效并重新展开。
cartonConfirmationSignature(box) {
return JSON.stringify({ pallet: String(box.transferPalletId || ''), dimensions: [box.length, box.width, box.height, box.weight].map(Number), items: box.items.map(line => [line.skuCode, Number(line.quantity)]) })
+3 -1
View File
@@ -48,12 +48,14 @@ export function receivingProgress(session = receiving.current) {
export function setCurrentReceiving(value, owner = '') {
const nextOwner = photoOwner(value, owner)
const previous = previewOwner && previewOwner === nextOwner ? receiving.photoSlots : []
const keepUnsigned = receiving.current?.status === 'WAIT_SIGN' && value?.status === 'WAIT_SIGN'
previewOwner = nextOwner
receiving.current = value || null
receiving.selected = value || null
receiving.photoSlots = RECEIVING_PHOTO_ROLES.map((role) => {
const photo = (value?.photos || []).find((item) => item.role === role)
if (!photo) return null
// 相机返回会重新读取 current;签收前已上传的文件尚未绑定,保留同一身份、同一柜会话的草稿。
if (!photo) return keepUnsigned ? previous.find(item => item?.role === role && item.fileId) || null : null
const old = previous.find(item => item?.role === role && String(item.fileId) === String(photo.fileId)
&& item.downloadPath === photo.downloadPath)
return old || { ...photo, fileId: String(photo.fileId), role, localPath: '', uploaded: true, status: 'idle' }
+61 -13
View File
@@ -1,3 +1,5 @@
import appManifest from '@/manifest.json'
const updateEndpoint = String(import.meta.env.VITE_PDA_UPDATE_URL || '').trim()
let checking = false
@@ -15,20 +17,40 @@ function getRuntimeInfo() {
return
}
// 标准真机基座的版本属于 HBuilderX;调试更新按当前工程版本模拟。
const debugBase = import.meta.env.DEV || uni.getAppBaseInfo().packageName === 'io.dcloud.HBuilder'
const runtime = {
appid: String((debugBase ? appManifest.appid : plus.runtime.appid) || ''),
appVersion: String((debugBase ? appManifest.versionName : plus.runtime.version) || ''),
appVersionCode: Number(debugBase ? appManifest.versionCode : plus.runtime.versionCode)
}
if (!runtime.appid || !runtime.appVersion || !Number.isInteger(runtime.appVersionCode) || runtime.appVersionCode < 1) {
reject(new Error('无法读取当前应用版本,请重新运行 App'))
return
}
if (debugBase) {
resolve({ ...runtime, wgtVersion: runtime.appVersion })
return
}
// 正式 APK 始终保留原生基座版本码,WGT 升级只改变资源版本。
plus.runtime.getProperty(plus.runtime.appid, (properties) => {
resolve({
appid: plus.runtime.appid,
appVersion: String(plus.runtime.version || ''),
appVersionCode: Number(plus.runtime.versionCode || 0),
wgtVersion: String(properties?.version || plus.runtime.version || '')
})
resolve({ ...runtime, wgtVersion: String(properties?.version || runtime.appVersion) })
})
})
}
function normalizeUpdate(payload, runtime) {
const value = payload && typeof payload === 'object' ? payload : {}
if (value.update !== true) return null
if ('code' in value && String(value.code) !== '200') {
const error = new Error(String(value.message || '检查更新失败,请稍后重试'))
error.code = value.code
error.requestId = value.requestId
error.traceId = value.traceId
throw error
}
if (typeof value.update !== 'boolean') throw new Error('更新服务返回了无效的版本信息')
if (!value.update) return null
if (value.appid !== runtime.appid) throw new Error('更新包与当前应用不匹配')
const packageType = String(value.packageType || '').toLowerCase()
@@ -110,20 +132,45 @@ function downloadUpdate(update) {
})
}
function prepareUpdateFile(filePath, update) {
return new Promise((resolve, reject) => {
const fail = (cause) => {
const error = new Error('更新包文件准备失败,请重新下载')
error.stage = 'prepare'
error.code = cause?.code
reject(error)
}
// 下载接口以 /package 结尾,临时文件可能没有安装器要求的扩展名。
const filename = `overseas-pda-${update.versionName}-${Date.now()}.${update.packageType}`
plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
entry.getParent((parent) => {
entry.moveTo(parent, filename, (file) => resolve(file.toLocalURL()), fail)
}, fail)
}, fail)
})
}
function installUpdate(filePath) {
return new Promise((resolve, reject) => {
plus.runtime.install(
filePath,
{ force: false },
resolve,
() => reject(new Error('更新包安装失败,请重新下载'))
(cause) => {
const code = cause?.code == null ? '' : `(${cause.code})`
const reason = String(cause?.message || '请重新下载后重试')
const error = new Error(`更新包安装失败${code}:${reason}`)
error.stage = 'install'
error.code = cause?.code
reject(error)
}
)
})
}
function showFailure(error, mandatory) {
const message = error?.message || '检查更新失败,请稍后重试'
if (!mandatory) {
if (!mandatory && error?.stage !== 'install' && error?.stage !== 'prepare') {
uni.showToast({ title: message, icon: 'none', duration: 3000 })
return Promise.resolve(false)
}
@@ -132,9 +179,9 @@ function showFailure(error, mandatory) {
uni.showModal({
title: '更新失败',
content: message,
confirmText: '重新尝试',
confirmText: mandatory ? '重新尝试' : '知道了',
showCancel: false,
complete: () => resolve(true)
complete: () => resolve(mandatory)
})
})
}
@@ -145,7 +192,8 @@ async function runUpdate(update) {
try {
const filePath = await downloadUpdate(update)
await installUpdate(filePath)
const installPath = await prepareUpdateFile(filePath, update)
await installUpdate(installPath)
if (update.packageType === 'wgt') {
uni.showModal({
title: '更新完成',
@@ -184,7 +232,7 @@ export async function checkForAppUpdate({ manual = false } = {}) {
})
if (response.statusCode !== 200) throw new Error('更新服务暂时不可用')
const update = normalizeUpdate(response.data?.data ?? response.data, runtime)
const update = normalizeUpdate(response.data, runtime)
if (update && isNewerUpdate(update, runtime)) {
await runUpdate(update)
} else if (manual) {
+218
View File
@@ -1,9 +1,82 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
const read = (path) => readFile(new URL(path, import.meta.url), 'utf8')
async function createUpdater({ development = true, packageName = 'io.dcloud.HBuilder',
manifest = { appid: '__UNI__936D079', versionName: '0.0.4', versionCode: 4 },
runtime = {}, resourceVersion = '0.0.4', response = { update: false }, acceptUpdate = false,
downloadResult = { statusCode: 200, tempFilePath: '_doc/temp/download/package' },
fileErrorAt, installError } = {}) {
const calls = { requests: [], modals: [], toasts: [], downloads: [], moves: [], installs: [], restarts: 0 }
const source = (await read('../src/utils/app-update.js'))
.replace(/^import .*$/gm, '')
.replaceAll('import.meta.env.VITE_PDA_UPDATE_URL', 'updateUrl')
.replaceAll('import.meta.env.DEV', 'development')
.replace('export async function checkForAppUpdate', 'async function checkForAppUpdate')
const updater = runInNewContext(`${source}\n;({ getRuntimeInfo, checkForAppUpdate })`, {
appManifest: manifest, development, updateUrl: 'https://updates.example.test/pda/overseas/latest',
plus: {
io: {
resolveLocalFileSystemURL(path, success, fail) {
const fileError = { code: 10, message: 'file operation failed' }
if (fileErrorAt === 'resolve') return fail(fileError)
const parent = {}
success({
getParent(success, fail) { fileErrorAt === 'parent' ? fail(fileError) : success(parent) },
moveTo(destination, name, success, fail) {
assert.equal(destination, parent)
calls.moves.push({ path, name })
if (fileErrorAt === 'move') return fail(fileError)
success({ toLocalURL: () => `_doc/temp/download/${name}` })
}
})
}
},
runtime: { appid: 'HBuilder', version: '5.24.0', versionCode: 52400,
getProperty(_appid, callback) { callback({ version: resourceVersion }) },
install(path, options, success, fail) {
calls.installs.push({ path, options })
if (installError) return fail(installError)
if (!/\.(wgt|apk)$/.test(path)) return fail({ code: -1201, message: 'WGT/WGTU文件格式错误' })
success()
},
restart() { calls.restarts += 1 }, ...runtime
}
},
uni: {
getAppBaseInfo: () => ({ packageName }),
request(options) {
calls.requests.push(options)
options.success({ statusCode: 200, data: typeof response === 'function' ? response(options.data) : response })
},
downloadFile(options) {
calls.downloads.push(options)
options.success(downloadResult)
options.complete()
return { onProgressUpdate() {} }
},
showLoading() {}, hideLoading() {},
showModal(options) {
calls.modals.push(options)
options.success?.({ confirm: acceptUpdate && options.confirmText === '立即更新' })
options.complete?.()
},
showToast(options) { calls.toasts.push(options) }
}
})
return { ...updater, calls }
}
const publishedApk = { update: true, appid: '__UNI__936D079', packageType: 'apk',
versionName: '0.0.5', versionCode: 5, minAppVersionCode: 5,
downloadUrl: 'https://updates.example.test/overseas-0.0.5.apk', mandatory: false }
const publishedWgt = { ...publishedApk, packageType: 'wgt', minAppVersionCode: 4,
downloadUrl: 'https://updates.example.test/overseas-0.0.5.wgt', releaseNotes: '更新测试' }
test('App-Plus checks the independent overseas update channel after launch', async () => {
const [app, updater, env] = await Promise.all([
read('../src/App.vue'),
@@ -53,3 +126,148 @@ test('overseas profile exposes manual App update checking and the runtime versio
assert.match(profile, /checkForAppUpdate\(\{ manual: true \}\)/)
assert.match(profile, /#ifndef APP-PLUS[\s\S]*?请在 PDA App 中检查更新/)
})
test('HBuilderX 0.0.4 checks the project version and offers a published 0.0.5 APK', async () => {
const updater = await createUpdater({ response: query => query.appVersionCode < 5 ? publishedApk : { update: false } })
await updater.checkForAppUpdate({ manual: true })
const query = updater.calls.requests[0].data
assert.equal(query.appid, '__UNI__936D079')
assert.equal(query.appVersion, '0.0.4')
assert.equal(query.appVersionCode, 4)
assert.equal(query.wgtVersion, '0.0.4')
assert.equal(updater.calls.modals[0]?.title, '发现更新 0.0.5')
assert.equal(updater.calls.toasts.length, 0)
})
test('standard HBuilder base uses project versions when running production WGT resources', async () => {
const updater = await createUpdater({ development: false })
const info = await updater.getRuntimeInfo()
assert.equal(info.appid, '__UNI__936D079')
assert.equal(info.appVersionCode, 4)
assert.equal(info.appVersion, '0.0.4')
})
test('released APK keeps its native base version after a WGT version increase', async () => {
const updater = await createUpdater({ development: false, packageName: 'com.baiyuelogistics.pda.overseas',
manifest: { appid: '__UNI__936D079', versionName: '0.0.5', versionCode: 5 },
runtime: { appid: '__UNI__936D079', version: '0.0.4', versionCode: 4 }, resourceVersion: '0.0.5' })
const info = await updater.getRuntimeInfo()
assert.equal(info.appVersionCode, 4)
assert.equal(info.appVersion, '0.0.4')
assert.equal(info.wgtVersion, '0.0.5')
})
test('HBuilderX 0.0.4 can detect a compatible published 0.0.5 WGT', async () => {
const updater = await createUpdater({ response: publishedWgt })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.requests[0].data.appVersionCode, 4)
assert.equal(updater.calls.requests[0].data.wgtVersion, '0.0.4')
assert.equal(updater.calls.modals[0]?.title, '发现更新 0.0.5')
assert.equal(updater.calls.modals[0]?.content, '更新测试')
})
test('released APK 0.0.4 shows the published 0.0.5 WGT release notes', async () => {
const updater = await createUpdater({ development: false, packageName: 'com.baiyuelogistics.pda.overseas',
runtime: { appid: '__UNI__936D079', version: '0.0.4', versionCode: 4 }, response: publishedWgt })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.modals[0]?.title, '发现更新 0.0.5')
assert.equal(updater.calls.modals[0]?.content, '更新测试')
})
test('an APK 0.0.4 with WGT 0.0.5 does not offer that WGT again', async () => {
const updater = await createUpdater({ development: false, packageName: 'com.baiyuelogistics.pda.overseas',
runtime: { appid: '__UNI__936D079', version: '0.0.4', versionCode: 4 },
resourceVersion: '0.0.5', response: publishedWgt })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.modals.length, 0)
assert.equal(updater.calls.toasts[0]?.title, '当前已是最新版本')
})
test('a WGT requiring APK 5 is rejected on a released APK 4 after resource updates', async () => {
const updater = await createUpdater({ development: false, packageName: 'com.baiyuelogistics.pda.overseas',
manifest: { appid: '__UNI__936D079', versionName: '0.0.5', versionCode: 5 },
runtime: { appid: '__UNI__936D079', version: '0.0.4', versionCode: 4 },
resourceVersion: '0.0.5', response: { ...publishedWgt, versionName: '0.0.6', minAppVersionCode: 5 } })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.modals.length, 0)
assert.equal(updater.calls.toasts[0]?.title, '当前安装包不支持此热更新,请安装新版 APK')
})
test('an unreadable native APK version is reported instead of claiming the latest version', async () => {
const updater = await createUpdater({ development: false, packageName: 'com.baiyuelogistics.pda.overseas',
runtime: { appid: '__UNI__936D079', version: '0.0.4', versionCode: 0 } })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.requests.length, 0)
assert.equal(updater.calls.toasts[0]?.title, '无法读取当前应用版本,请重新运行 App')
})
test('update service business errors are shown instead of claiming the latest version', async () => {
const updater = await createUpdater({ response: { code: 'S0503', message: 'PDA 发布通道未初始化', data: null } })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.toasts[0]?.title, 'PDA 发布通道未初始化')
assert.equal(updater.calls.modals.length, 0)
})
test('invalid update responses are rejected instead of claiming the latest version', async () => {
const updater = await createUpdater({ response: {} })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.toasts[0]?.title, '更新服务返回了无效的版本信息')
})
test('unpublished versions remain unavailable to the device', async () => {
const updater = await createUpdater({ response: { update: false } })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.modals.length, 0)
assert.equal(updater.calls.toasts[0]?.title, '当前已是最新版本')
})
test('a downloaded extensionless WGT is renamed before install and restarts on success', async () => {
const updater = await createUpdater({ response: publishedWgt, acceptUpdate: true })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.downloads[0]?.url, publishedWgt.downloadUrl)
assert.equal(updater.calls.moves[0]?.path, '_doc/temp/download/package')
assert.match(updater.calls.moves[0]?.name, /^overseas-pda-0\.0\.5-\d+\.wgt$/)
assert.equal(updater.calls.installs[0]?.path, `_doc/temp/download/${updater.calls.moves[0].name}`)
assert.equal(updater.calls.installs[0]?.options.force, false)
assert.equal(updater.calls.modals[1]?.title, '更新完成')
assert.equal(updater.calls.restarts, 1)
})
test('an extensionless APK receives the APK suffix and does not restart as a WGT', async () => {
const updater = await createUpdater({ response: publishedApk, acceptUpdate: true })
await updater.checkForAppUpdate({ manual: true })
assert.match(updater.calls.installs[0]?.path, /\.apk$/)
assert.equal(updater.calls.installs[0]?.options.force, false)
assert.equal(updater.calls.restarts, 0)
})
test('native installation errors remain visible with their actual reason and code', async () => {
const updater = await createUpdater({ response: publishedWgt, acceptUpdate: true,
installError: { code: -1205, message: 'WGT安装包中manifest.json文件的version版本不匹配' } })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.modals[1]?.title, '更新失败')
assert.match(updater.calls.modals[1]?.content, /-1205/)
assert.match(updater.calls.modals[1]?.content, /version版本不匹配/)
assert.equal(updater.calls.restarts, 0)
assert.equal(updater.calls.installs.length, 1)
})
test('unreadable or unrenamable downloads never reach the native installer', async () => {
for (const fileErrorAt of ['resolve', 'parent', 'move']) {
const updater = await createUpdater({ response: publishedWgt, acceptUpdate: true, fileErrorAt })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.installs.length, 0, fileErrorAt)
assert.equal(updater.calls.restarts, 0, fileErrorAt)
assert.equal(updater.calls.modals[1]?.title, '更新失败', fileErrorAt)
assert.match(updater.calls.modals[1]?.content, /更新包文件准备失败/, fileErrorAt)
}
})
test('an unsuccessful HTTP download never prepares or installs an update', async () => {
const updater = await createUpdater({ response: publishedWgt, acceptUpdate: true,
downloadResult: { statusCode: 404, tempFilePath: '_doc/temp/download/package' } })
await updater.checkForAppUpdate({ manual: true })
assert.equal(updater.calls.moves.length, 0)
assert.equal(updater.calls.installs.length, 0)
assert.match(updater.calls.toasts[0]?.title, /下载失败(404)/)
})
+48
View File
@@ -0,0 +1,48 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { pickDispatchItem } from '../src/api/fulfillment.js'
import { session } from '../src/stores/session.js'
const path = '/api/pda/v1/last-leg/storage-rent/preparations'
const pick = '/api/pda/v1/last-leg/dispatches/PC1/items/9007199254740995/pick'
const body = { recordVersion: '9007199254740993', positionId: '9007199254740994', packages: 2, productQuantity: 0, cartonMark: null, idempotencyKey: 'dispatch-rent-1' }
const ready = { data: { preparationId: 'rent1', ready: true, status: 'READY' } }
const pending = { data: { preparationId: 'rent1', ready: false, status: 'FREEZE_PENDING' } }
const submit = () => pickDispatchItem('PC1', '9007199254740995', body)
function transport(responses) {
const calls = []; session.apiBase = '/api'; session.token = 'overseas-token'
globalThis.uni = { request(options) {
calls.push({ method: options.method, url: options.url, data: options.data })
const response = responses.shift(); assert.ok(response, 'unexpected request')
if (response.network) return options.fail({ errMsg: 'network down' })
options.success({ statusCode: 200, data: { code: '200', ...response }, header: {} })
} }
return calls
}
test('排车仓租与实际拣货绑定同一来源、数量和幂等键,保持长ID精度', async () => {
const calls = transport([ready, { data: { success: true } }]); await submit()
assert.deepEqual(calls, [
{ method: 'POST', url: path, data: { mode: 'DISPATCH', businessNo: 'PC1', itemId: '9007199254740995', positionId: body.positionId, packages: 2, cartonMark: null, idempotencyKey: body.idempotencyKey, productQuantity: 0 } },
{ method: 'POST', url: pick, data: body }
])
})
test('免租或不计租仍按后端就绪结果继续,非布尔就绪禁止拣货', async () => {
const calls = transport([{ data: { ready: true, status: 'NOT_REQUIRED' } }, { data: {} }]); await submit(); assert.equal(calls.at(-1).url, pick)
const blocked = transport([{ data: { ready: 'true' } }]); await assert.rejects(submit(), /预校验/); assert.equal(blocked.length, 1)
})
test('预占待回执只读查询,就绪后仅发一次拣货', async t => {
t.mock.method(globalThis, 'setTimeout', callback => { callback(); return 0 })
const calls = transport([pending, ready, { data: {} }]); await submit()
assert.deepEqual(calls.map(c => [c.method, c.url]), [['POST', path], ['GET', path + '/rent1'], ['POST', pick]])
})
test('资金失败释放预占;预校验404或断网不绕过,不发拣货', async () => {
const calls = transport([{ data: { preparationId: 'rent1', ready: false, status: 'FAILED', message: '余额不足' } }, { data: {} }])
await assert.rejects(submit(), /余额不足/); assert.deepEqual(calls.map(c => c.method), ['POST', 'DELETE'])
for (const failure of [{ code: 'A0404', message: 'missing', requestId: 'req1' }, { network: true }]) {
const failed = transport([failure]); await assert.rejects(submit(), e => failure.network ? e.network : e.code === failure.code && e.requestId === 'req1'); assert.equal(failed.length, 1)
}
})
test('拣货请求发出后结果不明,不重发也不释放可能已消费的预占', async () => {
const calls = transport([ready, { network: true }]); await assert.rejects(submit(), e => e.network)
assert.deepEqual(calls.map(c => c.method), ['POST', 'POST'])
})
+21 -1
View File
@@ -211,12 +211,32 @@ test('missing appointment blocks approval while preserving rejection to customer
storage(); const sent = []
const state = page({ reviewDispatchLoading: async (...args) => { sent.push(args); return proof(lastCommand) }, getDispatchTask: async () => task({ recordVersion: 1 }) })
state.current = reviewTask({ actions: { LOADING_REVIEW: { allowed: true, blockCode: 'APPROVAL_BLOCKED', blockReason: '预约收货时间尚未确认' } } })
assert.equal(state.reviewTime('2026-10-21T17:00:00Z'), '2026-10-22 01:00')
assert.equal(state.reviewTime('2026-10-21T17:00:00Z'), '美东 2026-10-21 13:00\n美西 2026-10-21 10:00')
assert.equal(state.reviewTime(null), '未填写')
state.reviewReason = '请客服补齐预约时间'
await state.submitReview('APPROVED'); assert.equal(sent.length, 0); assert.match(state.error.message, /预约收货时间尚未确认/)
await state.submitReview('REJECTED'); assert.equal(sent.length, 1); assert.equal(sent[0][1].decision, 'REJECTED')
})
for (const [instant, expected] of [
['2026-11-06T00:00:00+08:00', '美东 2026-11-05 11:00\n美西 2026-11-05 08:00'],
['2026-11-05T16:00:00Z', '美东 2026-11-05 11:00\n美西 2026-11-05 08:00'],
['2026-07-01T15:00:00Z', '美东 2026-07-01 11:00\n美西 2026-07-01 08:00'],
['2026-03-08T06:30:00Z', '美东 2026-03-08 01:30\n美西 2026-03-07 22:30'],
['2026-03-08T07:30:00Z', '美东 2026-03-08 03:30\n美西 2026-03-07 23:30'],
['2026-03-08T10:30:00Z', '美东 2026-03-08 06:30\n美西 2026-03-08 03:30'],
['2026-11-01T05:30:00Z', '美东 2026-11-01 01:30\n美西 2026-10-31 22:30'],
['2026-11-01T07:30:00Z', '美东 2026-11-01 02:30\n美西 2026-11-01 00:30'],
['2026-11-01T10:30:00Z', '美东 2026-11-01 05:30\n美西 2026-11-01 02:30'],
]) test(`review times use eastern and pacific daylight-saving rules for ${instant}`, () => {
assert.equal(page().reviewTime(instant), expected)
})
test('review times preserve missing values and reject invalid or timezone-free timestamps', () => {
const state = page()
for (const missing of [null, undefined, '']) assert.equal(state.reviewTime(missing), '未填写')
for (const invalid of ['not-a-date', 'invalidZ', '2026-11-06T00:00:00', '2026-11-06']) assert.equal(state.reviewTime(invalid), '时间无效')
})
test('review task is reachable in the existing list and blocks actual source selection until approval', async () => {
storage(); const state = page({ listDispatchTasks: async () => [reviewTask()], getDispatchTask: async () => reviewTask() })
await state.loadTasks(); assert.equal(state.tasks.length, 1); assert.equal(state.stageLabel(state.tasks[0]), '待理货审核')
+10 -8
View File
@@ -3,15 +3,15 @@ import assert from 'node:assert/strict'
import { pickDispatchItem, pickOutboundTask, pickOutboundPallet, confirmCargoDiscard } from '../src/api/fulfillment.js'
import { session } from '../src/stores/session.js'
// 模拟当前生产:仓租预检查接口不存在,既有库存命令仍正常受理。
// 排车拣货先完成仓租预校验,再提交同一份库存命令。
function transport(failure) {
const calls = []
session.apiBase = '/api'; session.token = 'overseas-token'
globalThis.uni = { request(options) {
calls.push({ method: options.method, url: options.url, data: options.data })
if (failure?.network) return options.fail({ errMsg: 'network down' })
const error = options.url.includes('/storage-rent/') ? { code: 'A0404', message: 'Resource not found' } : failure
options.success({ statusCode: 200, data: error || { code: '200', data: { success: true } }, header: {} })
const rent = options.url.includes('/storage-rent/')
options.success({ statusCode: 200, data: rent ? { code: '200', data: { preparationId: 'rent-1', ready: true, status: 'READY' } } : failure || { code: '200', data: { success: true } }, header: {} })
} }
return calls
}
@@ -27,18 +27,20 @@ const modes = [
]
for (const mode of modes) {
test(`${mode.name} works without the unpublished rent endpoint and preserves its stock payload`, async () => {
test(`${mode.name} preserves its stock payload`, async () => {
const calls = transport()
await mode.submit()
assert.deepEqual(calls, [{ method: 'POST', url: '/api/pda/v1/last-leg' + mode.path, data: mode.body }])
const stock = calls.find(call => call.url.includes(mode.path))
assert.deepEqual(stock, { method: 'POST', url: '/api/pda/v1/last-leg' + mode.path, data: mode.body })
if (mode.name === 'dispatch') assert.equal(calls.filter(call => call.url.includes('/storage-rent/')).length, 1)
})
test(`${mode.name} propagates stock failures without fallback or automatic resubmission`, async () => {
for (const failure of [{ code: 'A0404', message: 'missing' }, { code: 'A0409', message: 'conflict' }, { code: 'S0503', message: 'unavailable' }, { network: true }]) {
const calls = transport(failure)
await assert.rejects(mode.submit(), error => failure.network ? error.network === true : error.code === failure.code)
assert.equal(calls.length, 1)
assert.equal(calls[0].url, '/api/pda/v1/last-leg' + mode.path)
assert.deepEqual(calls[0].data, mode.body)
const stock = calls.find(call => call.url.includes(mode.path))
if (failure.network && mode.name === 'dispatch') assert.equal(stock, undefined)
else assert.deepEqual(stock, { method: 'POST', url: '/api/pda/v1/last-leg' + mode.path, data: mode.body })
}
})
}
+2 -1
View File
@@ -121,6 +121,7 @@ test('fulfillment API calls the frozen list detail pick complete and review rout
else if (options.method === 'GET' && options.url.includes('/dispatches/')) data = { dispatchNo: 'DSP-1', taskNo: 'TASK-1', items: [] }
else if (options.method === 'GET' && options.url.includes('/outbound-tasks/resolve/')) data = { workflow: 'DISPATCH', dispatchNo: 'DSP-1', outboundNo: 'OUT-1' }
else if (options.method === 'GET' && options.url.includes('/outbound-tasks/')) data = { task: { taskNo: 'OUT-TASK-1', outboundNo: 'OUT-1' }, items: [] }
else if (options.method === 'POST' && options.url.includes('/storage-rent/preparations')) data = { preparationId: 'rent-1', ready: true, status: 'READY' }
options.success({ statusCode: 200, data: { code: '200', data }, header: {} })
}
}
@@ -135,7 +136,7 @@ test('fulfillment API calls the frozen list detail pick complete and review rout
await pickOutboundPallet('OUT/TASK/1', 'DP/1', { idempotencyKey: 'out-pallet-key' })
await completeOutboundTask('OUT/TASK/1', { idempotencyKey: 'out-complete-key' })
assert.equal(calls.length, 13)
assert.equal(calls.length, 14)
assert.deepEqual(calls.find(call => call.url.endsWith('/dispatches/DSP%2F1/loading-review')).data, { recordVersion: 0, idempotencyKey: 'review-key', decision: 'REJECTED', reason: '车牌不符' })
assert.ok(calls.some((call) => call.url.endsWith('/dispatches')))
assert.ok(calls.some((call) => call.url.includes('/dispatches/DSP%2F1/items/11/pick')))
+31 -2
View File
@@ -1,7 +1,11 @@
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import assert from 'node:assert/strict'
import { readFile, readdir } from 'node:fs/promises'
import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { loadEnv } from 'vite'
const read = path => readFile(new URL(path, import.meta.url), 'utf8')
test('PDA H5 has no container publishing entry', async () => {
const files = await readdir(new URL('../deploy/', import.meta.url))
@@ -28,10 +32,12 @@ test('host nginx serves uploaded files and proxies only the API prefix', async (
test('only H5 production overrides the toolchain asset base', async () => {
const source = (await read('../vite.config.js'))
.replace(/^import .*$/gm, '')
.replaceAll('import.meta.url', 'configUrl')
.replace('export default ', '')
for (const platform of ['h5', 'app', 'app-plus', 'app-harmony', undefined]) {
for (const mode of ['production', 'development']) {
const factory = runInNewContext(source, {
URL, fileURLToPath, configUrl: new URL('../vite.config.js', import.meta.url).href,
defineConfig: value => value,
loadEnv: () => ({}),
uni: () => ({}),
@@ -45,8 +51,10 @@ test('only H5 production overrides the toolchain asset base', async () => {
})
test('H5 proxy uses the shared gateway prefix and preserves API suffixes', async () => {
const source = (await read('../vite.config.js')).replace(/^import .*$/gm, '').replace('export default ', '')
const source = (await read('../vite.config.js')).replace(/^import .*$/gm, '')
.replaceAll('import.meta.url', 'configUrl').replace('export default ', '')
const factory = runInNewContext(source, {
URL, fileURLToPath, configUrl: new URL('../vite.config.js', import.meta.url).href,
defineConfig: value => value, loadEnv: () => ({ API_PROXY_TARGET: 'https://gateway.example.com' }),
uni: () => ({}), process: { env: { UNI_PLATFORM: 'h5' }, cwd: () => '/project' }
})
@@ -57,3 +65,24 @@ test('H5 proxy uses the shared gateway prefix and preserves API suffixes', async
assert.equal(proxy['/gateway-api'].rewrite(`/gateway-api${suffix}`), `/api${suffix}`)
}
})
test('App update configuration loads from the project when HBuilderX starts elsewhere', async t => {
const fixturePrefix = join(tmpdir(), 'overseas-pda-env-')
const fixtureDir = await mkdtemp(fixturePrefix)
assert.ok(resolve(fixtureDir).startsWith(resolve(fixturePrefix)))
t.after(() => rm(fixtureDir, { recursive: true, force: true }))
const endpoint = 'https://updates.example.test/pda/overseas/latest'
await writeFile(join(fixtureDir, '.env.local'), `VITE_PDA_UPDATE_URL=${endpoint}\n`)
const source = (await read('../vite.config.js')).replace(/^import .*$/gm, '')
.replaceAll('import.meta.url', 'configUrl').replace('export default ', '')
const factory = runInNewContext(source, {
URL, fileURLToPath, configUrl: pathToFileURL(join(fixtureDir, 'vite.config.js')).href,
defineConfig: value => value, loadEnv, uni: () => ({}),
process: { env: { UNI_PLATFORM: 'app' }, cwd: () => join(fixtureDir, 'HBuilderX') }
})
for (const mode of ['development', 'production']) {
const config = factory({ mode })
assert.equal(JSON.parse(config.define['import.meta.env.VITE_PDA_UPDATE_URL']), endpoint)
assert.equal(resolve(config.envDir), resolve(fixtureDir))
}
})
+6 -5
View File
@@ -189,7 +189,7 @@ test('无关联库存按现场箱唛去重计数,提交扫描清单而非手
let payload
const { vm } = page({ confirmCargoDiscard: async (...args) => { payload = args }, listCargoDiscardTasks: async () => [] })
vm.discardCurrent = { discardNo: 'CD-A' }
vm.discardTask = { palletNo: 'P-A', status: 'PENDING', scanMode: 'PALLET', cartonMarks: [], skus: [{ itemId: 'sku', plannedPackages: 10, actualQuantityEditable: true }] }
vm.discardTask = { palletNo: 'P-A', status: 'PENDING', scanMode: 'PALLET', cartonMarks: [], skus: [{ itemId: 'sku', plannedPackages: 10, actualQuantityEditable: true, allowedCartonMarks: ['FIELD-A','FIELD-B','FIELD-C','BOX-1','BOX-2',...Array.from({ length: 10 }, (_, i) => 'FIELD-'+i)] }] }
vm.discardPhotoReady = true; vm.discardPhotos = [{ fileId: '101' }]
for (const value of ['', ' ', null, -1, 11, 1.5, 'abc']) {
vm.discardActuals = { sku: value }; assert.equal(vm.canConfirmDiscard, false)
@@ -204,7 +204,7 @@ test('无关联库存按现场箱唛去重计数,提交扫描清单而非手
})
test('无关联托盘扫码后从零开始,等待扫描现场箱唛', async () => {
const { vm } = page({ resolveCargoDiscardPallet: async () => ({ discardNo: 'CD-A', palletNo: 'P-A', cartonMarks: [], scanMode: 'PALLET', skus: [{ itemId: 'sku', plannedPackages: 10, actualQuantityEditable: true }] }) })
const { vm } = page({ resolveCargoDiscardPallet: async () => ({ discardNo: 'CD-A', palletNo: 'P-A', cartonMarks: [], scanMode: 'PALLET', skus: [{ itemId: 'sku', plannedPackages: 10, actualQuantityEditable: true, allowedCartonMarks: ['FIELD-A','FIELD-B','FIELD-C','BOX-1','BOX-2',...Array.from({ length: 10 }, (_, i) => 'FIELD-'+i)] }] }) })
vm.discardCurrent = { discardNo: 'CD-A' }
await vm.resolveDiscardPallet('P-A')
assert.equal(vm.discardActuals.sku, 0)
@@ -213,13 +213,14 @@ test('无关联托盘扫码后从零开始,等待扫描现场箱唛', async ()
test('无关联任务先扫托盘,再扫现场箱唛自动计数', async () => {
const { vm } = page()
vm.discardTasks = [{ discardNo: 'CD-NO-BOX', palletNo: 'P-1', status: 'PENDING', scanMode: 'PALLET', cartonMarks: [], skus: [{ itemId: 'sku', plannedPackages: 2, actualQuantityEditable: true }] }]
vm.discardTasks = [{ discardNo: 'CD-NO-BOX', palletNo: 'P-1', status: 'PENDING', scanMode: 'PALLET', cartonMarks: [], skus: [{ itemId: 'sku', plannedPackages: 2, actualQuantityEditable: true, allowedCartonMarks: ['FIELD-A','FIELD-B','FIELD-C','BOX-1','BOX-2',...Array.from({ length: 10 }, (_, i) => 'FIELD-'+i)] }] }]
vm.openDiscardOrder('CD-NO-BOX'); await Promise.resolve()
assert.equal(vm.discardTask, null)
await vm.resolveDiscardPallet('P-1')
assert.equal(vm.discardTask.palletNo, 'P-1')
assert.equal(vm.discardActuals.sku, 0)
vm.discardPhotoReady = true; vm.discardPhotos = [{ fileId: '101' }]
await vm.scanDiscardCarton('RANDOM-FOREIGN-BOX'); assert.equal(vm.discardActuals.sku, 0); assert.match(vm.error.message, /不属于/);
await vm.scanDiscardCarton('FIELD-A'); await vm.scanDiscardCarton('FIELD-B')
assert.equal(vm.discardActuals.sku, 2); assert.equal(vm.canConfirmDiscard, true)
})
@@ -434,7 +435,7 @@ test('失败后刷新仍报错,保留草稿且不再发送出库', async () =>
test('无关联扫码显示备注,不能扫托盘或超过目标,失败刷新后保留现场箱唛再提交', async () => {
let attempts = 0
const task = { discardNo: 'CD-FIELD', palletNo: 'PALLET-FIELD', status: 'PENDING', scanMode: 'PALLET', cartonMarks: [], remark: '只废弃破损外箱', remainingPackages: 2, skus: [{ itemId: 'sku', plannedPackages: 8, actualQuantityEditable: true }] }
const task = { discardNo: 'CD-FIELD', palletNo: 'PALLET-FIELD', status: 'PENDING', scanMode: 'PALLET', cartonMarks: [], remark: '只废弃破损外箱', remainingPackages: 2, skus: [{ itemId: 'sku', plannedPackages: 8, actualQuantityEditable: true, allowedCartonMarks: ['FIELD-A','FIELD-B','FIELD-C','BOX-1','BOX-2',...Array.from({ length: 10 }, (_, i) => 'FIELD-'+i)] }] }
const { vm } = page({ confirmCargoDiscard: async () => { if (++attempts === 1) throw new Error('余额不足') }, listCargoDiscardTasks: async () => [] })
vm.discardTasks = [task]; vm.openDiscardOrder(task.discardNo); await vm.resolveDiscardPallet(task.palletNo)
assert.equal(vm.discardOrderRemark, '只废弃破损外箱')
@@ -450,7 +451,7 @@ test('无关联扫码显示备注,不能扫托盘或超过目标,失败刷
test('已扫描现场箱唛可移除并同步回减数量,确认只提交剩余箱唛', async () => {
let payload
const task = { discardNo: 'CD-REMOVE', palletNo: 'P-REMOVE', status: 'PENDING', scanMode: 'PALLET', cartonMarks: [], remainingPackages: 4, skus: [{ itemId: 'sku', plannedPackages: 8, actualQuantityEditable: true }] }
const task = { discardNo: 'CD-REMOVE', palletNo: 'P-REMOVE', status: 'PENDING', scanMode: 'PALLET', cartonMarks: [], remainingPackages: 4, skus: [{ itemId: 'sku', plannedPackages: 8, actualQuantityEditable: true, allowedCartonMarks: ['FIELD-A','FIELD-B','FIELD-C','BOX-1','BOX-2',...Array.from({ length: 10 }, (_, i) => 'FIELD-'+i)] }] }
const { vm } = page({ confirmCargoDiscard: async (...args) => { payload = args }, listCargoDiscardTasks: async () => [] })
vm.discardTasks = [task]; vm.openDiscardOrder(task.discardNo); await vm.resolveDiscardPallet(task.palletNo)
await vm.scanDiscardCarton('BOX-1'); await vm.scanDiscardCarton('BOX-2')
+2 -1
View File
@@ -146,7 +146,8 @@ test('Chinese English and Spanish locale selection is persisted from profile wit
for (const label of ['简体中文', 'English', 'Español']) assert.match(i18n, new RegExp(label))
assert.match(profile, /currentLocale, LOCALE_OPTIONS, setLocale/)
assert.match(profile, /@tap="selectLanguage"[\s\S]*切换语言/)
assert.match(profile, /uni\.showActionSheet[\s\S]*setLocale\(selected\.value\)/)
assert.match(profile, /ref="languagePopup"[\s\S]*role="radiogroup"/)
assert.match(profile, /applyLanguage\(value\)[\s\S]*setLocale\(selected\.value\)/)
assert.match(inbound, /warehouse-profile/)
})
+95 -2
View File
@@ -2,7 +2,7 @@ import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import * as store from '../src/stores/receiving.js'
import { normalizeReceivingSession, toReceivingError } from '../src/api/receiving-adapter.js'
import { normalizeReceivingSession, toReceivingError, RECEIVING_PHOTO_ROLES } from '../src/api/receiving-adapter.js'
const source = readFileSync(new URL('../src/pages/operation/operation.vue', import.meta.url), 'utf8').match(/<script>([\s\S]*?)<\/script>/)[1]
const defer = () => { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b }); return { promise, resolve, reject } }
@@ -13,7 +13,7 @@ const sessionValue = (patch = {}) => normalizeReceivingSession({ containerNo: 'C
function page(overrides = {}) {
const deps = { ...store, session: { tenantId: '100', currentUser: { id: 'operator', warehouseId: '900' } },
PortalHeader: {}, ReceivingSessionSummary: {}, ScanTargetInput: {}, requireSession: () => true,
PortalHeader: {}, ReceivingSessionSummary: {}, ScanTargetInput: {}, RECEIVING_PHOTO_ROLES, requireSession: () => true,
startScanBroadcast: () => () => {}, playErrorSound() {}, playSuccessSound() {},
receivingPhase: store.receivingPhase, toReceivingError: error => error, ...overrides }
const definition = new Function(...Object.keys(deps), source.replace(/^\s*import .*$/gm, '').replace('export default', 'return'))(...Object.values(deps))
@@ -25,6 +25,35 @@ function page(overrides = {}) {
return { vm, definition, deps }
}
test('camera resume retains all unsigned uploads by role and clears them across session or identity changes', async () => {
store.resetReceivingSession()
const unsigned = sessionValue({ status: 'WAIT_SIGN', photos: [], domesticLoadingPhotos: [] })
let nextFile = 10
const { vm, deps } = page({ uploadCurrentUnloadPhoto: async () => ({ fileId: String(++nextFile) }) })
await vm.applyCurrentReceiving(unsigned)
await vm.replacePhoto(0, 'camera:plate')
vm.suspendReceiving(); vm._pageActive = true
await vm.applyCurrentReceiving(structuredClone(unsigned))
await vm.replacePhoto(1, 'camera:seal')
vm.suspendReceiving(); vm._pageActive = true
await vm.applyCurrentReceiving(structuredClone(unsigned))
await vm.replacePhoto(2, 'camera:door')
assert.deepEqual(vm.photoSlots.map(photo => photo.fileId), ['11', '12', '13'])
assert.equal(vm.photosReady, true)
await vm.replacePhoto(1, 'camera:seal-again')
assert.deepEqual(vm.photoSlots.map(photo => photo.fileId), ['11', '14', '13'])
deps.session.currentUser = { ...deps.session.currentUser, id: 'other-operator' }; vm.user = deps.session.currentUser
await vm.applyCurrentReceiving(structuredClone(unsigned))
assert.deepEqual(vm.photoSlots, [null, null, null])
await vm.replacePhoto(0, 'camera:new-owner')
await vm.applyCurrentReceiving({ ...unsigned, preparedAt: '2026-11-05T10:00:00' })
assert.deepEqual(vm.photoSlots, [null, null, null])
await vm.replacePhoto(0, 'camera:new-session')
await vm.applyCurrentReceiving({ ...unsigned, preparedAt: '2026-11-05T10:00:00', status: 'SIGNED' })
assert.deepEqual(vm.photoSlots, [null, null, null])
vm.suspendReceiving()
})
test('same current readback retains three signed previews; collapsed unversioned domestic images issue no downloads', async () => {
store.resetReceivingSession(); const calls = []
const download = async path => { calls.push(path); return `local:${path}` }
@@ -64,6 +93,70 @@ test('editing and rejecting a pallet cannot submit using the previous successful
assert.equal(writes, 0)
})
test('queued pallet scan follows the current step while a pending carton requires confirmation', t => {
store.resetReceivingSession(); store.setCurrentReceiving(sessionValue())
store.receiving.resolvedCarton = { inboundCode: 'IN-A', cartonMark: 'IN-A#1', destinationType: 'OVERSEAS' }
const { vm } = page()
t.after(() => vm.suspendReceiving())
const calls = [], toasts = []
vm.resolvePallet = value => calls.push(['pallet', value])
vm.resolveCarton = value => calls.push(['carton', value])
vm.showToast = message => toasts.push(message)
vm.activeTarget = 'pallet'
vm.dispatchHardwareScan({ value: 'PAL-A', target: 'carton' })
assert.deepEqual(calls, [['pallet', 'PAL-A']])
store.receiving.resolvedPallet = { palletCode: 'PAL-A', compatible: true }
vm.palletInput = 'PAL-A'; vm.activeTarget = 'carton'
vm.dispatchHardwareScan({ value: 'IN-A#2', target: 'carton' })
assert.deepEqual(calls, [['pallet', 'PAL-A']])
assert.deepEqual(toasts, ['请先确认当前箱收货,再扫描下一箱'])
assert.equal(vm.activeInbound.cartonMark, 'IN-A#1')
vm.clearReceiptContext()
vm.dispatchHardwareScan({ value: 'IN-A#2', target: 'pallet' })
assert.deepEqual(calls, [['pallet', 'PAL-A'], ['carton', 'IN-A#2']])
})
test('queued carton remains pending until the current carton receipt is confirmed', async t => {
store.resetReceivingSession(); store.setCurrentReceiving(sessionValue())
store.receiving.resolvedCarton = { inboundCode: 'IN-A', cartonMark: 'IN-A#1', destinationType: 'OVERSEAS' }
store.receiving.resolvedPallet = { palletCode: 'PAL-A', compatible: true }
const { vm } = page()
t.after(() => vm.suspendReceiving())
const parsed = []
vm.resolveCarton = value => parsed.push(value)
vm.palletInput = 'PAL-A'; vm.activeTarget = 'carton'
vm.scanQueue = [{ value: 'IN-A#2', target: 'carton' }]
vm.drainScanQueue()
assert.equal(vm.scanQueue.length, 1)
assert.deepEqual(parsed, [])
vm.clearReceiptContext()
await new Promise(resolve => setTimeout(resolve, 5))
assert.deepEqual(parsed, ['IN-A#2'])
assert.equal(vm.scanQueue.length, 0)
})
test('cannot finish a container while an overseas carton awaits receipt confirmation', async t => {
store.resetReceivingSession(); store.setCurrentReceiving(sessionValue())
store.receiving.resolvedCarton = { inboundCode: 'IN-A', cartonMark: 'IN-A#1', destinationType: 'OVERSEAS' }
store.receiving.resolvedPallet = { palletCode: 'PAL-A', compatible: true }
let completions = 0
const { vm } = page({ completeCurrentReceiving: async () => {
completions++
return sessionValue({ status: 'COMPLETED_WITH_DIFFERENCE' })
} })
t.after(() => vm.suspendReceiving())
vm.applyCurrentReceiving = async () => {}
vm.palletInput = 'PAL-A'; vm.activeTarget = 'carton'
await vm.completeContainer()
assert.equal(completions, 0)
vm.clearReceiptContext()
await vm.completeContainer()
assert.equal(completions, 1)
})
test('an incompatible pallet never reports success and a corrected scan can be validated normally', async t => {
store.resetReceivingSession(); store.setCurrentReceiving(sessionValue())
store.receiving.resolvedCarton = { inboundCode: 'IN-A', cartonMark: 'IN-A#22-1', destinationType: 'FBA' }
+3 -2
View File
@@ -90,10 +90,11 @@ test('domestic cabinet photos are read-only, previewable and non-blocking in sig
assert.doesNotMatch(page, /domesticLoadingPhotos[\s\S]{0,120}customer/)
})
test('fixed receiving action leaves enough scroll-safe space above the PDA bottom bar', () => {
test('receiving finish action remains in document flow after the scan and save controls', () => {
assert.match(page, /v-if="canFinishOnsite" class="sticky-action-dock"><view class="sticky-action one"/)
assert.match(page, /allInboundsReconciled \? '完成整柜入库' : '现场收货结束(标记差异)'/)
assert.match(page, /receiving-content-with-action\{[^}]*padding-bottom:calc\(152px \+ env\(safe-area-inset-bottom,0px\)\)/)
assert.match(page, /sticky-action-dock\{position:static;max-width:none/)
assert.match(page, /receiving-content-with-action\{[^}]*padding-bottom:calc\(24px \+ env\(safe-area-inset-bottom,0px\)\)/)
assert.match(page, /primary-button,\.secondary-button,\.ghost-button\{[^}]*align-items:center;justify-content:center[^}]*line-height:normal;text-align:center/)
assert.match(page, /sticky-action button\{[^}]*align-items:center;justify-content:center;line-height:normal;text-align:center/)
})
+66 -1
View File
@@ -22,6 +22,16 @@ function state(a = '2', b = '2', c = '2') {
return value
}
test('resume card is redundant only when the same receipt task is on the current page', () => {
const activeTask = { receiptNo: 'RR-ACTIVE', palletCode: 'PLT-SHARED' }
const listed = tasks => scope.page.computed.activeTaskListed.call({ activeTask, tasks })
assert.equal(listed([{ ...activeTask }]), true)
assert.equal(listed([{ receiptNo: 'RR-OTHER', palletCode: 'PLT-SHARED' }]), false)
assert.equal(listed([]), false, 'keep resume access when paging away from the active task')
assert.equal(scope.page.computed.activeTaskListed.call({ activeTask: null, tasks: [activeTask] }), false)
assert.equal(scope.page.computed.activeTaskListed.call({ activeTask: {}, tasks: [{}] }), false)
})
test('list entry can confirm without scanning when string wire quantities reconcile', () => {
const value = state()
assert.equal(value.totals[0].quantity, 4)
@@ -40,7 +50,7 @@ test('counting still rejects mismatched totals and invalid box quantities', () =
})
function scanState() {
const value = { task: state().task, tasks: [], error: null, scanCode: '', scanResult: '', selectedMark: '', busy: false,
const value = { task: state().task, tasks: [], error: null, scanCode: '', scanResult: '', selectedMark: '', busy: false, listLoading: false, openingReceiptNo: '',
open(row) { this.task = row }, $nextTick(callback) { callback() } }
value.run = scope.page.methods.run.bind(value)
value.enterTask = scope.page.methods.enterTask.bind(value)
@@ -48,6 +58,61 @@ function scanState() {
return value
}
test('opening a task keeps list counts stable and uses only that task loading state until cancellation', async () => {
const value = scanState()
const row = { receiptNo: 'RR-SELECTED', returnNo: 'RT-SELECTED' }
value.task = null; value.tasks = [row]; value.total = 1
let release, currentReads = 0
const pending = new Promise(resolve => { release = resolve })
scope.getCurrentReturnCountTask = async () => { currentReads++; await pending; return null }
scope.beginReturnCountTask = async () => assert.fail('cancelled selection cannot begin a task')
value.fetchTasks = async () => assert.fail('opening a card cannot refresh the list')
value.ask = async () => ({ confirm: false })
const opening = scope.page.methods.choose.call(value, row)
assert.equal(value.busy, true)
assert.equal(value.listLoading, false)
assert.equal(value.openingReceiptNo, row.receiptNo)
assert.equal(value.total, 1)
assert.equal(value.tasks[0], row)
await scope.page.methods.choose.call(value, { receiptNo: 'RR-SECOND' })
assert.equal(currentReads, 1)
release(); await opening
assert.equal(value.busy, false)
assert.equal(value.openingReceiptNo, '')
assert.equal(value.task, null)
assert.equal(value.tasks[0], row)
})
test('failed task opening releases its indicator and retains list and diagnostic evidence', async () => {
const value = scanState(), row = { receiptNo: 'RR-SELECTED' }
value.task = null; value.tasks = [row]
scope.getCurrentReturnCountTask = async () => { throw Object.assign(new Error('读取任务失败'), { code: 'A0409', requestId: 'REQ', traceId: 'TRACE' }) }
await scope.page.methods.choose.call(value, row)
assert.equal(value.busy, false)
assert.equal(value.listLoading, false)
assert.equal(value.openingReceiptNo, '')
assert.equal(value.tasks[0], row)
assert.equal(value.error.code, 'A0409')
assert.equal(value.error.requestId, 'REQ')
assert.equal(value.error.traceId, 'TRACE')
})
test('explicit list loading owns the refresh indicator and always releases it', async () => {
for (const fails of [false, true]) {
const value = scanState()
let release
const pending = new Promise(resolve => { release = resolve })
value.fetchTasks = async () => { await pending; if (fails) throw new Error('加载失败') }
const loading = scope.page.methods.load.call(value)
assert.equal(value.listLoading, true)
assert.equal(value.openingReceiptNo, '')
release(); await loading
assert.equal(value.busy, false)
assert.equal(value.listLoading, false)
assert.equal(Boolean(value.error), fails)
}
})
test('box and single-batch pallet scans claim and open counting directly without start dialog', async () => {
for (const mark of ['RC#2-1', 'PLT-1']) {
const value = scanState()
+33 -13
View File
@@ -5,6 +5,15 @@ import vm from 'node:vm'
const physicalRow = items => ({ items, length: 10, width: 10, height: 10, weight: 1, originalPackaging: true, confirmed: true })
test('physical volume uses cubic metres while receipt dimensions remain centimetres', () => {
const page = setup(async () => ({}))
assert.equal(page.rowVolume({ length: 30, width: 20, height: 20 }), '0.012000')
assert.equal(page.rowVolume({ length: 1, width: 1, height: 1 }), '0.000001')
assert.equal(page.rowVolume({ length: '', width: 20, height: 20 }), '—')
page.palletLength = 120; page.palletWidth = 100; page.palletHeight = 150
assert.equal(page.palletVolume, '1.800000')
})
test('box and parcel confirmation opens the camera only after every valid row is confirmed', () => {
for (const type of ['BOX', 'PARCEL']) {
const cameras = []
@@ -58,7 +67,7 @@ test('final photo upload waits for explicit confirmation and failed uploads cann
assert.equal(requests.length, 0)
await page.confirmReceipt()
assert.equal(requests.length, failUpload ? 0 : 1)
if (failUpload) assert.match(page.error.message, /照片/)
if (failUpload) assert.equal(page.error.message, 'upload failed')
}
})
@@ -87,13 +96,23 @@ test('parcel photos accumulate without submitting until explicit receipt confirm
assert.equal(page.current, null)
})
test('parcel signing requires a photo even for a partial receipt', async () => {
let requests = 0
const page = setup(async () => { requests++; return {} })
page.unitType = 'PARCEL'; page.boxRows = [physicalRow({ 'SKU-TEST': 2 })]
await page.confirmReceipt()
assert.equal(requests, 0)
assert.match(page.error.message, /照片/)
test('missing receipt photos show a reminder without submitting or adding a page error', async () => {
for (const type of ['BOX', 'PARCEL', 'PALLET']) {
let requests = 0
const modals = []
const page = setup(async () => { requests++; return {} }, new Map(), 'operator:warehouse', {
uni: { showModal: options => modals.push(options) }
})
page.unitType = type; page.boxRows = [physicalRow({ 'SKU-TEST': 10 })]
page.quantity = () => 10; page.remaining = () => 10
await page.confirmReceipt()
assert.equal(requests, 0)
assert.equal(modals.length, 1)
assert.match(modals[0].content, /照片/)
assert.equal(modals[0].showCancel, false)
assert.equal(page.error, undefined)
assert.ok(page.current)
}
})
test('editing the draft before the camera returns prevents late photo submission', async () => {
@@ -111,10 +130,10 @@ test('editing the draft before the camera returns prevents late photo submission
})
function setup(confirm, saved = new Map(), scope = 'operator:warehouse', runtime = {}) {
const context = vm.createContext({ reactive: value => value, ReturnLabelConfirmation: {}, PortalHeader: {}, ScanTargetInput: {},
const context = vm.createContext({ reactive: value => value, ReturnLabelConfirmation: {}, PortalHeader: {}, ScanTargetInput: {}, ExceptionReturnWork: {},
playSuccessSound() {}, playErrorSound() {}, confirmReturnReceipt: confirm,
...runtime,
uni: { setStorageSync: (key, value) => saved.set(key, structuredClone(value)), getStorageSync: key => saved.get(key), removeStorageSync: key => saved.delete(key), ...runtime.uni } })
uni: { showModal() {}, setStorageSync: (key, value) => saved.set(key, structuredClone(value)), getStorageSync: key => saved.get(key), removeStorageSync: key => saved.delete(key), ...runtime.uni } })
const store = readFileSync(new URL('../src/stores/warehouse-work.js', import.meta.url), 'utf8')
vm.runInContext(store.replace(/^import .*$/mg, '').replace(/export /g, ''), context)
const page = readFileSync(new URL('../src/pages/return-receipt/return-receipt.vue', import.meta.url), 'utf8')
@@ -129,13 +148,14 @@ function setup(confirm, saved = new Map(), scope = 'operator:warehouse', runtime
quantity: () => 2, boxCount: () => 1
})
Object.defineProperty(instance, 'allBoxRowsConfirmed', { get: () => component.computed.allBoxRowsConfirmed.call(instance) })
Object.defineProperty(instance, 'palletVolume', { get: () => component.computed.palletVolume.call(instance) })
return instance
}
test('SKU lookup displays all pending order lines while retaining scanned SKU for pallet generation', () => {
const source = readFileSync(new URL('../src/pages/return-receipt/return-receipt.vue', import.meta.url), 'utf8')
const script = source.match(/<script[^>]*>([\s\S]*?)<\/script>/)[1]
const component = vm.runInNewContext(script.replace(/^\s*import .*$/mg, '').replace('export default', 'globalThis.component ='), { ReturnLabelConfirmation: {}, PortalHeader: {}, ScanTargetInput: {} })
const component = vm.runInNewContext(script.replace(/^\s*import .*$/mg, '').replace('export default', 'globalThis.component ='), { ReturnLabelConfirmation: {}, PortalHeader: {}, ScanTargetInput: {}, ExceptionReturnWork: {} })
const lines = [{ skuCode: 'SKU-A', expectedQuantity: 6 }, { skuCode: 'SKU-B', expectedQuantity: 4 }]
const instance = { current: { expectedItems: lines }, selectedSku: 'SKU-A' }
instance.selectedItems = component.computed.selectedItems.call(instance)
@@ -168,7 +188,7 @@ test('PALLET page submits the required palletCode through the actual confirmatio
test('parcel signing allows an empty code but still rejects quantities above the remaining amount', async () => {
const source = readFileSync(new URL('../src/pages/return-receipt/return-receipt.vue', import.meta.url), 'utf8')
const component = vm.runInNewContext(source.match(/<script[^>]*>([\s\S]*?)<\/script>/)[1].replace(/^\s*import .*$/mg, '').replace('export default', 'globalThis.component ='), { ReturnLabelConfirmation: {}, PortalHeader: {}, ScanTargetInput: {} })
const component = vm.runInNewContext(source.match(/<script[^>]*>([\s\S]*?)<\/script>/)[1].replace(/^\s*import .*$/mg, '').replace('export default', 'globalThis.component ='), { ReturnLabelConfirmation: {}, PortalHeader: {}, ScanTargetInput: {}, ExceptionReturnWork: {} })
const state = { current: {}, selectedItems: [{ skuCode: 'A' }], receiptQuantity: 2, unitType: 'PARCEL', boxRows: [physicalRow({ A: 2 })], remaining: () => 3 }
assert.equal(component.computed.canConfirm.call(state), true)
state.boxRows[0].items.A = 4
@@ -205,7 +225,7 @@ test('batch waybill scans stay on the single parcel waybill input', () => {
test('parcel rows must be nonempty and summed quantities cannot exceed the order remainder', () => {
const source = readFileSync(new URL('../src/pages/return-receipt/return-receipt.vue', import.meta.url), 'utf8')
const component = vm.runInNewContext(source.match(/<script[^>]*>([\s\S]*?)<\/script>/)[1].replace(/^\s*import .*$/mg, '').replace('export default', 'globalThis.component ='), { ReturnLabelConfirmation: {}, PortalHeader: {}, ScanTargetInput: {} })
const component = vm.runInNewContext(source.match(/<script[^>]*>([\s\S]*?)<\/script>/)[1].replace(/^\s*import .*$/mg, '').replace('export default', 'globalThis.component ='), { ReturnLabelConfirmation: {}, PortalHeader: {}, ScanTargetInput: {}, ExceptionReturnWork: {} })
const state = { current: {}, selectedItems: [{ skuCode: 'A' }], receiptQuantity: 4, unitType: 'PARCEL', boxRows: [physicalRow({ A: 2 }), physicalRow({ A: 2 })], remaining: () => 3 }
assert.equal(component.computed.canConfirm.call(state), false)
state.remaining = () => 5
@@ -300,3 +300,9 @@ test('新增预报箱无SKU绑定时恢复为可编辑箱,保留已有草稿',
assert.ok(added)
assert.ok(value.declaredSkuCodes.includes(added.items[0].skuCode))
})
test('warehouse transfer errors show guidance without diagnostic identifiers', () => {
const { value: page } = setup()
assert.equal(page.simpleErrorMessage({message:'该单为仓库上门取货,请先完成车辆取货送仓\nrequestId: request-1'}), '该单为仓库上门取货,请先完成车辆取货送仓')
assert.equal(page.simpleErrorMessage({message:'操作失败(错误码:S0503;requestId:request-1;traceId:trace-1)'}), '操作失败')
})
+5 -1
View File
@@ -1,5 +1,8 @@
import { defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import { fileURLToPath } from 'node:url'
const projectDir = fileURLToPath(new URL('.', import.meta.url))
function loggedProxy(name, options) {
return {
@@ -24,9 +27,10 @@ function loggedProxy(name, options) {
}
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
const env = loadEnv(mode, projectDir, '')
const apiTarget = env.API_PROXY_TARGET || 'http://127.0.0.1:9000'
return {
envDir: projectDir,
base: process.env.UNI_PLATFORM === 'h5' && mode === 'production' ? '/' : undefined,
plugins: [uni()],
define: {