Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2ec169eb3 |
@@ -2,14 +2,13 @@
|
|||||||
|
|
||||||
## 快速读取顺序
|
## 快速读取顺序
|
||||||
|
|
||||||
1. 由“模块快速路由”选最小模块并读最近 `AGENTS.md`,按 `routes.ts → pages/ → api/types/stores/composables` 下钻,不扫描全部 `src/`。
|
1. 用“模块快速路由”选择最小业务模块,进入后读取该目录最近的 `AGENTS.md`;按 `routes.ts → pages/ → api/types/stores/composables` 下钻,不先扫描全部 `src/`。
|
||||||
2. 视觉、布局/交互承载变更或真实页面验收先读 `../../docs/Admin-Client前端原型还原验收规则.md`;需原型依据再读 `../../docs/悦/货代SAAS平台后台/AGENTS.md` 并定位片段。纯文案、逻辑或单元测试不触发。
|
2. 视觉还原、布局/交互承载方式变更或真实页面验收时读取 `../../docs/Admin-Client前端原型还原验收规则.md`;需要原型依据才读取 `../../docs/悦/货代SAAS平台后台/AGENTS.md` 并定位目标片段。纯文案、逻辑或单元测试任务不自动读取。
|
||||||
样式优化另读 `../../docs/Admin高密度界面规范.md` 的“样式维护边界”“新模块接入规则”,保留已确认密度、彩色页签、业务语义及承载。国内仓、客户管理为样板;新增菜单按本轮范围显式接入,货柜入口见 `../../docs/Admin货柜管理样式核对记录.md`。
|
Admin 样式优化还须读取 `../../docs/Admin高密度界面规范.md` 的“样式维护边界”和“新模块接入规则”;以已确认密度与彩色页签为视觉基线,逐操作保留业务语义和承载方式。国内仓、客户管理是样板;新增菜单按本轮范围显式接入,货柜管理入口见 `../../docs/Admin货柜管理样式核对记录.md`。
|
||||||
蓝白样式接入见 [样板指南](../../docs/界面参考/蓝白卡片式工作台风格参考.md)。
|
3. 标准列表或公共组件任务读取 `src/shared/components/AGENTS.md`;国内/海外 HTTP、Token 或刷新任务读取 `src/shared/api/AGENTS.md`;Finance 任务读取 `src/modules/finance/AGENTS.md`;海外仓全流程任务先读 `../../docs/海外仓业务/README.md`。
|
||||||
3. 标准列表/公共组件读 `src/shared/components/AGENTS.md`;HTTP、Token/刷新读 `src/shared/api/AGENTS.md`;Finance 读 `src/modules/finance/AGENTS.md`;海外仓全流程先读 `../../docs/海外仓业务/README.md`。
|
4. 平台/客户层级与权限公共语义读取 `../../docs/平台客户层级与权限契约.md`;统一 API、Token、会话撤销或可靠事件任务按需读取 `../../docs/统一认证与服务通信契约.md` 对应章节。
|
||||||
4. 平台/客户层级及权限读 `../../docs/平台客户层级与权限契约.md`;统一 API、Token、会话撤销或可靠事件按需读 `../../docs/统一认证与服务通信契约.md` 对应章节。
|
|
||||||
|
|
||||||
单端仅读本指引、最近模块指引及命中代码;跨服务状态、权限或接口边界不明才加后端契约。预算遵循根指引,先读适用规则、定向查业务表,跳过无关专题。
|
普通单端任务的最小读取集是本文件、目标模块最近的 `AGENTS.md` 和目标代码命中段;只有跨服务状态、权限或接口边界无法判断时才增加后端契约。读取预算遵循根指引的行数与字符数标准,先读适用规则,再定向读取业务表,不全文加载无关专题。
|
||||||
|
|
||||||
## 项目定位与技术基线
|
## 项目定位与技术基线
|
||||||
|
|
||||||
@@ -37,54 +36,61 @@
|
|||||||
|
|
||||||
## 模块快速路由
|
## 模块快速路由
|
||||||
|
|
||||||
按短表定位后按需查 [业务细则](docs/business-index.md);涉及业务行为变更时必须核对对应细则及最近模块指引。从应用根执行 `rg -n -F '任务词或文件名' docs/business-index.md`,只读命中条款。
|
表中 `modules/`、`core/`、`shared/`、`app/` 和 `main.ts` 均相对 `src/`;裸文件名沿用同一单元格最近目录。模块细节只在最近指引维护,应用层保留入口。
|
||||||
|
|
||||||
路径从应用根起算,`modules/`、`core/` 从 `src/` 起算;接口片段与符号沿同一行代码定位。模块指引中的后端类名以服务名起算,如 `firstleg/service/X.java` 即 `baiyue-firstleg/firstleg/src/main/java/com/baiyue/firstleg/service/X.java`。
|
| 业务 | Admin 入口 | 联查 |
|
||||||
|
|---|---|---|
|
||||||
|
| 登录、会话与统一 Token | `modules/auth/`、`core/auth/` | 国内 `auth/`、`iam/`;海外请求客户端再读 `shared/api/AGENTS.md` |
|
||||||
|
| 启动与懒加载资源恢复 | `main.ts`、`core/routing/navigationRecovery.ts` | 仅识别动态模块/Chunk 资源过期;30 秒内同目标最多自动恢复一次,存在未保存编辑时必须先确认 |
|
||||||
|
| 工作台与指标 | `modules/dashboard/` | 指标所属模块与服务端,不复制领域契约 |
|
||||||
|
| 自营销量、库存与数据采集 | `modules/self-operated/AGENTS.md` | 三个入口 `/self-operated/sales`、`/self-operated/inventory`、`/self-operated/collection`;后端 `lastleg-service/selfoperated/analytics/`,正式合同见 `../../docs/自营业务/README.md`。 |
|
||||||
|
| 船期日历 | `modules/sailing-calendar/` | 当前日历入口覆盖渠道、周模板、单次船期、收货截止时间和按渠道货量统计;后端按 `firstleg/` 船期接口定位,不读取已归档的货柜开发规划 |
|
||||||
|
| 预约管理、预约列表、跨客户同仓预约 | `modules/appointment-calendar/`;入仓单预约沿 `modules/overseas-warehouse/` | 统一规则见 `../../docs/海外仓业务/README.md` 的预约送仓;同仓跨客户共用预约,客户归属在货物明细;到港只读 Firstleg,送仓归 Lastleg |
|
||||||
|
| FBA 无匹配价格、人工定价 | `modules/inbounds/fee/api.ts` 的 `createManualInboundQuote`、`types.ts`;页面消费沿 `InboundFeePanel.vue` 核对 | `POST /manual-quote` 提交计费重量、体积、单价、原因和 `Idempotency-Key`;Backend `PlatformFbaPricingController.manualQuote` → `FbaPricingService.manualQuote`,权限 `firstleg:inbound:confirm-send-fee`。仅 FBA、已有实际测量且当前价格未命中时允许,客户已确认费用禁止改价;`MANUAL_QUOTE` 快照允许价格记录与版本为空,不伪造价格簿关联。API 回归 `modules/inbounds/fee/api.test.ts`,不能以 API 存在代替页面接入完成 |
|
||||||
|
| PDA版本、APK下载、WGT热更新发布与停发 | `modules/pda-releases/pages/PdaReleasesView.vue`、`modules/pda-releases/api/pdaReleases.ts`、`modules/pda-releases/routes.ts` | 系统菜单 `/system/pda-releases`;列表权限 `platform:pda-release:list`,上传/发布/停发权限 `platform:pda-release:manage`。国内/海外按 `domestic/overseas` 分开查询,上传只创建草稿,发布与停发需确认;管理请求使用国内 HTTP 的 `/platform/v1/files/pda-releases`,后端见 `file/AGENTS.md`,设备安装与重启查对应 PDA 的更新工具 |
|
||||||
|
| 客户、企业审核、客户统计 | `modules/customers/` | `iam/`、`auth/`、`file/`、`firstleg/customerstatistics/`;公司联系电话只作企业联系信息,不修改管理员/成员登录手机号且不要求跨企业唯一。审核必填资质仅营业执照与统一社会信用代码;法人身份证选填,可随资质包提交,也可在已有营业执照后单独补传或替换 |
|
||||||
|
| 供应商、国内整柜 | `modules/suppliers/`、`modules/domestic-containers/` | Backend `warehouse/` 及对应 OpenAPI |
|
||||||
|
| 平台仓库与仓储资源 | 仓库主档 `modules/warehouses/`,国内资源 `modules/warehouse-resources/` | 全部仓库 ID、类型、状态、地址和能力归国内 `warehouse/`;海外 `warehouse-overseas-service/` 只维护引用同一 warehouseId 的库位、托盘和锁 |
|
||||||
|
| 平台用户、RBAC、导航 | `modules/iam/`、`core/access/`、`core/navigation/` | `auth/`、`iam/`、平台权限契约 |
|
||||||
|
| 国内/海外 PDA 独立人员与海外仓绑定 | `modules/iam/pages/InternalUsersView.vue`、`modules/iam/api/platformIam.ts` | 国内 `CN_FIRSTLEG_PDA_OPERATOR` 与海外 `OVERSEAS_WAREHOUSE_PDA_OPERATOR` 互斥;只有海外角色必须且只能绑定一个 `overseasWarehouseId`,候选来自国内 Warehouse 平台仓库 API 的公共 `OVERSEAS + ACTIVE + RECEIVING` 收货仓 |
|
||||||
|
| 消息中心 | `modules/notifications/` | Backend `iam/.../notification/`;仅顶部消息中心,不进入左侧菜单 |
|
||||||
|
| 订单列表、批量审核预览、详情、商品图片与入库费用 | `modules/unified-orders/`、`modules/first-leg-orders/`;平台商品图片由 `modules/unified-orders/api/unifiedOrders.ts` 按客户与 fileId 下载 | `order/`、`firstleg/`、Finance;旧系统导入固定归属“IT测试公司”,前端不提交或选择客户,逐行结果展示入仓码与失败原因。图片读取归 `file/` 的 `PlatformProductImageController`。Order 状态为 `SUBMITTED` 时统一列表必须保持 `PENDING_REVIEW/APPROVE_ORDER`,不得被已存在的 Firstleg 准备中入库投影覆盖。批量审核弹框通过 `unifiedOrders.ts` 的 `/orders/first-leg/batch-review-preview` 一次取回全部预览,按服务端 `canApprove/blockReason` 展示,不逐票请求详情或用内部 ID 作标题 |
|
||||||
|
| 客户原始申报资料编辑与渠道变更 | `modules/unified-orders/components/OrderDeclarationEditorDialog.vue`、`api/unifiedOrders.ts`、`pages/UnifiedOrdersView.vue` | 使用订单版本和货物 `itemNo` 整体提交,不允许增删货物行;只编辑客户申报快照,不覆盖仓库/PDA 实测、测量审核或计费事实。渠道变化需二次确认并由 Backend `order/` 联查 `firstleg/` 的分柜、同柜、装柜与重新计价门禁;国内收货仓或中转仓变化必须重新下单 |
|
||||||
|
| 入库扣货、解除与凭证历史 | `modules/unified-orders/pages/UnifiedOrdersView.vue`、`modules/inbounds/core/api.ts`、`types.ts` | 页面只消费服务端 `holdFlag/currentHoldReason/canHold/canRelease/actionBlockReason/history`;扣货与解除提交当前入库版本、幂等键、必填原因和可选凭证,凭证下载只走 Firstleg 授权入口。Backend `firstleg/` 的 `InboundHoldService`、`InboundHoldGuard`、`InboundHoldEvidenceService`,文件归 `file/` |
|
||||||
|
| 入库、测量、称重库位状态、客户箱规策略与计价主数据 | 测量弹框/工作区 `modules/inbounds/measurement/InboundMeasurementDialog.vue`、`InboundMeasurementPanel.vue`,称重 `modules/inbounds/weight/components/WeightOcrPanel.vue`;主数据 `modules/fba-pricing/`、`modules/dimension-config/`、`modules/customers/components/CustomerBillingRulesPanel.vue`、`modules/fee-items/` | 客户固定四档箱规,默认计算方式为 `ADD/MULTIPLY`;测量行可选实际尺寸、箱规尺寸策略或客户默认尺寸系数,保存后以 Backend `firstleg/` 返回的外箱尺寸、体积重和计费基数为准,不在页面独立重算。费用确认的实际箱数、毛重和体积优先汇总当前 `actualMeasurementRows`,不得用可能滞后的工作区顶层合计覆盖明细。称重页在每张图片卡片只展示服务端 `locationCode/slotStatus/sharedOverflow`,不渲染或自行推导整票预留引导;删除图片须提示槽位仍归本票保留,不得按图片数组下标推导托盘或库位 |
|
||||||
|
| 一件代发托盘打印 | `modules/unified-orders/pages/UnifiedOrdersView.vue` 的“托盘打印”页签、`modules/inbounds/core/DropshipPalletPrintPanel.vue`、`core/api.ts` | 仅一件代发订单展示;测量审核预生成托盘码后由 Admin 电脑端打印,支持本票全部托盘合并打印和单托补打。PDA 只扫码组托,不承担 PDF 下载或打印机连接 |
|
||||||
|
| 入库单扣货、解除、凭证与历史 | `modules/inbounds/pages/InboundOrdersView.vue`、详情工作区、`modules/inbounds/core/api.ts` | 列表展示服务端 `holdFlag/currentHoldReason` 并支持筛选;详情只按 `canHold/canRelease/actionBlockReason` 开放操作。扣货与解除提交当前 `version`、原因和独立幂等键,可选凭证先按明确客户与入库单上传;历史文件只调用专用下载入口,不把上传成功但未提交命令的文件冒充扣货证据 |
|
||||||
|
| 客户专属价格簿、柜级阶梯运费与受控调价 | 列表/上传 `modules/fba-pricing/carrier-rates/pages/CarrierRatesView.vue`,版本详情/仓库映射/确认 `modules/fba-pricing/carrier-rates/pages/CarrierRateDetailView.vue`,路由 `modules/fba-pricing/routes.ts`;`modules/inbounds/fee/`、`modules/unified-orders/components/InboundFeeDetailManager.vue` | 列表与上传后按 `versionId` 进入 `fba-carrier-rate-detail` 独立详情页,价格行只读;回归入口 `modules/fba-pricing/carrier-rates/pages/CarrierRatesView.test.ts`。价格簿页面显式选择公共报价或具体客户;列表、上传、确认只作用于该 `customerId`,不得混合版本。计价优先消费客户专属 ACTIVE 版本,无专属版本才回退公共 ACTIVE;柜级阶梯金额和各客户分摊只展示服务端结果。调整计费量只能在服务端返回的上下 10% 范围内并提交当前费用版本、原因与二次确认;私人仓尾程派送费使用稳定 `PRIVATE_LAST_MILE_DELIVERY` 代码且只对 `PRIVATE` 目的地开放;一件代发须在预装确认前完成试算,计价后保持服务端 `WAIT_PALLETIZE` 状态 |
|
||||||
|
| 财务、客户资金账户与柜级公共费用分摊 | `modules/finance/`,继续读该目录 `AGENTS.md`;客户账户 `pages/FinanceCustomerAccountsView.vue`,柜费 `modules/loading-lists/components/ContainerFeesPanel.vue`、`api/containerFees.ts` | `finance/`、`firstleg/`、`file/`、`docs/财务管理/`;实际、冻结、可用余额、授信与流水只消费 Finance 权威结果,充值审核和手工充扣携带版本与幂等键。跨客户公共柜费只按服务端柜内客户/订单事实分摊,金额必须守恒,创建与审核、驳回、调整、作废均整组原子处理 |
|
||||||
|
| 货柜双工作台、排柜、预装/装柜清单、真实柜号后补与整柜报关 | 国内 `modules/container-loading/pages/DomesticContainersView.vue`、海外 `OverseasContainersView.vue`,共享详情实现 `ContainerDetailView.vue`;预装详情 `modules/loading-lists/pages/PreloadPlanDetailView.vue`,资料/PDA 证据 `components/ContainerOverviewPanel.vue`,报关 `components/ContainerCustomsPanel.vue` | 国内“送柜报关”只消费 `/containers/domestic` 与服务端 `allowedActions`,承载模拟柜、订舱关联、智能装柜;模拟柜创建选择与智能装柜一致的 9 类计划渠道,未关联订舱前实际渠道为空,订舱关联候选按计划渠道组匹配并同时展示订舱号与提单号、装柜清单页签、出口报关和国内出仓;创建柜次时自动生成唯一预装计划,预装详情先调用 `/loading-plans/{planId}/lifecycle`,完成后深链进入国内货柜详情的装柜清单页签,独立装柜清单导航 `/loading-lists` 复用已确认清单 API,查看进入独立详情路由 `/loading-lists/:planId`,保留返回列表和打印;独立清单详情与货柜清单页签共同使用 `useLoadingListDetail.ts` 加载、校验和处理错误,`LoadingListDetailDrawer.vue` 统一密度、摘要、明细、历史及打印入口,打印实现归 `printLoadingList.ts`,外层只保留返回目标与货柜专属 PDA/报关区域;货柜列表经 `ContainerWorkbenchView.vue` 在国内装柜与海外清关提柜之间按权限切换。订舱关联允许真实集装箱号为空,但确认预装和创建 PDA 任务前必须补齐;历史已建但缺号的任务仍可在预装详情首次补录,保存后恢复 PDA 可进入状态;全买单柜继续使用 `complete-all-buy`。海外“清关提柜”只消费 `/containers/overseas`,承载船节点、目的港清关、DO/PU、码头车队和还空;原预约/实际提柜展示位改为整柜预计/实际到仓,预计到仓在列表内人工快捷维护并经海外接口同步整柜尾程订单,实际到仓只读海外 PDA 首次开始收货时间。还空截止事实由服务端基于卸柜完成时间加 72 小时计算,前端不重算。两端统一使用 `containerBookingId`,列表范围由服务端 `scope=ACTIVE/HISTORY` 分页,禁止浏览器筛选或本地推导写资格。后端为 `LoadingListService`、`firstleg/customs/container/`、`firstleg/terminaldrayage/` 和 `lastleg-service/`,文件归 `file/` |
|
||||||
|
| 合柜报关 / 同柜不可拆组 | `modules/unified-orders/api/coLoadGroups.ts`、`pages/UnifiedOrdersView.vue`;装柜消费 `modules/container-loading/pages/SmartLoadingWorkbenchView.vue` | 前端只提交订单 ID;Backend `firstleg/loading/coload/` 展开并冻结每票全部可用入仓片段。成员数是入仓片段数,不等于订单票数;只要求同国内仓、同渠道,允许跨客户及不同目的仓港;分配、移除、取消均整组处理 |
|
||||||
|
| 全局智能装柜工作台、入仓码候选与箱数分配 | `modules/container-loading/components/SmartLoadingDialog.vue` 内嵌 `pages/GlobalSmartLoadingView.vue`,柜次页 `SmartLoadingWorkbenchView.vue`,以及 `smartLoadingChannelGroups.ts`、`smartLoadingItems.ts`、`api/platformContainerLoading.ts`;全局页当前不注册独立路由 | Backend `firstleg/` 的 `/inbound-candidates`、`/containers`、`/inbound-assignments`、`/plans/{planId}/pending-review-assignments`、`/group-assignments`、`/unpicked-items`。`orderStatuses` 最多四项且未传表示全部未完成状态;候选状态多选覆盖待审核、待测量、待分柜、装柜中,状态只用于筛选展示,按钮资格以服务端 `canAssign` 为准;待审核/待测量可提前占位但不得提前确认预装或启动 PDA。计划箱数编辑上限、已用和未用展示只消费服务端 `totalPackageCount/remainingPackageCount`,不得从候选页或本地规格重新拼算。人工加入允许跨渠道,智能推荐仍按柜次渠道。柜次容量和限重取服务端字段;同柜组作为单卡整组分页、分配和移除,任一成员已拣时整组保留 |
|
||||||
|
| 国内货柜履约订舱资料、打印、关联候选与出仓前船期 | `modules/ocean-bookings/` 的 `components/OceanBookingDocumentsPanel.vue`、`OceanBookingPrintDialog.vue`,以及 `modules/container-loading/`、`modules/port-schedules/` | 订舱草稿按当前版本维护资料,放舱后资料与表单只读;打印对草稿与已放舱订舱均开放,按当前已保存资料生成,未填写字段显示“—”。`platformOceanBookings.ts` 的 `/link-candidates` 只消费服务端分页,`containerCount` 是柜型需求 `quantity` 总和;Backend `firstleg/oceanbooking/`、`file/`、`print/`、`firstleg/portschedule/` |
|
||||||
|
| 订舱级拖车预约 | `modules/trucking/api/platformTrucking.ts` 的 `/candidates`、`components/TruckAppointmentForm.vue`、`pages/TruckAppointmentCreateView.vue`、`TruckAppointmentsView.vue` | 表单只选择服务端返回的 `RELEASED` 订舱与 `TRUCKING + truckingScope=DOMESTIC` 国内拖车供应商,不选择或提交客户、柜次、装柜计划或真实集装箱号;清关提柜固定选择 `OVERSEAS` 海外车队,类型在供应商主档单选维护;提单号和仓库由订舱冻结事实带入。一个订舱最多一张非终态拖车单,重复创建转入现有单继续编辑;PDA 完成不自动推进拖车。附件为平台作用域且不重复提单文件;Backend `TruckAppointmentService`、`truck-appointments-v1.yaml` |
|
||||||
|
| 目的港码头拖车与还空预警 | 海外清关提柜工作台/详情 `modules/container-loading/pages/OverseasContainersView.vue`、`OverseasContainerDetailView.vue`,API `modules/container-loading/api/terminalDrayages.ts`、`containerArrivalTimes.ts` | 与订舱级拖车预约是不同生命周期;按 `containerBookingId` 读取服务端状态、`allowedActions` 和历史,不能复用订舱级拖车表单或自行推进状态。列表“预计到仓”列直接提供人工日期时间选择器,保存时通过 Lastleg 柜级版本和幂等键原子更新该柜全部尾程订单,已有入库计划后禁止修改;“实际到仓”只读 `ll_receiving_container_session.receiving_at`,即海外 PDA 首次开始收货时间。还空截止、超时天/小时只展示服务端基于权威卸柜完成时间加 72 小时计算的结果;Backend `firstleg/terminaldrayage/`、`lastleg-service/`,邮件记录通过 `terminalDrayages.ts` 查询与重试。 |
|
||||||
|
| 历史报关协同与国内出仓 | `modules/customs/`、`modules/outbound-dispatch/` | `modules/customs/` 是历史报关案件/清单/代理提交与回执入口;装柜完成后的整柜退税/买单资料从货柜详情进入,不在旧模块复制;Backend `firstleg/outbound/dispatch/`、`firstleg/customs/`、`file/` |
|
||||||
|
| 主数据、下载、退避任务重试、审计 | `modules/master-data/`、`modules/downloads/pages/DownloadCenterView.vue`、`modules/audit/` | File 导出任务返回 `attemptCount/maxAttempts/nextRetryAt`;仅失败或已进入自动退避的等待任务显示重试,等待任务重试用于立即执行当前投递,不创建新任务;联查 `warehouse/`、`file/`、`audit-service/` |
|
||||||
|
| 海外接柜、入库、库存与库内服务 | `modules/overseas-warehouse/` | `gateway/`、`lastleg-service/`、`warehouse-overseas-service/`;与排车、出库、派送、异常退回和一件代发共同组成海外仓全流程 |
|
||||||
|
| 海外采购、卡车、散板 | `modules/overseas-business/` | `gateway/`、`lastleg-service/` |
|
||||||
|
| 海外仓业务合作仓与通用资料 | 合作仓 `modules/warehouses/`;报价/汇率/车辆 `modules/overseas-master-data/` | 国内 `warehouse/`、海外实际资源与服务 |
|
||||||
|
| 海外仓业务国内出仓后船节点 | `modules/port-schedules/`、`modules/ocean-bookings/`、货柜详情 | `firstleg/portschedule/`、`integration-service/`;预计节点只展示不推进实际进度,手工实际节点必须严格向后追加并防重复,十节点标准见 `../../docs/海外仓业务/船节点标准化契约.md` |
|
||||||
|
| 海外排车、出库与派送 | `modules/overseas-warehouse/AGENTS.md` | 按模块表定位排车、出库、派送页面及 API;履约边界在模块内维护 |
|
||||||
|
| 海外异常退回与客户回访 | `modules/overseas-warehouse/AGENTS.md` | 派送异常退回区别于退货库存;页面、API 与原子推进约束见模块指引 |
|
||||||
|
|
||||||
| 业务 | 首个入口 |
|
全量验收按业务从 `../../docs/订单与客户/`、`入库测量与计费/`、`国内货柜履约/`、`财务管理/` 选择最小契约;海外跨模块流程或入口不明时读 `../../docs/海外仓业务/README.md`,已定位局部任务直接沿模块入口。进度、排期或验收状态问题再读取对应进度表和报告。
|
||||||
|---|---|
|
|
||||||
| 登录、会话与统一 Token | `modules/auth/AGENTS.md`、`core/auth/` |
|
散货托盘码打印:`modules/loading-lists/components/PalletLabelPrintDialog.vue`、`modules/loading-lists/api/platformLoadingLists.ts`,由货柜详情与装柜清单详情进入;先调用 `/pallet-labels/prepare` 获取服务端按 FBA 仓分组的冻结清单,再通过 `/pallet-labels/print` 下载 PDF。托盘码使用“真实柜号-FBA 地址内部编号-三位序号”,页面同时展示 FBA 仓码和内部编号;支持全部打印或按仓指定张数补打,一件代发托盘不在该清单,前端不生成或重新编号托盘码。
|
||||||
| 启动与懒加载资源恢复 | `src/main.ts`、`core/routing/navigationRecovery.ts` |
|
|
||||||
| 工作台与指标 | `modules/dashboard/AGENTS.md` |
|
|
||||||
| 自营销量、库存与数据采集 | `modules/self-operated/AGENTS.md` |
|
|
||||||
| 船期日历 | `modules/sailing-calendar/AGENTS.md` |
|
|
||||||
| 预约管理、预约列表、跨客户同仓预约 | `modules/appointment-calendar/AGENTS.md`、`modules/overseas-warehouse/` |
|
|
||||||
| FBA 无匹配价格、人工定价 | `modules/inbounds/fee/api.ts`、`createManualInboundQuote` |
|
|
||||||
| PDA版本、APK下载、WGT热更新发布与停发 | `modules/pda-releases/AGENTS.md` |
|
|
||||||
| 客户、企业审核、客户统计 | `modules/customers/AGENTS.md` |
|
|
||||||
| 供应商、国内整柜 | `modules/suppliers/AGENTS.md`、`modules/domestic-containers/AGENTS.md` |
|
|
||||||
| 平台仓库与仓储资源 | `modules/warehouses/AGENTS.md`、`modules/warehouse-resources/AGENTS.md` |
|
|
||||||
| 平台用户、RBAC、导航 | `modules/iam/AGENTS.md`、`core/access/` |
|
|
||||||
| 国内/海外 PDA 独立人员与海外仓绑定 | `modules/iam/pages/InternalUsersView.vue`、`modules/iam/api/platformIam.ts` |
|
|
||||||
| 消息中心 | `modules/notifications/AGENTS.md` |
|
|
||||||
| 订单列表、批量审核预览、详情、商品图片与入库费用 | `modules/unified-orders/AGENTS.md`、`modules/first-leg-orders/` |
|
|
||||||
| 客户原始申报资料编辑与渠道变更 | `modules/unified-orders/components/OrderDeclarationEditorDialog.vue`、`modules/unified-orders/api/unifiedOrders.ts` |
|
|
||||||
| 入库扣货、解除与凭证历史 | `modules/unified-orders/pages/UnifiedOrdersView.vue`、`modules/inbounds/core/api.ts` |
|
|
||||||
| 入库、测量、称重库位状态、客户箱规策略与计价主数据 | `modules/inbounds/AGENTS.md`、`modules/dimension-config/AGENTS.md` |
|
|
||||||
| 一件代发托盘打印 | `modules/unified-orders/pages/UnifiedOrdersView.vue`、`modules/inbounds/core/DropshipPalletPrintPanel.vue` |
|
|
||||||
| 入库单扣货、解除、凭证与历史 | `modules/inbounds/pages/InboundOrdersView.vue`、`modules/inbounds/core/api.ts` |
|
|
||||||
| 客户专属价格簿、柜级阶梯运费与受控调价 | `modules/fba-pricing/AGENTS.md`、`modules/fba-pricing/carrier-rates/pages/CarrierRateDetailView.vue` |
|
|
||||||
| 财务、客户资金账户与柜级公共费用分摊 | `modules/finance/AGENTS.md` |
|
|
||||||
| 货柜双工作台、排柜、预装/装柜清单、装柜照片与证据、真实柜号后补与整柜报关 | `modules/container-loading/AGENTS.md`、`modules/loading-lists/AGENTS.md` |
|
|
||||||
| 合柜报关 / 同柜不可拆组 | `modules/unified-orders/api/coLoadGroups.ts`、`modules/unified-orders/pages/UnifiedOrdersView.vue` |
|
|
||||||
| 全局智能装柜工作台、入仓码候选与箱数分配 | `modules/container-loading/components/SmartLoadingDialog.vue`、`modules/container-loading/pages/GlobalSmartLoadingView.vue` |
|
|
||||||
| 国内货柜履约订舱资料、打印、关联候选与出仓前船期 | `modules/ocean-bookings/AGENTS.md` |
|
|
||||||
| 订舱级拖车预约 | `modules/trucking/AGENTS.md` |
|
|
||||||
| 目的港码头拖车与还空预警 | `modules/container-loading/AGENTS.md` |
|
|
||||||
| 历史报关案件、报关回执与国内出仓 | `modules/customs/AGENTS.md`、`modules/outbound-dispatch/AGENTS.md` |
|
|
||||||
| 主数据、下载、退避任务重试 | `modules/master-data/AGENTS.md`、`modules/downloads/AGENTS.md` |
|
|
||||||
| 费用项目、计费科目 | `modules/fee-items/AGENTS.md` |
|
|
||||||
| 操作日志、审计日志、操作人 | `modules/audit/AGENTS.md` |
|
|
||||||
| 海外接柜、入库、库存与库内服务 | `modules/overseas-warehouse/AGENTS.md` |
|
|
||||||
| 海外采购、卡车、散板 | `modules/overseas-business/AGENTS.md` |
|
|
||||||
| 海外仓业务合作仓与通用资料 | `modules/warehouses/AGENTS.md`、`modules/overseas-master-data/AGENTS.md` |
|
|
||||||
| 海外仓业务国内出仓后船节点 | `modules/port-schedules/AGENTS.md`、`modules/ocean-bookings/` |
|
|
||||||
| 海外排车、出库与派送 | `modules/overseas-warehouse/AGENTS.md` |
|
|
||||||
| 海外异常退回与客户回访 | `modules/overseas-warehouse/AGENTS.md` |
|
|
||||||
|
|
||||||
## 海外模块内部快速索引(海外仓全流程)
|
## 海外模块内部快速索引(海外仓全流程)
|
||||||
|
|
||||||
海外仓作业先读 `src/modules/overseas-warehouse/AGENTS.md`;采购、车队等页面/API 联查按需查 `docs/business-index.md` 同名节。
|
- 海外仓的尾程订单控制与柜级入仓计划转换、退货库存、排车出库、异常回访:读取 `src/modules/overseas-warehouse/AGENTS.md`,字段与流程仅在该模块维护。
|
||||||
|
|
||||||
|
| 关键词 | 页面/路由入口 | API 与联查 |
|
||||||
|
|---|---|---|
|
||||||
|
| 海外采购 | `modules/overseas-business/pages/PurchaseOrdersView.vue`、详情/编辑页 | `modules/overseas-business/api/platformOverseasBusiness.ts` 的 purchase 方法;Backend `lastleg-service/procurement/` |
|
||||||
|
| 美国卡车、本土散板 | `modules/overseas-business/pages/TransportOrdersView.vue`、`TransportOrderFormView.vue` | 同一 API 的 us-truck/looseboard 方法;Backend `lastleg-service/trucking/`、`looseboard/` |
|
||||||
|
| 海外报价、月度汇率、车辆 | `modules/overseas-master-data/pages/OverseasQuotesView.vue`、`ExchangeRatesView.vue`、`VehiclesView.vue` | `modules/overseas-master-data/api/overseasMasterData.ts`;Backend `lastleg-service/masterdata/` |
|
||||||
|
| 司机档案、驾驶证、到期提醒与资格预览 | `modules/overseas-master-data/pages/DriversView.vue`、`DriverDetailView.vue`;最近指引 `modules/overseas-master-data/AGENTS.md` | `api/drivers.ts`;Backend `lastleg-service/fleet/driver/`、File `FLEET_DRIVER_LICENSE` |
|
||||||
|
|
||||||
## 业务、安全与共享装配
|
## 业务、安全与共享装配
|
||||||
|
|
||||||
@@ -121,7 +127,7 @@ pnpm typecheck
|
|||||||
pnpm build
|
pnpm build
|
||||||
```
|
```
|
||||||
|
|
||||||
- 源码、依赖或构建配置变更至少运行 `pnpm typecheck` 和受影响测试,交付前运行 `pnpm test` 与 `pnpm build`;不影响代码、契约或配置的纯文档/索引变更只检查路径、链接及索引合同。当前没有 lint 脚本,不声称 lint 通过。
|
- 普通变更至少运行 `pnpm typecheck` 和受影响测试;交付前运行 `pnpm test` 与 `pnpm build`。当前没有 lint 脚本,不声称 lint 通过。
|
||||||
- 不手工修改 `dist/`、`node_modules/` 或生成声明;依赖变化同步 `package.json` 与锁文件。
|
- 不手工修改 `dist/`、`node_modules/` 或生成声明;依赖变化同步 `package.json` 与锁文件。
|
||||||
- 测试环境全量验收入口为 `../../baiyue-firstleg/scripts/admin-test-env-acceptance.mjs`,模块说明见同仓库 `scripts/admin-test-env-modules/README.md`;它会写入或停用测试数据,只有本轮明确授权才能运行。
|
- 测试环境全量验收入口为 `../../baiyue-firstleg/scripts/admin-test-env-acceptance.mjs`,模块说明见同仓库 `scripts/admin-test-env-modules/README.md`;它会写入或停用测试数据,只有本轮明确授权才能运行。
|
||||||
- `pnpm test/typecheck` 和本地回归脚本不代表真实服务验收完成;HTTP 验收后仍由人工完成页面和截图确认。
|
- `pnpm test/typecheck` 和本地回归脚本不代表真实服务验收完成;HTTP 验收后仍由人工完成页面和截图确认。
|
||||||
|
|||||||
@@ -1,70 +0,0 @@
|
|||||||
# Admin业务详细索引
|
|
||||||
|
|
||||||
本文件保存当前页面/API 入口及业务规则,是[应用指引](../AGENTS.md)的按需补充。涉及字段、状态、权限、金额、资源或作业恢复时必须读取受影响条款,不作为普通定位任务的全文首读。
|
|
||||||
|
|
||||||
正文代码路径以工作区 `apps/admin-web/` 应用根起算,源码包缩写与裸文件名沿对应条目的目录解释;明确标注“工作区”的路径从工作区根起算。Markdown 相对链接以本文件所在的 `docs/` 为起点。已知文件直接定位;行为变更同时核对最近模块指引及服务端合同。
|
|
||||||
|
|
||||||
原条款在本文件维护,主 AGENTS 仅保留短入口和通用边界;不要将新业务细节复制回主指引。
|
|
||||||
|
|
||||||
## 模块快速路由
|
|
||||||
|
|
||||||
表中 `modules/`、`core/`、`shared/`、`app/` 和 `main.ts` 均相对 `src/`;裸文件名沿用同一单元格最近目录。模块细节只在最近指引维护,应用层保留入口。
|
|
||||||
|
|
||||||
| 业务 | Admin 入口 | 联查 |
|
|
||||||
|---|---|---|
|
|
||||||
| 登录、会话与统一 Token | `modules/auth/`、`core/auth/` | 国内 `auth/`、`iam/`;海外请求客户端再读 `shared/api/AGENTS.md` |
|
|
||||||
| 启动与懒加载资源恢复 | `main.ts`、`core/routing/navigationRecovery.ts` | 仅识别动态模块/Chunk 资源过期;30 秒内同目标最多自动恢复一次,存在未保存编辑时必须先确认 |
|
|
||||||
| 工作台与指标 | `modules/dashboard/` | 指标所属模块与服务端,不复制领域契约 |
|
|
||||||
| 自营销量、库存与数据采集 | `modules/self-operated/AGENTS.md` | 三个入口 `/self-operated/sales`、`/self-operated/inventory`、`/self-operated/collection`;后端 `lastleg-service/selfoperated/analytics/`,正式合同见 `../../docs/自营业务/README.md`。 |
|
|
||||||
| 船期日历 | `modules/sailing-calendar/` | 当前日历入口覆盖渠道、周模板、单次船期、收货截止时间和按渠道货量统计;后端按 `firstleg/` 船期接口定位,不读取已归档的货柜开发规划 |
|
|
||||||
| 预约管理、预约列表、跨客户同仓预约 | `modules/appointment-calendar/`;入仓单预约沿 `modules/overseas-warehouse/` | 统一规则见 `../../docs/海外仓业务/README.md` 的预约送仓;同仓跨客户共用预约,客户归属在货物明细;到港只读 Firstleg,送仓归 Lastleg |
|
|
||||||
| FBA 无匹配价格、人工定价 | `modules/inbounds/fee/api.ts` 的 `createManualInboundQuote`、`types.ts`;页面消费沿 `InboundFeePanel.vue` 核对 | `POST /manual-quote` 提交计费重量、体积、单价、原因和 `Idempotency-Key`;Backend `PlatformFbaPricingController.manualQuote` → `FbaPricingService.manualQuote`,权限 `firstleg:inbound:confirm-send-fee`。仅 FBA、已有实际测量且当前价格未命中时允许,客户已确认费用禁止改价;`MANUAL_QUOTE` 快照允许价格记录与版本为空,不伪造价格簿关联。API 回归 `modules/inbounds/fee/api.test.ts`,不能以 API 存在代替页面接入完成 |
|
|
||||||
| PDA版本、APK下载、WGT热更新发布与停发 | `modules/pda-releases/pages/PdaReleasesView.vue`、`modules/pda-releases/api/pdaReleases.ts`、`modules/pda-releases/routes.ts` | 系统菜单 `/system/pda-releases`;列表权限 `platform:pda-release:list`,上传/发布/停发权限 `platform:pda-release:manage`。国内/海外按 `domestic/overseas` 分开查询,上传只创建草稿,发布与停发需确认;管理请求使用国内 HTTP 的 `/platform/v1/files/pda-releases`,后端见 `file/AGENTS.md`,设备安装与重启查对应 PDA 的更新工具 |
|
|
||||||
| 客户、企业审核、客户统计 | `modules/customers/` | `iam/`、`auth/`、`file/`、`firstleg/customerstatistics/`;公司联系电话只作企业联系信息,不修改管理员/成员登录手机号且不要求跨企业唯一。审核必填资质仅营业执照与统一社会信用代码;法人身份证选填,可随资质包提交,也可在已有营业执照后单独补传或替换 |
|
|
||||||
| 供应商、国内整柜 | `modules/suppliers/`、`modules/domestic-containers/` | Backend `warehouse/` 及对应 OpenAPI |
|
|
||||||
| 平台仓库与仓储资源 | 仓库主档 `modules/warehouses/`,国内资源 `modules/warehouse-resources/` | 全部仓库 ID、类型、状态、地址和能力归国内 `warehouse/`;海外 `warehouse-overseas-service/` 只维护引用同一 warehouseId 的库位、托盘和锁 |
|
|
||||||
| 平台用户、RBAC、导航 | `modules/iam/`、`core/access/`、`core/navigation/` | `auth/`、`iam/`、平台权限契约 |
|
|
||||||
| 国内/海外 PDA 独立人员与海外仓绑定 | `modules/iam/pages/InternalUsersView.vue`、`modules/iam/api/platformIam.ts` | 国内 `CN_FIRSTLEG_PDA_OPERATOR` 与海外 `OVERSEAS_WAREHOUSE_PDA_OPERATOR` 互斥;只有海外角色必须且只能绑定一个 `overseasWarehouseId`,候选来自国内 Warehouse 平台仓库 API 的公共 `OVERSEAS + ACTIVE + RECEIVING` 收货仓 |
|
|
||||||
| 消息中心 | `modules/notifications/` | Backend `iam/.../notification/`;仅顶部消息中心,不进入左侧菜单 |
|
|
||||||
| 订单列表、批量审核预览、详情、商品图片与入库费用 | `modules/unified-orders/`、`modules/first-leg-orders/`;平台商品图片由 `modules/unified-orders/api/unifiedOrders.ts` 按客户与 fileId 下载 | `order/`、`firstleg/`、Finance;旧系统导入固定归属“IT测试公司”,前端不提交或选择客户,逐行结果展示入仓码与失败原因。图片读取归 `file/` 的 `PlatformProductImageController`。Order 状态为 `SUBMITTED` 时统一列表必须保持 `PENDING_REVIEW/APPROVE_ORDER`,不得被已存在的 Firstleg 准备中入库投影覆盖。批量审核弹框通过 `unifiedOrders.ts` 的 `/orders/first-leg/batch-review-preview` 一次取回全部预览,按服务端 `canApprove/blockReason` 展示,不逐票请求详情或用内部 ID 作标题 |
|
|
||||||
| 客户原始申报资料编辑与渠道变更 | `modules/unified-orders/components/OrderDeclarationEditorDialog.vue`、`api/unifiedOrders.ts`、`pages/UnifiedOrdersView.vue` | 使用订单版本和货物 `itemNo` 整体提交,不允许增删货物行;只编辑客户申报快照,不覆盖仓库/PDA 实测、测量审核或计费事实。渠道变化需二次确认并由 Backend `order/` 联查 `firstleg/` 的分柜、同柜、装柜与重新计价门禁;国内收货仓或中转仓变化必须重新下单 |
|
|
||||||
| 入库扣货、解除与凭证历史 | `modules/unified-orders/pages/UnifiedOrdersView.vue`、`modules/inbounds/core/api.ts`、`types.ts` | 页面只消费服务端 `holdFlag/currentHoldReason/canHold/canRelease/actionBlockReason/history`;扣货与解除提交当前入库版本、幂等键、必填原因和可选凭证,凭证下载只走 Firstleg 授权入口。Backend `firstleg/` 的 `InboundHoldService`、`InboundHoldGuard`、`InboundHoldEvidenceService`,文件归 `file/` |
|
|
||||||
| 入库、测量、称重库位状态、客户箱规策略与计价主数据 | 测量弹框/工作区 `modules/inbounds/measurement/InboundMeasurementDialog.vue`、`InboundMeasurementPanel.vue`,称重 `modules/inbounds/weight/components/WeightOcrPanel.vue`;主数据 `modules/fba-pricing/`、`modules/dimension-config/`、`modules/customers/components/CustomerBillingRulesPanel.vue`、`modules/fee-items/` | 客户固定四档箱规,默认计算方式为 `ADD/MULTIPLY`;测量行可选实际尺寸、箱规尺寸策略或客户默认尺寸系数,保存后以 Backend `firstleg/` 返回的外箱尺寸、体积重和计费基数为准,不在页面独立重算。费用确认的实际箱数、毛重和体积优先汇总当前 `actualMeasurementRows`,不得用可能滞后的工作区顶层合计覆盖明细。称重页在每张图片卡片只展示服务端 `locationCode/slotStatus/sharedOverflow`,不渲染或自行推导整票预留引导;删除图片须提示槽位仍归本票保留,不得按图片数组下标推导托盘或库位 |
|
|
||||||
| 一件代发托盘打印 | `modules/unified-orders/pages/UnifiedOrdersView.vue` 的“托盘打印”页签、`modules/inbounds/core/DropshipPalletPrintPanel.vue`、`core/api.ts` | 仅一件代发订单展示;测量审核预生成托盘码后由 Admin 电脑端打印,支持本票全部托盘合并打印和单托补打。PDA 只扫码组托,不承担 PDF 下载或打印机连接 |
|
|
||||||
| 入库单扣货、解除、凭证与历史 | `modules/inbounds/pages/InboundOrdersView.vue`、详情工作区、`modules/inbounds/core/api.ts` | 列表展示服务端 `holdFlag/currentHoldReason` 并支持筛选;详情只按 `canHold/canRelease/actionBlockReason` 开放操作。扣货与解除提交当前 `version`、原因和独立幂等键,可选凭证先按明确客户与入库单上传;历史文件只调用专用下载入口,不把上传成功但未提交命令的文件冒充扣货证据 |
|
|
||||||
| 客户专属价格簿、柜级阶梯运费与受控调价 | 列表/上传 `modules/fba-pricing/carrier-rates/pages/CarrierRatesView.vue`,版本详情/仓库映射/确认 `modules/fba-pricing/carrier-rates/pages/CarrierRateDetailView.vue`,路由 `modules/fba-pricing/routes.ts`;`modules/inbounds/fee/`、`modules/unified-orders/components/InboundFeeDetailManager.vue` | 列表与上传后按 `versionId` 进入 `fba-carrier-rate-detail` 独立详情页,价格行只读;回归入口 `modules/fba-pricing/carrier-rates/pages/CarrierRatesView.test.ts`。价格簿页面显式选择公共报价或具体客户;列表、上传、确认只作用于该 `customerId`,不得混合版本。计价优先消费客户专属 ACTIVE 版本,无专属版本才回退公共 ACTIVE;柜级阶梯金额和各客户分摊只展示服务端结果。调整计费量只能在服务端返回的上下 10% 范围内并提交当前费用版本、原因与二次确认;私人仓尾程派送费使用稳定 `PRIVATE_LAST_MILE_DELIVERY` 代码且只对 `PRIVATE` 目的地开放;一件代发须在预装确认前完成试算,计价后保持服务端 `WAIT_PALLETIZE` 状态 |
|
|
||||||
| 财务、客户资金账户与柜级公共费用分摊 | `modules/finance/`,继续读该目录 `AGENTS.md`;客户账户 `pages/FinanceCustomerAccountsView.vue`,柜费 `modules/loading-lists/components/ContainerFeesPanel.vue`、`api/containerFees.ts` | `finance/`、`firstleg/`、`file/`、`docs/财务管理/`;实际、冻结、可用余额、授信与流水只消费 Finance 权威结果,充值审核和手工充扣携带版本与幂等键。跨客户公共柜费只按服务端柜内客户/订单事实分摊,金额必须守恒,创建与审核、驳回、调整、作废均整组原子处理 |
|
|
||||||
| 货柜双工作台、排柜、预装/装柜清单、真实柜号后补与整柜报关 | 国内 `modules/container-loading/pages/DomesticContainersView.vue`、海外 `OverseasContainersView.vue`,共享详情实现 `ContainerDetailView.vue`;预装详情 `modules/loading-lists/pages/PreloadPlanDetailView.vue`,资料/PDA 证据 `components/ContainerOverviewPanel.vue`,报关 `components/ContainerCustomsPanel.vue` | 规则见下文「货柜工作台规则」 |
|
|
||||||
| 合柜报关 / 同柜不可拆组 | `modules/unified-orders/api/coLoadGroups.ts`、`pages/UnifiedOrdersView.vue`;装柜消费 `modules/container-loading/pages/SmartLoadingWorkbenchView.vue` | 前端只提交订单 ID;Backend `firstleg/loading/coload/` 展开并冻结每票全部可用入仓片段。成员数是入仓片段数,不等于订单票数;只要求同国内仓、同渠道,允许跨客户及不同目的仓港;分配、移除、取消均整组处理 |
|
|
||||||
| 全局智能装柜工作台、入仓码候选与箱数分配 | `modules/container-loading/components/SmartLoadingDialog.vue` 内嵌 `pages/GlobalSmartLoadingView.vue`,柜次页 `SmartLoadingWorkbenchView.vue`,以及 `smartLoadingChannelGroups.ts`、`smartLoadingItems.ts`、`api/platformContainerLoading.ts`;全局页当前不注册独立路由 | Backend `firstleg/` 的 `/inbound-candidates`、`/containers`、`/inbound-assignments`、`/plans/{planId}/pending-review-assignments`、`/group-assignments`、`/unpicked-items`。`orderStatuses` 最多四项且未传表示全部未完成状态;候选状态多选覆盖待审核、待测量、待分柜、装柜中,状态只用于筛选展示,按钮资格以服务端 `canAssign` 为准;待审核/待测量可提前占位但不得提前确认预装或启动 PDA。计划箱数编辑上限、已用和未用展示只消费服务端 `totalPackageCount/remainingPackageCount`,不得从候选页或本地规格重新拼算。人工加入允许跨渠道,智能推荐仍按柜次渠道。柜次容量和限重取服务端字段;同柜组作为单卡整组分页、分配和移除,任一成员已拣时整组保留 |
|
|
||||||
| 国内货柜履约订舱资料、打印、关联候选与出仓前船期 | `modules/ocean-bookings/` 的 `components/OceanBookingDocumentsPanel.vue`、`OceanBookingPrintDialog.vue`,以及 `modules/container-loading/`、`modules/port-schedules/` | 订舱草稿按当前版本维护资料,放舱后资料与表单只读;打印对草稿与已放舱订舱均开放,按当前已保存资料生成,未填写字段显示“—”。`platformOceanBookings.ts` 的 `/link-candidates` 只消费服务端分页,`containerCount` 是柜型需求 `quantity` 总和;Backend `firstleg/oceanbooking/`、`file/`、`print/`、`firstleg/portschedule/` |
|
|
||||||
| 订舱级拖车预约 | `modules/trucking/api/platformTrucking.ts` 的 `/candidates`、`components/TruckAppointmentForm.vue`、`pages/TruckAppointmentCreateView.vue`、`TruckAppointmentsView.vue` | 表单只选择服务端返回的 `RELEASED` 订舱与 `TRUCKING + truckingScope=DOMESTIC` 国内拖车供应商,不选择或提交客户、柜次、装柜计划或真实集装箱号;清关提柜固定选择 `OVERSEAS` 海外车队,类型在供应商主档单选维护;提单号和仓库由订舱冻结事实带入。一个订舱最多一张非终态拖车单,重复创建转入现有单继续编辑;PDA 完成不自动推进拖车。附件为平台作用域且不重复提单文件;Backend `TruckAppointmentService`、`truck-appointments-v1.yaml` |
|
|
||||||
| 目的港码头拖车与还空预警 | 海外清关提柜工作台/详情 `modules/container-loading/pages/OverseasContainersView.vue`、`OverseasContainerDetailView.vue`,API `modules/container-loading/api/terminalDrayages.ts`、`containerArrivalTimes.ts` | 与订舱级拖车预约是不同生命周期;按 `containerBookingId` 读取服务端状态、`allowedActions` 和历史,不能复用订舱级拖车表单或自行推进状态。列表“预计到仓”列直接提供人工日期时间选择器,保存时通过 Lastleg 柜级版本和幂等键原子更新该柜全部尾程订单,已有入库计划后禁止修改;“实际到仓”只读 `ll_receiving_container_session.receiving_at`,即海外 PDA 首次开始收货时间。还空截止、超时天/小时只展示服务端基于权威卸柜完成时间加 72 小时计算的结果;Backend `firstleg/terminaldrayage/`、`lastleg-service/`,邮件记录通过 `terminalDrayages.ts` 查询与重试。 |
|
|
||||||
| 历史报关协同与国内出仓 | `modules/customs/`、`modules/outbound-dispatch/` | `modules/customs/` 是历史报关案件/清单/代理提交与回执入口;装柜完成后的整柜退税/买单资料从货柜详情进入,不在旧模块复制;Backend `firstleg/outbound/dispatch/`、`firstleg/customs/`、`file/` |
|
|
||||||
| 主数据、下载、退避任务重试、审计 | `modules/master-data/`、`modules/downloads/pages/DownloadCenterView.vue`、`modules/audit/` | File 导出任务返回 `attemptCount/maxAttempts/nextRetryAt`;仅失败或已进入自动退避的等待任务显示重试,等待任务重试用于立即执行当前投递,不创建新任务;联查 `warehouse/`、`file/`、`audit-service/` |
|
|
||||||
| 海外接柜、入库、库存与库内服务 | `modules/overseas-warehouse/` | `gateway/`、`lastleg-service/`、`warehouse-overseas-service/`;与排车、出库、派送、异常退回和一件代发共同组成海外仓全流程 |
|
|
||||||
| 海外采购、卡车、散板 | `modules/overseas-business/` | `gateway/`、`lastleg-service/` |
|
|
||||||
| 海外仓业务合作仓与通用资料 | 合作仓 `modules/warehouses/`;报价/汇率/车辆 `modules/overseas-master-data/` | 国内 `warehouse/`、海外实际资源与服务 |
|
|
||||||
| 海外仓业务国内出仓后船节点 | `modules/port-schedules/`、`modules/ocean-bookings/`、货柜详情 | `firstleg/portschedule/`、`integration-service/`;预计节点只展示不推进实际进度,手工实际节点必须严格向后追加并防重复,十节点标准见 `../../docs/海外仓业务/船节点标准化契约.md` |
|
|
||||||
| 海外排车、出库与派送 | `modules/overseas-warehouse/AGENTS.md` | 按模块表定位排车、出库、派送页面及 API;履约边界在模块内维护 |
|
|
||||||
| 海外异常退回与客户回访 | `modules/overseas-warehouse/AGENTS.md` | 派送异常退回区别于退货库存;页面、API 与原子推进约束见模块指引 |
|
|
||||||
|
|
||||||
全量验收按业务从 `../../docs/订单与客户/`、`入库测量与计费/`、`国内货柜履约/`、`财务管理/` 选择最小契约;海外跨模块流程或入口不明时读 `../../docs/海外仓业务/README.md`,已定位局部任务直接沿模块入口。进度、排期或验收状态问题再读取对应进度表和报告。
|
|
||||||
|
|
||||||
散货托盘码打印:`modules/loading-lists/components/PalletLabelPrintDialog.vue`、`modules/loading-lists/api/platformLoadingLists.ts`,由货柜详情与装柜清单详情进入;先调用 `/pallet-labels/prepare` 获取服务端按 FBA 仓分组的冻结清单,再通过 `/pallet-labels/print` 下载 PDF。托盘码使用“真实柜号-FBA 地址内部编号-三位序号”,页面同时展示 FBA 仓码和内部编号;支持全部打印或按仓指定张数补打,一件代发托盘不在该清单,前端不生成或重新编号托盘码。
|
|
||||||
|
|
||||||
|
|
||||||
## 货柜工作台规则
|
|
||||||
|
|
||||||
- 国内“送柜报关”只消费 `/containers/domestic` 与服务端 `allowedActions`,承载模拟柜、订舱关联、智能装柜;模拟柜创建选择与智能装柜一致的 9 类计划渠道,未关联订舱前实际渠道为空,订舱关联候选按计划渠道组匹配并同时展示订舱号与提单号、装柜清单页签、出口报关和国内出仓;创建柜次时自动生成唯一预装计划,预装详情先调用 `/loading-plans/{planId}/lifecycle`,完成后深链进入国内货柜详情的装柜清单页签,独立装柜清单导航 `/loading-lists` 复用已确认清单 API,查看进入独立详情路由 `/loading-lists/:planId`,保留返回列表和打印;独立清单详情与货柜清单页签共同使用 `useLoadingListDetail.ts` 加载、校验和处理错误,`LoadingListDetailDrawer.vue` 统一密度、摘要、明细、历史及打印入口,打印实现归 `printLoadingList.ts`,外层只保留返回目标与货柜专属 PDA/报关区域;货柜列表经 `ContainerWorkbenchView.vue` 在国内装柜与海外清关提柜之间按权限切换。订舱关联允许真实集装箱号为空,但确认预装和创建 PDA 任务前必须补齐;历史已建但缺号的任务仍可在预装详情首次补录,保存后恢复 PDA 可进入状态;全买单柜继续使用 `complete-all-buy`。海外“清关提柜”只消费 `/containers/overseas`,承载船节点、目的港清关、DO/PU、码头车队和还空;原预约/实际提柜展示位改为整柜预计/实际到仓,预计到仓在列表内人工快捷维护并经海外接口同步整柜尾程订单,实际到仓只读海外 PDA 首次开始收货时间。还空截止事实由服务端基于卸柜完成时间加 72 小时计算,前端不重算。两端统一使用 `containerBookingId`,列表范围由服务端 `scope=ACTIVE/HISTORY` 分页,禁止浏览器筛选或本地推导写资格。后端为 `LoadingListService`、`firstleg/customs/container/`、`firstleg/terminaldrayage/` 和 `lastleg-service/`,文件归 `file/`
|
|
||||||
|
|
||||||
## 海外模块内部快速索引(海外仓全流程)
|
|
||||||
|
|
||||||
- 海外仓的尾程订单控制与柜级入仓计划转换、退货库存、排车出库、异常回访:读取 `src/modules/overseas-warehouse/AGENTS.md`,字段与流程仅在该模块维护。
|
|
||||||
|
|
||||||
| 关键词 | 页面/路由入口 | API 与联查 |
|
|
||||||
|---|---|---|
|
|
||||||
| 海外采购 | `modules/overseas-business/pages/PurchaseOrdersView.vue`、详情/编辑页 | `modules/overseas-business/api/platformOverseasBusiness.ts` 的 purchase 方法;Backend `lastleg-service/procurement/` |
|
|
||||||
| 美国卡车、本土散板 | `modules/overseas-business/pages/TransportOrdersView.vue`、`TransportOrderFormView.vue` | 同一 API 的 us-truck/looseboard 方法;Backend `lastleg-service/trucking/`、`looseboard/` |
|
|
||||||
| 海外报价、月度汇率、车辆 | `modules/overseas-master-data/pages/OverseasQuotesView.vue`、`ExchangeRatesView.vue`、`VehiclesView.vue` | `modules/overseas-master-data/api/overseasMasterData.ts`;Backend `lastleg-service/masterdata/` |
|
|
||||||
| 司机档案、驾驶证、到期提醒与资格预览 | `modules/overseas-master-data/pages/DriversView.vue`、`DriverDetailView.vue`;最近指引 `modules/overseas-master-data/AGENTS.md` | `api/drivers.ts`;Backend `lastleg-service/fleet/driver/`、File `FLEET_DRIVER_LICENSE` |
|
|
||||||
+2
-3
@@ -5,9 +5,8 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite --host 0.0.0.0 --port 5173",
|
"dev": "vite --host 0.0.0.0 --port 5173",
|
||||||
"build": "vue-tsc --noEmit -p tsconfig.app.json && vite build",
|
"build": "vue-tsc --noEmit && vite build",
|
||||||
"typecheck": "vue-tsc --noEmit -p tsconfig.app.json",
|
"typecheck": "vue-tsc --noEmit",
|
||||||
"typecheck:all": "vue-tsc --noEmit -p tsconfig.json",
|
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:phase4:test": "node scripts/phase4-test-frontend-acceptance.mjs",
|
"test:phase4:test": "node scripts/phase4-test-frontend-acceptance.mjs",
|
||||||
"preview": "vite preview --port 4173"
|
"preview": "vite preview --port 4173"
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
import { defineComponent, markRaw } from 'vue'
|
import { defineComponent } from 'vue'
|
||||||
import { readFileSync } from 'node:fs'
|
|
||||||
import { resolve } from 'node:path'
|
|
||||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||||
import { ElMenu, ElMenuItem, ElSubMenu } from 'element-plus'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { describe, expect, it, vi } from 'vitest'
|
|
||||||
import { adminNavigation, filterAdminNavigation, type AdminNavigationNode } from '@/core/navigation/adminNavigation'
|
import { adminNavigation, filterAdminNavigation, type AdminNavigationNode } from '@/core/navigation/adminNavigation'
|
||||||
import AdminSidebarMenu from './AdminSidebarMenu.vue'
|
import AdminSidebarMenu from './AdminSidebarMenu.vue'
|
||||||
|
|
||||||
@@ -88,72 +85,6 @@ describe('AdminSidebarMenu', () => {
|
|||||||
expect(wrapper.get('nav').attributes('data-collapsed')).toBe('true')
|
expect(wrapper.get('nav').attributes('data-collapsed')).toBe('true')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('fits collapsed icons inside the scrolling rail and keeps hover submenus outside it', async () => {
|
|
||||||
const host = document.createElement('div')
|
|
||||||
host.className = 'app-shell is-collapsed'
|
|
||||||
host.innerHTML = '<aside class="app-sidebar"><nav class="side-nav"></nav></aside>'
|
|
||||||
document.body.append(host)
|
|
||||||
const style = document.createElement('style')
|
|
||||||
style.textContent = readFileSync(resolve(process.cwd(), 'src/styles/shell.css'), 'utf8')
|
|
||||||
document.head.append(style)
|
|
||||||
const rail = host.querySelector<HTMLElement>('.side-nav')!
|
|
||||||
const router = routerPlugin()
|
|
||||||
await router.push('/')
|
|
||||||
const icon = markRaw(adminNavigation[0].icon)
|
|
||||||
const items: AdminNavigationNode[] = [
|
|
||||||
{ key: 'home', title: '首页', icon, path: '/' },
|
|
||||||
{
|
|
||||||
key: 'resources', title: '资源管理', icon,
|
|
||||||
children: [{ key: 'warehouses', title: '仓库管理', icon, path: '/warehouses' }],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
const wrapper = mount(AdminSidebarMenu, {
|
|
||||||
attachTo: rail,
|
|
||||||
props: { items, activePath: '/', collapsed: true },
|
|
||||||
global: { plugins: [router], components: { ElMenu, ElMenuItem, ElSubMenu }, stubs: { transition: false } },
|
|
||||||
})
|
|
||||||
try {
|
|
||||||
await flushPromises()
|
|
||||||
const menu = wrapper.get('.side-nav-menu.el-menu--collapse')
|
|
||||||
const group = wrapper.get('.side-nav-menu > .el-sub-menu')
|
|
||||||
const leafTrigger = wrapper.get('.el-menu-tooltip__trigger')
|
|
||||||
expect(getComputedStyle(host.querySelector('.app-sidebar')!).width).toBe('76px')
|
|
||||||
expect(getComputedStyle(rail).overflowX).toBe('hidden')
|
|
||||||
expect(getComputedStyle(rail).overflowY).toBe('auto')
|
|
||||||
expect(getComputedStyle(menu.element).width).toBe('100%')
|
|
||||||
for (const trigger of [leafTrigger, group.get('.el-sub-menu__title')]) {
|
|
||||||
expect(getComputedStyle(trigger.element).paddingLeft).toBe('0px')
|
|
||||||
expect(getComputedStyle(trigger.element).paddingRight).toBe('0px')
|
|
||||||
expect(getComputedStyle(trigger.element).justifyContent).toBe('center')
|
|
||||||
expect(getComputedStyle(trigger.get('.menu-icon').element).marginRight).toBe('0px')
|
|
||||||
}
|
|
||||||
|
|
||||||
await group.trigger('mouseenter')
|
|
||||||
await vi.waitFor(() => expect(group.attributes('aria-expanded')).toBe('true'))
|
|
||||||
const popup = document.body.querySelector('.shell-nav-popper .el-menu--popup')
|
|
||||||
expect(popup).not.toBeNull()
|
|
||||||
expect(popup?.closest('.side-nav')).toBeNull()
|
|
||||||
expect(popup?.textContent).toContain('仓库管理')
|
|
||||||
|
|
||||||
const destination = popup!.querySelector<HTMLElement>('.el-menu-item')!
|
|
||||||
destination.focus()
|
|
||||||
expect(document.activeElement).toBe(destination)
|
|
||||||
expect(destination.getAttribute('role')).toBe('menuitem')
|
|
||||||
destination.click()
|
|
||||||
await flushPromises()
|
|
||||||
expect(router.currentRoute.value.path).toBe('/warehouses')
|
|
||||||
|
|
||||||
await wrapper.setProps({ collapsed: false })
|
|
||||||
host.classList.remove('is-collapsed')
|
|
||||||
expect(getComputedStyle(host.querySelector('.app-sidebar')!).width).toBe('240px')
|
|
||||||
expect(wrapper.find('.el-menu--collapse').exists()).toBe(false)
|
|
||||||
} finally {
|
|
||||||
wrapper.unmount()
|
|
||||||
style.remove()
|
|
||||||
host.remove()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
it('renders only entries included in the filtered navigation input', () => {
|
it('renders only entries included in the filtered navigation input', () => {
|
||||||
const items = filterAdminNavigation(adminNavigation, new Set(['platform:permission:list']))
|
const items = filterAdminNavigation(adminNavigation, new Set(['platform:permission:list']))
|
||||||
const wrapper = mount(AdminSidebarMenu, {
|
const wrapper = mount(AdminSidebarMenu, {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ defineProps<{
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<el-sub-menu v-if="node.children?.length" :index="node.key" popper-class="admin-workbench shell-nav-popper">
|
<el-sub-menu v-if="node.children?.length" :index="node.key">
|
||||||
<template #title>
|
<template #title>
|
||||||
<component
|
<component
|
||||||
v-if="!level"
|
v-if="!level"
|
||||||
|
|||||||
@@ -44,17 +44,6 @@ describe('WorkspaceTabs', () => {
|
|||||||
})
|
})
|
||||||
afterEach(() => { document.body.innerHTML = '' })
|
afterEach(() => { document.body.innerHTML = '' })
|
||||||
|
|
||||||
it('retains its own theme on the teleported management menu', async () => {
|
|
||||||
const { wrapper } = await mountTabs()
|
|
||||||
await wrapper.get('[aria-label="页签管理"]').trigger('click')
|
|
||||||
await flushPromises()
|
|
||||||
|
|
||||||
const popper = document.body.querySelector('.shell-header-popper')
|
|
||||||
expect(popper?.classList.contains('admin-workbench')).toBe(true)
|
|
||||||
expect(popper?.closest('.workspace-tabs')).toBeNull()
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps a dirty tab open when discard confirmation is cancelled', async () => {
|
it('keeps a dirty tab open when discard confirmation is cancelled', async () => {
|
||||||
const { wrapper, workspace, unsaved } = await mountTabs()
|
const { wrapper, workspace, unsaved } = await mountTabs()
|
||||||
unsaved.upsert({ key: 'customer-form', label: '客户资料', dirty: true, requiredPermission: null, workspaceTabId: 'customers' })
|
unsaved.upsert({ key: 'customer-form', label: '客户资料', dirty: true, requiredPermission: null, workspaceTabId: 'customers' })
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import '@/styles/adminDensity.css'
|
import '@/styles/adminDensity.css'
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import { computed, nextTick, ref, watch } from 'vue'
|
import { computed, nextTick, ref, watch } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
@@ -126,7 +125,7 @@ watch(
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="workspace-tabs admin-workbench" aria-label="页面工作区">
|
<section class="workspace-tabs" aria-label="页面工作区">
|
||||||
<div ref="tabListRef" class="workspace-tab-list" role="tablist" aria-label="已打开页面" @wheel="handleTabWheel">
|
<div ref="tabListRef" class="workspace-tab-list" role="tablist" aria-label="已打开页面" @wheel="handleTabWheel">
|
||||||
<div
|
<div
|
||||||
v-for="(tab, index) in workspace.tabs"
|
v-for="(tab, index) in workspace.tabs"
|
||||||
@@ -157,7 +156,7 @@ watch(
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<el-dropdown trigger="click" placement="bottom-end" popper-class="admin-workbench shell-header-popper" @command="handleCommand">
|
<el-dropdown trigger="click" placement="bottom-end" @command="handleCommand">
|
||||||
<el-button class="workspace-tab-more" text aria-label="页签管理" title="页签管理">
|
<el-button class="workspace-tab-more" text aria-label="页签管理" title="页签管理">
|
||||||
<MoreHorizontal :size="18" aria-hidden="true" />
|
<MoreHorizontal :size="18" aria-hidden="true" />
|
||||||
</el-button>
|
</el-button>
|
||||||
@@ -182,8 +181,9 @@ watch(
|
|||||||
min-width: 0;
|
min-width: 0;
|
||||||
height: 44px;
|
height: 44px;
|
||||||
align-items: stretch;
|
align-items: stretch;
|
||||||
border-bottom: 1px solid var(--workbench-border);
|
border-bottom: 1px solid var(--cc-border);
|
||||||
background: var(--workbench-surface);
|
background: #f7f9fc;
|
||||||
|
box-shadow: 0 5px 14px rgba(23, 42, 70, .045);
|
||||||
}
|
}
|
||||||
.workspace-tab-list {
|
.workspace-tab-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -208,10 +208,10 @@ watch(
|
|||||||
border: 1px solid transparent;
|
border: 1px solid transparent;
|
||||||
border-bottom: 0;
|
border-bottom: 0;
|
||||||
border-radius: 8px 8px 0 0;
|
border-radius: 8px 8px 0 0;
|
||||||
color: var(--workbench-muted);
|
color: #526178;
|
||||||
}
|
}
|
||||||
.workspace-tab:hover { background: var(--workbench-surface-soft); color: var(--workbench-text); }
|
.workspace-tab:hover { background: #eef3fa; color: #24344d; }
|
||||||
.workspace-tab.is-active { border-color: var(--workbench-accent-border); background: var(--workbench-accent-soft); color: var(--workbench-primary); }
|
.workspace-tab.is-active { border-color: var(--cc-border); background: #fff; color: #172033; }
|
||||||
.workspace-tab-activate {
|
.workspace-tab-activate {
|
||||||
display: flex;
|
display: flex;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
@@ -239,19 +239,19 @@ watch(
|
|||||||
border: 0;
|
border: 0;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
color: var(--workbench-muted);
|
color: #7b8799;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.workspace-tab-close:hover { background: var(--workbench-accent-border); color: var(--workbench-primary); }
|
.workspace-tab-close:hover { background: #dde6f2; color: #26364d; }
|
||||||
.workspace-tab-activate:focus-visible,
|
.workspace-tab-activate:focus-visible,
|
||||||
.workspace-tab-close:focus-visible { outline: 2px solid var(--workbench-primary); outline-offset: -2px; }
|
.workspace-tab-close:focus-visible { outline: 2px solid var(--cc-primary); outline-offset: -2px; }
|
||||||
.workspace-tab-more { width: 44px; height: 44px; flex: 0 0 44px; border-radius: 0; border-left: 1px solid var(--workbench-border); color: var(--workbench-muted); }
|
.workspace-tab-more { width: 44px; height: 44px; flex: 0 0 44px; border-radius: 0; border-left: 1px solid var(--cc-border); color: #526178; }
|
||||||
|
|
||||||
@media (max-width: 720px) {
|
@media (max-width: 720px) {
|
||||||
.workspace-tabs { top: 64px; height: 48px; }
|
.workspace-tabs { top: 64px; height: 48px; }
|
||||||
.workspace-tab-list { align-items: center; padding: 4px 6px; }
|
.workspace-tab-list { align-items: center; padding: 4px 6px; }
|
||||||
.workspace-tab { min-width: 140px; height: 40px; border-bottom: 1px solid transparent; border-radius: 8px; }
|
.workspace-tab { min-width: 140px; height: 40px; border-bottom: 1px solid transparent; border-radius: 8px; }
|
||||||
.workspace-tab.is-active { border-color: var(--workbench-accent-border); }
|
.workspace-tab.is-active { border-color: #cbd7e7; }
|
||||||
.workspace-tab-close { width: 34px; height: 34px; flex-basis: 34px; }
|
.workspace-tab-close { width: 34px; height: 34px; flex-basis: 34px; }
|
||||||
.workspace-tab-more { height: 48px; }
|
.workspace-tab-more { height: 48px; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,8 +114,7 @@ describe('AppLayout', () => {
|
|||||||
|
|
||||||
it('shows the authenticated identity and the localhost full-access control', async () => {
|
it('shows the authenticated identity and the localhost full-access control', async () => {
|
||||||
const { wrapper } = await mountLayout()
|
const { wrapper } = await mountLayout()
|
||||||
expect(wrapper.get('.user-copy').text()).toBe('平台管理员(admin)')
|
expect(wrapper.text()).toContain('登录身份:平台管理员(admin)')
|
||||||
expect(wrapper.get('.user-copy').attributes('aria-label')).toBe('登录身份:平台管理员(admin)')
|
|
||||||
const accessToggle = wrapper.get('[role="switch"]')
|
const accessToggle = wrapper.get('[role="switch"]')
|
||||||
expect(accessToggle.text()).toContain('本地全权限')
|
expect(accessToggle.text()).toContain('本地全权限')
|
||||||
expect(accessToggle.text()).toContain('已关闭')
|
expect(accessToggle.text()).toContain('已关闭')
|
||||||
@@ -131,29 +130,10 @@ describe('AppLayout', () => {
|
|||||||
expect(notificationTrigger.find('.notification-count').exists()).toBe(false)
|
expect(notificationTrigger.find('.notification-count').exists()).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('avoids repeating identical display names and accounts while retaining the full accessible identity', async () => {
|
|
||||||
const { wrapper } = await mountLayout()
|
|
||||||
const auth = useAuthStore()
|
|
||||||
auth.user = { ...auth.user!, name: 'admin', account: 'admin' }
|
|
||||||
await wrapper.vm.$nextTick()
|
|
||||||
|
|
||||||
expect(wrapper.get('.user-copy').text()).toBe('admin')
|
|
||||||
expect(wrapper.get('.user-copy').attributes('aria-label')).toBe('登录身份:admin(admin)')
|
|
||||||
expect(wrapper.get('.user-copy').attributes('title')).toBe('登录身份:admin(admin)')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('limits the shell theme to navigation and header instead of inheriting it into routed pages', async () => {
|
|
||||||
const { wrapper } = await mountLayout('/customers')
|
|
||||||
|
|
||||||
expect(wrapper.get('.app-sidebar').classes()).toContain('admin-workbench')
|
|
||||||
expect(wrapper.get('.app-header').classes()).toContain('admin-workbench')
|
|
||||||
expect(wrapper.get('.cached-count').element.closest('.admin-workbench')).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('hides the shell heading when the route opts out', async () => {
|
it('hides the shell heading when the route opts out', async () => {
|
||||||
const { wrapper } = await mountLayout('/customers')
|
const { wrapper } = await mountLayout('/customers')
|
||||||
expect(wrapper.find('.page-heading').exists()).toBe(false)
|
expect(wrapper.find('.page-heading').exists()).toBe(false)
|
||||||
expect(wrapper.get('.user-copy').attributes('aria-label')).toBe('登录身份:平台管理员(admin)')
|
expect(wrapper.text()).toContain('登录身份:平台管理员(admin)')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('logs out after confirmation', async () => {
|
it('logs out after confirmation', async () => {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import '@/styles/adminDensity.css'
|
import '@/styles/adminDensity.css'
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
@@ -27,12 +26,9 @@ const collapsed = ref(false)
|
|||||||
const mobileMenuOpen = ref(false)
|
const mobileMenuOpen = ref(false)
|
||||||
const isMobileViewport = ref(false)
|
const isMobileViewport = ref(false)
|
||||||
let mobileViewportMedia: MediaQueryList | undefined
|
let mobileViewportMedia: MediaQueryList | undefined
|
||||||
|
const pageTitle = computed(() => route.meta.title || '管理后台')
|
||||||
|
const pageDescription = computed(() => route.meta.description || '')
|
||||||
const showPageHeading = computed(() => route.meta.showPageHeading !== false)
|
const showPageHeading = computed(() => route.meta.showPageHeading !== false)
|
||||||
const userIdentity = computed(() => {
|
|
||||||
const name = auth.user?.name, account = auth.user?.account
|
|
||||||
return name && account && name !== account ? `${name}(${account})` : name || account || '—'
|
|
||||||
})
|
|
||||||
const userIdentityLabel = computed(() => `登录身份:${auth.user?.name ?? '-'}(${auth.user?.account ?? '-'})`)
|
|
||||||
const menuCollapsed = computed(() => collapsed.value && !mobileMenuOpen.value)
|
const menuCollapsed = computed(() => collapsed.value && !mobileMenuOpen.value)
|
||||||
const menuButtonLabel = computed(() => {
|
const menuButtonLabel = computed(() => {
|
||||||
if (isMobileViewport.value) return mobileMenuOpen.value ? '关闭菜单' : '打开菜单'
|
if (isMobileViewport.value) return mobileMenuOpen.value ? '关闭菜单' : '打开菜单'
|
||||||
@@ -143,7 +139,7 @@ watch(() => auth.user?.id || auth.user?.account || '', (userId, previousUserId)
|
|||||||
<template>
|
<template>
|
||||||
<div class="app-shell" :class="{ 'is-collapsed': collapsed, 'is-mobile-open': mobileMenuOpen }">
|
<div class="app-shell" :class="{ 'is-collapsed': collapsed, 'is-mobile-open': mobileMenuOpen }">
|
||||||
<button v-if="mobileMenuOpen" class="sidebar-scrim" type="button" aria-label="关闭菜单" @click="mobileMenuOpen = false" />
|
<button v-if="mobileMenuOpen" class="sidebar-scrim" type="button" aria-label="关闭菜单" @click="mobileMenuOpen = false" />
|
||||||
<aside class="app-sidebar admin-workbench">
|
<aside class="app-sidebar">
|
||||||
<div class="brand-block">
|
<div class="brand-block">
|
||||||
<img class="brand-logo brand-logo-full" :src="baiyueLogoWhite" alt="柏悦物流" />
|
<img class="brand-logo brand-logo-full" :src="baiyueLogoWhite" alt="柏悦物流" />
|
||||||
<img class="brand-logo brand-logo-mark" :src="baiyueMarkWhite" alt="柏悦物流" />
|
<img class="brand-logo brand-logo-mark" :src="baiyueMarkWhite" alt="柏悦物流" />
|
||||||
@@ -154,7 +150,7 @@ watch(() => auth.user?.id || auth.user?.account || '', (userId, previousUserId)
|
|||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<div class="app-main">
|
<div class="app-main">
|
||||||
<header class="app-header admin-workbench" :class="{ 'app-header--without-page-heading': !showPageHeading }">
|
<header class="app-header" :class="{ 'app-header--without-page-heading': !showPageHeading }">
|
||||||
<button
|
<button
|
||||||
class="shell-menu-button"
|
class="shell-menu-button"
|
||||||
type="button"
|
type="button"
|
||||||
@@ -162,12 +158,13 @@ watch(() => auth.user?.id || auth.user?.account || '', (userId, previousUserId)
|
|||||||
:aria-expanded="menuExpanded"
|
:aria-expanded="menuExpanded"
|
||||||
@click="handleMenuToggle"
|
@click="handleMenuToggle"
|
||||||
><Menu :size="22" /></button>
|
><Menu :size="22" /></button>
|
||||||
<div v-if="showPageHeading" class="page-heading" aria-hidden="true" />
|
<div v-if="showPageHeading" class="page-heading">
|
||||||
|
<!-- <h1>{{ pageTitle }}</h1><p v-if="pageDescription">{{ pageDescription }}</p> -->
|
||||||
|
</div>
|
||||||
<div class="header-user">
|
<div class="header-user">
|
||||||
<button
|
<button
|
||||||
v-if="access.localFullAccessAvailable"
|
v-if="access.localFullAccessAvailable"
|
||||||
class="local-full-access-toggle workbench-tone"
|
class="local-full-access-toggle"
|
||||||
:data-tone="access.localFullAccessEnabled ? 'green' : 'blue'"
|
|
||||||
type="button"
|
type="button"
|
||||||
role="switch"
|
role="switch"
|
||||||
:aria-checked="access.localFullAccessEnabled"
|
:aria-checked="access.localFullAccessEnabled"
|
||||||
@@ -178,7 +175,7 @@ watch(() => auth.user?.id || auth.user?.account || '', (userId, previousUserId)
|
|||||||
<span>本地全权限</span>
|
<span>本地全权限</span>
|
||||||
<strong>{{ access.localFullAccessEnabled ? '已开启' : '已关闭' }}</strong>
|
<strong>{{ access.localFullAccessEnabled ? '已开启' : '已关闭' }}</strong>
|
||||||
</button>
|
</button>
|
||||||
<el-dropdown v-if="canOpenNotificationManagement" trigger="click" placement="bottom-end" popper-class="admin-workbench shell-header-popper">
|
<el-dropdown v-if="canOpenNotificationManagement" trigger="click" placement="bottom-end">
|
||||||
<button class="notification-trigger" type="button" aria-label="消息中心">
|
<button class="notification-trigger" type="button" aria-label="消息中心">
|
||||||
<Bell :size="18" /><span>消息中心</span>
|
<Bell :size="18" /><span>消息中心</span>
|
||||||
</button>
|
</button>
|
||||||
@@ -189,7 +186,7 @@ watch(() => auth.user?.id || auth.user?.account || '', (userId, previousUserId)
|
|||||||
</el-dropdown-menu></template>
|
</el-dropdown-menu></template>
|
||||||
</el-dropdown>
|
</el-dropdown>
|
||||||
<div class="user-avatar">{{ auth.user?.name.slice(0, 1) }}</div>
|
<div class="user-avatar">{{ auth.user?.name.slice(0, 1) }}</div>
|
||||||
<div class="user-copy" :aria-label="userIdentityLabel" :title="userIdentityLabel"><strong>{{ userIdentity }}</strong></div>
|
<div class="user-copy" :aria-label="`登录身份:${auth.user?.name ?? '-'}(${auth.user?.account ?? '-'})`"><strong>登录身份:{{ auth.user?.name }}({{ auth.user?.account }})</strong></div>
|
||||||
<el-button text aria-label="退出登录" @click="handleLogout"><LogOut :size="18" /></el-button>
|
<el-button text aria-label="退出登录" @click="handleLogout"><LogOut :size="18" /></el-button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -212,14 +209,14 @@ watch(() => auth.user?.id || auth.user?.account || '', (userId, previousUserId)
|
|||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.app-header--without-page-heading .header-user { margin-left: auto; }
|
.app-header--without-page-heading .header-user { margin-left: auto; }
|
||||||
.local-full-access-toggle { display: inline-flex; height: 38px; align-items: center; gap: 7px; padding: 0 11px; border: 1px solid var(--workbench-border); border-radius: 10px; background: var(--workbench-surface); color: var(--workbench-muted); font: inherit; font-size: 13px; cursor: pointer; transition: background .2s ease, border-color .2s ease; }
|
.local-full-access-toggle { display: inline-flex; height: 38px; align-items: center; gap: 7px; padding: 0 11px; border: 1px solid rgba(255, 255, 255, .3); border-radius: 10px; background: rgba(255, 255, 255, .12); color: #fff; font: inherit; font-size: 13px; cursor: pointer; transition: background .2s ease, border-color .2s ease; }
|
||||||
.local-full-access-toggle:hover { border-color: var(--workbench-accent-border); background: var(--workbench-accent-soft); }
|
.local-full-access-toggle:hover { border-color: rgba(255, 255, 255, .55); background: rgba(255, 255, 255, .22); }
|
||||||
.local-full-access-toggle:focus-visible { outline: 2px solid var(--workbench-primary); outline-offset: 2px; }
|
.local-full-access-toggle:focus-visible { outline: 2px solid rgba(255, 255, 255, .9); outline-offset: 2px; }
|
||||||
.local-full-access-toggle[aria-checked="true"] { border-color: var(--workbench-accent-border); background: var(--workbench-accent-soft); color: var(--workbench-accent); }
|
.local-full-access-toggle[aria-checked="true"] { border-color: #86efac; background: rgba(22, 163, 74, .3); }
|
||||||
.local-full-access-toggle strong { color: inherit; font-size: 12px; }
|
.local-full-access-toggle strong { color: #dcfce7; font-size: 12px; }
|
||||||
.notification-trigger { display: inline-flex; height: 38px; align-items: center; gap: 7px; padding: 0 12px; border: 1px solid var(--workbench-border); border-radius: 10px; background: var(--workbench-surface); color: var(--workbench-text); font: inherit; font-size: 13px; font-weight: 600; cursor: pointer; transition: background .2s ease, border-color .2s ease; }
|
.notification-trigger { display: inline-flex; height: 38px; align-items: center; gap: 7px; padding: 0 12px; border: 1px solid rgba(255, 255, 255, .28); border-radius: 10px; background: rgba(255, 255, 255, .12); color: #fff; font: inherit; font-size: 13px; font-weight: 600; cursor: pointer; transition: background .2s ease, border-color .2s ease, transform .2s ease; }
|
||||||
.notification-trigger:hover { border-color: var(--workbench-accent-border); background: var(--workbench-accent-soft); color: var(--workbench-primary); }
|
.notification-trigger:hover { border-color: rgba(255, 255, 255, .48); background: rgba(255, 255, 255, .24); transform: translateY(-1px); }
|
||||||
.notification-trigger:focus-visible { outline: 2px solid var(--workbench-primary); outline-offset: 2px; }
|
.notification-trigger:focus-visible { outline: 2px solid rgba(255, 255, 255, .9); outline-offset: 2px; }
|
||||||
.notification-trigger > svg { flex: 0 0 auto; }
|
.notification-trigger > svg { flex: 0 0 auto; }
|
||||||
@media (max-width: 720px) { .local-full-access-toggle > span { display: none; } .notification-trigger { width: 44px; height: 44px; justify-content: center; padding: 0; } .notification-trigger > span { display: none; } }
|
@media (max-width: 720px) { .local-full-access-toggle > span { display: none; } .notification-trigger { width: 44px; height: 44px; justify-content: center; padding: 0; } .notification-trigger > span { display: none; } }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import { computed } from 'vue'
|
import { computed } from 'vue'
|
||||||
import { ShieldX } from '@lucide/vue'
|
import { ShieldX } from '@lucide/vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
@@ -17,7 +16,7 @@ async function returnToAccessiblePage() {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="forbidden-page admin-workbench" aria-labelledby="forbidden-title">
|
<section class="forbidden-page" aria-labelledby="forbidden-title">
|
||||||
<div class="forbidden-icon" aria-hidden="true"><ShieldX :size="32" /></div>
|
<div class="forbidden-icon" aria-hidden="true"><ShieldX :size="32" /></div>
|
||||||
<p class="section-kicker">403 · 权限不足</p>
|
<p class="section-kicker">403 · 权限不足</p>
|
||||||
<h2 id="forbidden-title">当前登录账号无法访问此页面</h2>
|
<h2 id="forbidden-title">当前登录账号无法访问此页面</h2>
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { decodeJwtClaims } from './jwt'
|
|
||||||
|
|
||||||
function token(payload: string) {
|
|
||||||
return `header.${Buffer.from(payload).toString('base64url')}.signature`
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('JWT claim decoding', () => {
|
|
||||||
it.each(['2110664514823360515', '"2110664514823360515"'])('preserves the exact account ID encoded as %s', userId => {
|
|
||||||
const claims = decodeJwtClaims(token(`{"user_id":${userId},"app_code":"PLATFORM","exp":1792060000,"iat":1792058200}`))
|
|
||||||
expect(claims.user_id).toBe('2110664514823360515')
|
|
||||||
expect(claims.exp).toBe(1792060000)
|
|
||||||
expect(claims).toHaveProperty('iat', 1792058200)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('retains safe numeric IDs and ordinary claims', () => {
|
|
||||||
expect(decodeJwtClaims(token('{"user_id":123,"username":"operator","roles":["ADMIN"],"exp":1}')))
|
|
||||||
.toEqual({ user_id: 123, username: 'operator', roles: ['ADMIN'], exp: 1 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each(['', 'header..signature'])('rejects a missing payload: %s', value => {
|
|
||||||
expect(() => decodeJwtClaims(value)).toThrow('登录响应中的 accessToken 格式无效')
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each(['header.%.signature', token('{"user_id":2110664514823360515,')])('rejects malformed encoding or JSON: %s', value => {
|
|
||||||
expect(() => decodeJwtClaims(value)).toThrow('登录响应中的 accessToken 无法解析')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
import { parseJsonWithSafeIntegers } from '@chongchong/shared'
|
|
||||||
|
|
||||||
export interface PlatformJwtClaims {
|
export interface PlatformJwtClaims {
|
||||||
user_id?: string | number
|
user_id?: string | number
|
||||||
username?: string
|
username?: string
|
||||||
@@ -21,7 +19,7 @@ export function decodeJwtClaims(token: string): PlatformJwtClaims {
|
|||||||
const payload = token.split('.')[1]
|
const payload = token.split('.')[1]
|
||||||
if (!payload) throw new Error('登录响应中的 accessToken 格式无效')
|
if (!payload) throw new Error('登录响应中的 accessToken 格式无效')
|
||||||
try {
|
try {
|
||||||
return parseJsonWithSafeIntegers(decodeBase64Url(payload)) as PlatformJwtClaims
|
return JSON.parse(decodeBase64Url(payload)) as PlatformJwtClaims
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error('登录响应中的 accessToken 无法解析')
|
throw new Error('登录响应中的 accessToken 无法解析')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,22 +8,6 @@ import {
|
|||||||
} from './adminNavigation'
|
} from './adminNavigation'
|
||||||
|
|
||||||
describe('adminNavigation', () => {
|
describe('adminNavigation', () => {
|
||||||
it('keeps outsourced read access separate from owned access and write-only permissions', () => {
|
|
||||||
const read = filterAdminNavigation(adminNavigation, new Set(['platform:fleet:outsourced-business:list']))
|
|
||||||
const vehicle = read.find(node => node.key === 'vehicle-management')
|
|
||||||
expect(vehicle?.children?.map(node => node.path)).toEqual(['/overseas-master-data/outsourced-business'])
|
|
||||||
const write = filterAdminNavigation(adminNavigation, new Set(['platform:fleet:outsourced-business:edit', 'platform:fleet:outsourced-business:upload']))
|
|
||||||
expect(getNavigationLeaves(write).some(node => node.path === '/overseas-master-data/outsourced-business')).toBe(false)
|
|
||||||
})
|
|
||||||
it('places owned-business under vehicle management and keeps edit/upload from granting page access', () => {
|
|
||||||
const read = filterAdminNavigation(adminNavigation, new Set(['platform:fleet:owned-business:list']))
|
|
||||||
const vehicle = read.find(node => node.key === 'vehicle-management')
|
|
||||||
expect(vehicle?.children?.map(node => node.path)).toEqual(['/overseas-master-data/owned-business'])
|
|
||||||
const writeOnly = filterAdminNavigation(adminNavigation, new Set([
|
|
||||||
'platform:fleet:owned-business:edit', 'platform:fleet:owned-business:upload',
|
|
||||||
]))
|
|
||||||
expect(getNavigationLeaves(writeOnly).some(node => node.path === '/overseas-master-data/owned-business')).toBe(false)
|
|
||||||
})
|
|
||||||
it('opens all self-operated read pages with list permission and keeps sync alone insufficient', () => {
|
it('opens all self-operated read pages with list permission and keeps sync alone insufficient', () => {
|
||||||
const read = filterAdminNavigation(adminNavigation, new Set(['platform:self-operated-analytics:list']))
|
const read = filterAdminNavigation(adminNavigation, new Set(['platform:self-operated-analytics:list']))
|
||||||
expect(getNavigationLeaves(read).map(item => item.path)).toEqual([
|
expect(getNavigationLeaves(read).map(item => item.path)).toEqual([
|
||||||
@@ -47,16 +31,16 @@ describe('adminNavigation', () => {
|
|||||||
{ title: '货柜管理', children: ['订舱列表', '拖车列表', '货柜列表', '装柜清单', '预装清单'] },
|
{ title: '货柜管理', children: ['订舱列表', '拖车列表', '货柜列表', '装柜清单', '预装清单'] },
|
||||||
{ title: '海外尾程', children: ['尾程订单', '入库单', '废弃单', '出库单', '换标单', '派送单', '托盘管理', '库位管理', '库存管理', '退货库存管理', '退货箱号管理'] },
|
{ title: '海外尾程', children: ['尾程订单', '入库单', '废弃单', '出库单', '换标单', '派送单', '托盘管理', '库位管理', '库存管理', '退货库存管理', '退货箱号管理'] },
|
||||||
{ title: '预约管理', children: ['预约列表'] },
|
{ title: '预约管理', children: ['预约列表'] },
|
||||||
{ title: '车辆管理', children: ['排车列表', '车辆列表', '司机管理', '自有业务', '外配业务', '出车记录'] },
|
{ title: '车辆管理', children: ['排车列表', '车辆列表', '司机管理', '车次管理', '拼车接货', '出车记录'] },
|
||||||
{ title: '海外业务', children: ['采购订单', '本土卡车', '本土散板', '散板需求'] },
|
{ title: '海外业务', children: ['采购订单', '本土卡车', '本土散板'] },
|
||||||
{ title: '客户服务', children: ['异常订单'] },
|
{ title: '客户服务', children: ['异常订单'] },
|
||||||
{ title: '财务管理', children: ['客户账户', '客户应收应付', '应收款统计表', '客户对账单', '结算单应收', '结算单应付'] },
|
{ title: '财务管理', children: ['客户账户', '客户应收应付', '应收款统计表', '客户对账单', '结算单应收', '结算单应付'] },
|
||||||
{ title: '海外仓', children: ['经营总览', '销量分析', '库存分析', '数据采集'] },
|
{ title: '海外仓', children: ['经营总览', '销量分析', '库存分析', '数据采集'] },
|
||||||
{ title: '通用', children: ['费用项目', '汇率管理', '仓库管理', '海外仓报价', '车队报价', '船期价格表', '下载中心', '供应商列表'] },
|
{ title: '通用', children: ['费用项目', '汇率管理', '仓库管理', '海外仓报价', '车队报价', '船期价格表', '下载中心'] },
|
||||||
{ title: '系统管理', children: ['用户管理', '角色权限', '菜单权限'] },
|
{ title: '系统管理', children: ['用户管理', '角色权限', '菜单权限'] },
|
||||||
])
|
])
|
||||||
expect(visible).toHaveLength(13)
|
expect(visible).toHaveLength(13)
|
||||||
expect(visible.flatMap(node => node.children ?? [])).toHaveLength(58)
|
expect(visible.flatMap(node => node.children ?? [])).toHaveLength(56)
|
||||||
expect(adminNavigation.find((item) => item.key === 'notifications')).toBeUndefined()
|
expect(adminNavigation.find((item) => item.key === 'notifications')).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -212,15 +196,13 @@ describe('adminNavigation', () => {
|
|||||||
expect(getNavigationLeaves(filtered).map((item) => item.path)).toEqual(['/dashboard', '/master-data/fee-items'])
|
expect(getNavigationLeaves(filtered).map((item) => item.path)).toEqual(['/dashboard', '/master-data/fee-items'])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('shows the restored supplier entry under general only with its list permission', () => {
|
it('retains the supplier route permission while omitting its entry from the latest sidebar', () => {
|
||||||
const visible = filterAdminNavigation(adminNavigation, new Set(['platform:supplier:list']))
|
const visible = filterAdminNavigation(adminNavigation, new Set(['platform:supplier:list']))
|
||||||
const missing = filterAdminNavigation(adminNavigation, new Set())
|
const missing = filterAdminNavigation(adminNavigation, new Set())
|
||||||
|
|
||||||
expect(getNavigationLeaves(adminNavigation).find(item => item.path === '/suppliers')?.permission).toBe('platform:supplier:list')
|
expect(getNavigationLeaves(adminNavigation).find(item => item.path === '/suppliers')?.permission).toBe('platform:supplier:list')
|
||||||
expect(getNavigationLeaves(visible).map((item) => item.path)).toEqual(['/dashboard', '/suppliers'])
|
expect(getNavigationLeaves(visible).map((item) => item.path)).toEqual(['/dashboard'])
|
||||||
expect(visible.find(item => item.title === '通用')?.children?.map(item => item.path)).toEqual(['/suppliers'])
|
|
||||||
expect(getNavigationLeaves(missing).map((item) => item.path)).toEqual(['/dashboard'])
|
expect(getNavigationLeaves(missing).map((item) => item.path)).toEqual(['/dashboard'])
|
||||||
expect(getNavigationLeaves(filterAdminNavigation(adminNavigation, new Set(['platform:supplier:create', 'platform:supplier:edit']))).map(item => item.path)).toEqual(['/dashboard'])
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('shows split container workbenches without a standalone smart-loading menu', () => {
|
it('shows split container workbenches without a standalone smart-loading menu', () => {
|
||||||
|
|||||||
@@ -134,9 +134,8 @@ export const adminNavigation: AdminNavigationNode[] = [
|
|||||||
{ key: 'fba-dispatch', title: '排车列表', icon: Truck, path: '/overseas-warehouse/dispatches', permission: 'platform:overseas-warehouse:dispatch:list' },
|
{ key: 'fba-dispatch', title: '排车列表', icon: Truck, path: '/overseas-warehouse/dispatches', permission: 'platform:overseas-warehouse:dispatch:list' },
|
||||||
{ key: 'vehicle-list', title: '车辆列表', icon: Truck, path: '/overseas-master-data/vehicles', permission: 'platform:overseas-master-data:vehicle:list' },
|
{ key: 'vehicle-list', title: '车辆列表', icon: Truck, path: '/overseas-master-data/vehicles', permission: 'platform:overseas-master-data:vehicle:list' },
|
||||||
{ key: 'driver-management', title: '司机管理', icon: ContactRound, path: '/overseas-master-data/drivers', permission: 'platform:overseas-master-data:driver:list' },
|
{ key: 'driver-management', title: '司机管理', icon: ContactRound, path: '/overseas-master-data/drivers', permission: 'platform:overseas-master-data:driver:list' },
|
||||||
{ key: 'fleet-owned-business', title: '自有业务', icon: Truck, path: '/overseas-master-data/owned-business', permission: 'platform:fleet:owned-business:list' },
|
{ key: 'fleet-trips', title: '车次管理', icon: Truck, path: '/overseas-master-data/trips', permission: 'platform:fleet:trip:list' },
|
||||||
{ key: 'fleet-outsourced-business', title: '外配业务', icon: Truck, path: '/overseas-master-data/outsourced-business', permission: 'platform:fleet:outsourced-business:list' },
|
{ key: 'fleet-capacity-offers', title: '拼车接货', icon: Truck, path: '/overseas-master-data/capacity-offers', permission: 'platform:fleet:capacity-offer:list', permissionAnyOf: ['platform:fleet:capacity-offer:manage'] },
|
||||||
{ key: 'fleet-trips', title: '车次管理', icon: Truck, path: '/overseas-master-data/trips', permission: 'platform:fleet:trip:list', hidden: true },
|
|
||||||
{ key: 'fleet-operations', title: '出车记录', icon: Truck, path: '/overseas-master-data/trip-operations', permission: 'platform:fleet:operations:list' },
|
{ key: 'fleet-operations', title: '出车记录', icon: Truck, path: '/overseas-master-data/trip-operations', permission: 'platform:fleet:operations:list' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -148,7 +147,6 @@ export const adminNavigation: AdminNavigationNode[] = [
|
|||||||
{ key: 'overseas-purchase', title: '采购订单', icon: ClipboardList, path: '/overseas-business/purchases', permission: 'platform:overseas-business:purchase:list' },
|
{ key: 'overseas-purchase', title: '采购订单', icon: ClipboardList, path: '/overseas-business/purchases', permission: 'platform:overseas-business:purchase:list' },
|
||||||
{ key: 'overseas-truck', title: '本土卡车', icon: Truck, path: '/overseas-business/trucks', permission: 'platform:overseas-business:truck:list' },
|
{ key: 'overseas-truck', title: '本土卡车', icon: Truck, path: '/overseas-business/trucks', permission: 'platform:overseas-business:truck:list' },
|
||||||
{ key: 'overseas-looseboard', title: '本土散板', icon: ClipboardList, path: '/overseas-business/looseboards', permission: 'platform:overseas-business:looseboard:list' },
|
{ key: 'overseas-looseboard', title: '本土散板', icon: ClipboardList, path: '/overseas-business/looseboards', permission: 'platform:overseas-business:looseboard:list' },
|
||||||
{ key: 'fleet-capacity-offers', title: '散板需求', icon: Truck, path: '/overseas-master-data/capacity-offers', permission: 'platform:fleet:capacity-offer:list', permissionAnyOf: ['platform:fleet:capacity-offer:manage'] },
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -206,7 +204,7 @@ export const adminNavigation: AdminNavigationNode[] = [
|
|||||||
{ key: 'fleet-quotes', title: '车队报价', icon: Truck, path: '/overseas-master-data/fleet-quotes', permission: 'platform:fleet:quote:list' },
|
{ key: 'fleet-quotes', title: '车队报价', icon: Truck, path: '/overseas-master-data/fleet-quotes', permission: 'platform:fleet:quote:list' },
|
||||||
{ key: 'fba-carrier-rates', title: '船期价格表', icon: CircleDollarSign, path: '/first-leg-pricing/carrier-rates', permission: 'firstleg:fba-pricing:rate:view' },
|
{ key: 'fba-carrier-rates', title: '船期价格表', icon: CircleDollarSign, path: '/first-leg-pricing/carrier-rates', permission: 'firstleg:fba-pricing:rate:view' },
|
||||||
{ key: 'download-center', title: '下载中心', icon: Download, path: '/downloads', permission: 'platform:download:list' },
|
{ key: 'download-center', title: '下载中心', icon: Download, path: '/downloads', permission: 'platform:download:list' },
|
||||||
{ key: 'supplier-list', title: '供应商列表', icon: ContactRound, path: '/suppliers', permission: 'platform:supplier:list' },
|
{ key: 'supplier-list', title: '供应商列表', icon: ContactRound, path: '/suppliers', permission: 'platform:supplier:list', hidden: true },
|
||||||
{ key: 'express-companies', title: '快递公司', icon: Truck, path: '/master-data/express-companies', permission: 'platform:express:list', hidden: true },
|
{ key: 'express-companies', title: '快递公司', icon: Truck, path: '/master-data/express-companies', permission: 'platform:express:list', hidden: true },
|
||||||
{ key: 'counterparties', title: '往来单位', icon: ContactRound, path: '/master-data/counterparties', permission: 'platform:counterparty:list', hidden: true },
|
{ key: 'counterparties', title: '往来单位', icon: ContactRound, path: '/master-data/counterparties', permission: 'platform:counterparty:list', hidden: true },
|
||||||
{ key: 'mojia-sku-sync', title: '称重机器', icon: Database, path: '/general/mojia-sku-sync', permission: 'platform:mojia-sku-sync:list', hidden: true },
|
{ key: 'mojia-sku-sync', title: '称重机器', icon: Database, path: '/general/mojia-sku-sync', permission: 'platform:mojia-sku-sync:list', hidden: true },
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
# Admin 预约日历模块指引
|
|
||||||
|
|
||||||
## 路径基准与读取顺序
|
|
||||||
|
|
||||||
- 本文件适用于 `src/modules/appointment-calendar/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`,预约规则见 `../../../docs/business-index.md`;工作日历正式规则在**工作区** `docs/海外仓业务/预约工作日历V13变更说明.md`。
|
|
||||||
- 本模块扁平存放页面、面板与 API,无 `pages/`、`components/` 分层:`*.vue` 多为面板,`*Api.ts` 为对应接口,`calendar.ts`/`schedule.ts`/`tripCalendar.ts` 为日历与航段计算,`useWorkDraft.ts`/`useWorkSyncRead.ts` 为草稿与只读同步。
|
|
||||||
- 后端只查 `lastleg-service/`(`inboundplan/`、`appointmentplanning/`);到港事实只读 `firstleg/` 的船节点,纯页面与文案不读后端。
|
|
||||||
|
|
||||||
## 页面与入口
|
|
||||||
|
|
||||||
| 目标 | 入口 | API 与后端 |
|
|
||||||
|---|---|---|
|
|
||||||
| 预约列表与日历主页面 | `AppointmentCalendarView.vue`;`appointment-calendar` | `api.ts`、`calendar.ts`;`lastleg-service/inboundplan/` |
|
|
||||||
| 工作日历、车次与送仓待办 | `WorkCalendarPanel.vue`、`TripAppointmentPanel.vue` | `workApi.ts`、`tripCalendar.ts`;`lastleg-service/appointmentplanning/` |
|
|
||||||
| 新建/批量预约、多客户共车 | `AppointmentCreatePanel.vue`、`AppointmentBatchForm.vue`、`WorkSharedTripForm.vue` | `workApi.ts`、`batchApi.ts` |
|
|
||||||
| 货物验证与入仓码关系 | `AppointmentCargoPanel.vue`、`AppointmentCargoTabs.vue`、`AppointmentInboundCodes.vue`、`CargoVerificationForm.vue` | `cargoVerificationApi.ts` |
|
|
||||||
| 改期、取消与取消记录 | `AppointmentImpactDialog.vue`、`AppointmentCancellationDialog.vue`、`AppointmentCancellationHistory.vue`、`AppointmentCancellationRecords.vue` | `impactApi.ts` |
|
|
||||||
| 派送安排与分批后送 | `WorkDispatchForm.vue`、`WorkExistingDispatchForm.vue` | `workApi.ts`;`lastleg-service/delivery/` |
|
|
||||||
| 收货范围与收货计划 | `ReceivingScope.vue`、`WorkReceivingPanel.vue`、`WorkReceiptPlans.vue` | `receivingApi.ts` |
|
|
||||||
| 外部候选取货与跟进 | `AppointmentExternalCandidates.vue`、`AppointmentFollowupDialog.vue` | `planningApi.ts`、`workApi.ts` |
|
|
||||||
|
|
||||||
## 关键边界
|
|
||||||
|
|
||||||
- 同仓跨客户共用一张预约,客户归属在货物明细,不为每个客户拆预约;同车多客户按 V13 规则处理。
|
|
||||||
- 到港事实只读 Firstleg 船节点,送仓与排车归 Lastleg;不得用预计到港替代计划到仓,也不得反向写船节点。
|
|
||||||
- 改期、取消、重新预约必须按服务端影响范围与版本提交,取消记录只追加,不改写历史。
|
|
||||||
- 未定日期事项进入待办跟进,不伪造日期;分批后送的批次关系以服务端返回为准。
|
|
||||||
- 面板之间共享草稿状态,`useWorkDraft.ts` 是唯一草稿入口;刷新时用 `useWorkSyncRead.ts` 合并服务端事实并保留本机未提交输入。
|
|
||||||
|
|
||||||
## 验证
|
|
||||||
|
|
||||||
- 定向:`pnpm test src/modules/appointment-calendar/<目标测试>`;日历与批次规则变更同时核对 V13 规则文档与 `lastleg-service` 合同。
|
|
||||||
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
|
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
import { DatePickerStub, TimePickerStub } from './temporal-picker.test-support'
|
|
||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import AppointmentBatchForm from './AppointmentBatchForm.vue'
|
|
||||||
import { getAppointmentBatch, repartitionAppointments } from './batchApi'
|
|
||||||
import { getWorkItems } from './workApi'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
import { workItem } from './work.test-support'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => true }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn().mockResolvedValue(true) } }))
|
|
||||||
vi.mock('./batchApi', async original => ({ ...await original<typeof import('./batchApi')>(), getAppointmentBatch: vi.fn(), repartitionAppointments: vi.fn() }))
|
|
||||||
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), getWorkItems: vi.fn() }))
|
|
||||||
let guard: LeaveGuard
|
|
||||||
function render() { return mount(AppointmentBatchForm, { props: { batchKey: 'FBA_APPOINTMENT:1' }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: {
|
|
||||||
ElDatePicker: DatePickerStub, ElTimePicker: TimePickerStub,
|
|
||||||
ElButton: { props: ['nativeType', 'disabled'], template: '<button :type="nativeType || \'button\'" :disabled="disabled"><slot /></button>' },
|
|
||||||
LoadErrorState: { props: ['message'], template: '<section role="alert">{{ message }}<button @click="$emit(\'retry\')">重试读取</button></section>' }, ApiErrorMeta: true, CargoVerificationForm: true,
|
|
||||||
} } }) }
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks(); vi.mocked(getAppointmentBatch).mockResolvedValue(batchContext())
|
|
||||||
vi.mocked(repartitionAppointments).mockResolvedValue({ replacedBatchKeys: ['FBA_APPOINTMENT:1'], replacedAppointmentNos: ['AP-001'], appointments: [batchContext('AP-NEW-1', 'FBA_APPOINTMENT:11').appointment, batchContext('AP-NEW-2', 'FBA_APPOINTMENT:12').appointment] })
|
|
||||||
vi.mocked(getWorkItems).mockResolvedValue({ records: [workItem({ batchKey: 'FBA_APPOINTMENT:2' })], page: 1, size: 8, total: 1, pages: 1 })
|
|
||||||
})
|
|
||||||
it('submits two conservative allocations without fake confirmation times and renders replacement business numbers', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.get('[aria-label="来源1分出箱数"]').setValue(20)
|
|
||||||
await wrapper.findAll('textarea')[0]!.setValue('分两次送仓'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const request = vi.mocked(repartitionAppointments).mock.calls[0]![0]
|
|
||||||
expect(request.originals).toEqual([{ appointmentNo: 'AP-001', version: 3 }])
|
|
||||||
expect(request.batches.map(row => row.plannedDate)).toEqual([null, null])
|
|
||||||
expect(request.batches[0]!.allocations.map(row => row.packageCount)).toEqual([50, 30])
|
|
||||||
expect(request.batches[1]!.allocations.map(row => row.packageCount)).toEqual([20])
|
|
||||||
expect(request).not.toHaveProperty('appointmentAt')
|
|
||||||
expect(wrapper.text()).toContain('AP-NEW-1'); expect(wrapper.text()).not.toContain('FBA_APPOINTMENT:')
|
|
||||||
expect(wrapper.emitted('updated')).toHaveLength(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('splits only the entered 60-box later batch into 40/20, never reallocating its original 160-box source', async () => {
|
|
||||||
const context = batchContext('AP-LATER-60', 'FBA_APPOINTMENT:1')
|
|
||||||
context.appointment.items = [{ ...context.appointment.items[0]!, packageCount: 60 }]
|
|
||||||
context.sources = [{ ...context.sources[0]!, packageCount: 60, originalPackages: 160 }]
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.get('[aria-label="来源1分出箱数"]').setValue(20)
|
|
||||||
await wrapper.findAll('textarea')[0]!.setValue('本批40先安排,20待排')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const request = vi.mocked(repartitionAppointments).mock.calls[0]![0]
|
|
||||||
expect(request.originals).toEqual([{ appointmentNo: 'AP-LATER-60', version: 3 }])
|
|
||||||
expect(request.batches.map(batch => batch.allocations.map(row => row.packageCount))).toEqual([[40], [20]])
|
|
||||||
expect(request.batches.flatMap(batch => batch.allocations).every(row => row.customerId === 'customer-a' && row.sourceKey === 'ORDER:1')).toBe(true)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('locks an unknown outcome and retries the same immutable repartition command', async () => {
|
|
||||||
vi.mocked(repartitionAppointments).mockRejectedValueOnce(new Error('unknown outcome'))
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.get('[aria-label="来源1分出箱数"]').setValue(20); await wrapper.findAll('textarea')[0]!.setValue('分批')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const first = vi.mocked(repartitionAppointments).mock.calls[0]![0]
|
|
||||||
expect(await guard()).toBe(false); expect(wrapper.get('fieldset').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(repartitionAppointments).toHaveBeenNthCalledWith(2, first); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps edited allocations after a version conflict and requires a fresh explicit submit', async () => {
|
|
||||||
vi.mocked(repartitionAppointments).mockRejectedValueOnce(new ApiResponseError('版本变化', 'A0409', 409))
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.get('[aria-label="来源1分出箱数"]').setValue(20); await wrapper.findAll('textarea')[0]!.setValue('保留分批原因')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(getAppointmentBatch).toHaveBeenCalledTimes(2); expect(repartitionAppointments).toHaveBeenCalledTimes(1)
|
|
||||||
expect((wrapper.get('[aria-label="来源1分出箱数"]').element as HTMLInputElement).value).toBe('20')
|
|
||||||
expect((wrapper.findAll('textarea')[0]!.element as HTMLTextAreaElement).value).toBe('保留分批原因'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('shows full appointment cargo when confirmed or replaced batches have no repartition sources', async () => {
|
|
||||||
const context = batchContext(); context.sources = []; context.allowedActions = []; context.blockReasons = ['原批次已有正式确认']; context.appointment.appointmentStatus = 'SUCCESS'
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.get('[aria-label="原批次货物快照"]').text()).toContain('IN-A')
|
|
||||||
expect(wrapper.text()).toContain('FBA-B'); expect(wrapper.text()).toContain('当前批次无分批资格')
|
|
||||||
await wrapper.get('form').trigger('submit'); expect(repartitionAppointments).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('loads a candidate context before merging and preserves both original versions', async () => {
|
|
||||||
const other = batchContext('AP-002', 'FBA_APPOINTMENT:2'); other.appointment.version = 6
|
|
||||||
vi.mocked(getAppointmentBatch).mockImplementation(async key => key === 'FBA_APPOINTMENT:2' ? other : batchContext())
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '同仓合并安排')!.trigger('click'); await flushPromises()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '核对并选择')!.trigger('click'); await flushPromises()
|
|
||||||
await wrapper.findAll('textarea')[0]!.setValue('同仓合并'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(repartitionAppointments).toHaveBeenCalledWith(expect.objectContaining({ originals: [{ appointmentNo: 'AP-001', version: 3 }, { appointmentNo: 'AP-002', version: 6 }], batches: [expect.objectContaining({ allocations: [expect.objectContaining({ customerId: 'customer-a', packageCount: 140 }), expect.objectContaining({ customerId: 'customer-b', packageCount: 60 })] })] }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('shows every terminal branch with only the original customer/source/destination quantities and opens the real batch', async () => {
|
|
||||||
const context = batchContext()
|
|
||||||
const source = context.appointment.items[0]!
|
|
||||||
context.appointment.items = [source]
|
|
||||||
context.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:2', 'FBA_APPOINTMENT:3']
|
|
||||||
context.appointment.replacementAppointmentNos = ['AP-INTERMEDIATE', 'AP-20']
|
|
||||||
context.sources = []; context.allowedActions = []
|
|
||||||
const forty = batchContext('AP-40', 'FBA_APPOINTMENT:4').appointment
|
|
||||||
forty.appointmentStatus = 'SUCCESS'
|
|
||||||
forty.items = [
|
|
||||||
{ ...source, packageCount: 40 },
|
|
||||||
{ ...source, id: 'foreign-customer', customerId: 'other-customer', inboundCode: 'FOREIGN-CUSTOMER', packageCount: 900 },
|
|
||||||
{ ...source, id: 'foreign-source', sourceKey: 'ORDER:OTHER', inboundCode: 'FOREIGN-SOURCE', packageCount: 800 },
|
|
||||||
{ ...source, id: 'foreign-destination', destinationKey: 'FBA:OTHER', inboundCode: 'FOREIGN-DESTINATION', packageCount: 700 },
|
|
||||||
]
|
|
||||||
const twenty = batchContext('AP-20', 'FBA_APPOINTMENT:3').appointment
|
|
||||||
twenty.appointmentStatus = 'CANCELLED'; twenty.items = [{ ...source, packageCount: 20 }]
|
|
||||||
context.currentBatches = [forty, twenty]
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const destinations = wrapper.get('[aria-label="当前货物去向"]')
|
|
||||||
expect(destinations.findAll('article')).toHaveLength(2)
|
|
||||||
expect(destinations.text()).toContain('40 箱'); expect(destinations.text()).toContain('20 箱')
|
|
||||||
expect(destinations.text()).toContain('已取消,分配保留')
|
|
||||||
expect(destinations.text()).not.toContain('FOREIGN-'); expect(destinations.text()).not.toContain('AP-INTERMEDIATE')
|
|
||||||
expect(destinations.text()).not.toContain('FBA_APPOINTMENT:')
|
|
||||||
await destinations.findAll('button').find(button => button.text() === '查看本批预约')!.trigger('click')
|
|
||||||
expect(wrapper.emitted('appointment')).toEqual([['AP-40']])
|
|
||||||
await destinations.findAll('button').find(button => button.text() === '查看完整批次')!.trigger('click'); await flushPromises()
|
|
||||||
expect(getAppointmentBatch).toHaveBeenLastCalledWith('FBA_APPOINTMENT:4')
|
|
||||||
expect(repartitionAppointments).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not create zero-quantity destinations or convert unknown quantities to zero', async () => {
|
|
||||||
const context = batchContext()
|
|
||||||
context.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:2']
|
|
||||||
context.sources = []; context.allowedActions = []
|
|
||||||
const unknown = batchContext('AP-UNKNOWN', 'FBA_APPOINTMENT:2').appointment
|
|
||||||
unknown.items = [{ ...context.appointment.items[0]!, packageCount: null }]
|
|
||||||
const empty = batchContext('AP-EMPTY', 'FBA_APPOINTMENT:3').appointment
|
|
||||||
empty.items = [{ ...context.appointment.items[0]!, packageCount: 0 }]
|
|
||||||
context.currentBatches = [unknown, empty]
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const destinations = wrapper.get('[aria-label="当前货物去向"]')
|
|
||||||
expect(destinations.findAll('article')).toHaveLength(1)
|
|
||||||
expect(destinations.text()).toContain('箱数待核实'); expect(destinations.text()).not.toContain('0 箱')
|
|
||||||
expect(destinations.text()).not.toContain('AP-EMPTY'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not fall back to historical replacement links when current destinations are empty', async () => {
|
|
||||||
const context = batchContext()
|
|
||||||
context.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:2']
|
|
||||||
context.appointment.replacementAppointmentNos = ['AP-OLD-REPLACEMENT']
|
|
||||||
context.sources = []; context.allowedActions = []; context.currentBatches = []
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const destinations = wrapper.get('[aria-label="当前货物去向"]')
|
|
||||||
expect(destinations.findAll('article')).toHaveLength(0)
|
|
||||||
expect(destinations.text()).toContain('原快照不代表当前待办')
|
|
||||||
expect(destinations.text()).not.toContain('AP-OLD-REPLACEMENT'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps every 40/20 destination after the entire customer has left the original current items', async () => {
|
|
||||||
const context = batchContext(), originalItem = context.appointment.items[0]!
|
|
||||||
context.appointment.items = [context.appointment.items[1]!]
|
|
||||||
context.sources = [context.sources[1]!]
|
|
||||||
const forty = batchContext('AP-40', 'FBA_APPOINTMENT:40').appointment
|
|
||||||
forty.items = [{ ...originalItem, packageCount: 40 }, { ...originalItem, id: 'unrelated', sourceKey: 'ORDER:OTHER', inboundCode: 'IN-UNRELATED', packageCount: 999 }]
|
|
||||||
const twenty = batchContext('AP-20', 'FBA_APPOINTMENT:20').appointment
|
|
||||||
twenty.items = [{ ...originalItem, packageCount: 20 }]
|
|
||||||
context.currentBatches = [context.appointment, forty, twenty]
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const destinations = wrapper.get('[aria-label="当前货物去向"]')
|
|
||||||
expect(destinations.text()).toContain('40 箱'); expect(destinations.text()).toContain('20 箱')
|
|
||||||
expect(destinations.text()).not.toContain('IN-UNRELATED')
|
|
||||||
expect(wrapper.findAll('[aria-label="来源1分出箱数"]')).toHaveLength(1)
|
|
||||||
expect((wrapper.get('[aria-label="来源1分出箱数"]').attributes('max'))).toBe('30')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('retries a new destination without exposing the prior batch or retaining its allocation inputs', async () => {
|
|
||||||
const original = batchContext()
|
|
||||||
original.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:2']; original.sources = []; original.allowedActions = []
|
|
||||||
const current = batchContext('AP-CURRENT', 'FBA_APPOINTMENT:2')
|
|
||||||
current.appointment.plannedDate = '2026-10-22'
|
|
||||||
original.currentBatches = [current.appointment]
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValueOnce(original).mockRejectedValueOnce(new Error('新批次暂不可用')).mockResolvedValue(current)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '查看完整批次')!.trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.text()).not.toContain('AP-001'); expect(wrapper.find('form').exists()).toBe(false)
|
|
||||||
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('AP-CURRENT')
|
|
||||||
expect((wrapper.findAll('input[data-picker-kind="date"]')[0]!.element as HTMLInputElement).value).toBe('2026-10-22')
|
|
||||||
expect((wrapper.get('[aria-label="来源1分出箱数"]').element as HTMLInputElement).value).toBe('0')
|
|
||||||
expect(getAppointmentBatch).toHaveBeenLastCalledWith('FBA_APPOINTMENT:2')
|
|
||||||
expect(repartitionAppointments).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import './appointmentNativeForms.css'
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import { computed, onMounted, reactive, ref } from 'vue'
|
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { getAppointmentBatch, repartitionAppointments, allocation, allocationKey, mergeBatchSources, splitBatch, type FbaAppointmentBatchContext, type RepartitionFbaAppointmentsRequest, type RepartitionFbaAppointmentsResponse } from './batchApi'
|
|
||||||
import { getWorkItems, type WorkPage } from './workApi'
|
|
||||||
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
|
|
||||||
import CargoVerificationForm from './CargoVerificationForm.vue'
|
|
||||||
import type { CargoVerificationSource } from './cargoVerificationApi'
|
|
||||||
const props = defineProps<{ batchKey: string }>()
|
|
||||||
const emit = defineEmits<{ updated: []; appointment: [appointmentNo: string] }>()
|
|
||||||
const access = useAccessPreviewStore(), activeKey = ref(props.batchKey), context = ref<FbaAppointmentBatchContext | null>(null), other = ref<FbaAppointmentBatchContext | null>(null)
|
|
||||||
const mode = ref<'split' | 'merge'>('split'), loading = ref(false), saving = ref(false), ready = ref(false)
|
|
||||||
const error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null), pending = ref<RepartitionFbaAppointmentsRequest | null>(null), result = ref<RepartitionFbaAppointmentsResponse | null>(null)
|
|
||||||
const form = reactive({ firstDate: '', nextDate: '', reason: '', remark: '', moved: {} as Record<string, number | string> })
|
|
||||||
const baseline = ref(JSON.stringify(form)), verification = ref<CargoVerificationSource | null>(null)
|
|
||||||
const canLeave = useWorkDraft(computed(() => baseline.value !== JSON.stringify(form)), computed(() => saving.value || !!pending.value))
|
|
||||||
const candidates = ref<WorkPage | null>(null), candidatePage = ref(1), keyword = ref(''), candidateLoading = ref(false), candidateError = ref<ApiErrorDetails | null>(null)
|
|
||||||
let candidateRequest = 0
|
|
||||||
let initializedKey: string | null = null
|
|
||||||
const canWrite = computed(() => access.can('platform:overseas-warehouse:inbound-order:fba-appointment'))
|
|
||||||
const replaced = computed(() => !!context.value?.appointment.replacementBatchKeys?.length || !!context.value?.appointment.replacementAppointmentNos?.length)
|
|
||||||
const hasCurrentDestinations = computed(() => replaced.value || context.value?.currentBatches.some(batch => batch.batchKey !== context.value?.appointment.batchKey))
|
|
||||||
const currentDestinations = computed(() => {
|
|
||||||
if (!context.value) return []
|
|
||||||
const sourceIdentity = (item: FbaAppointmentBatchContext['appointment']['items'][number]) => JSON.stringify([item.customerId, item.sourceKey, item.destinationKey])
|
|
||||||
const originalSources = new Set(context.value.originalSourceRefs.map(allocationKey))
|
|
||||||
return context.value.currentBatches.map(appointment => ({ appointment, items: appointment.items.filter(item => item.destinationKey && originalSources.has(sourceIdentity(item)) && (item.packageCount == null || item.packageCount > 0)) })).filter(row => row.items.length)
|
|
||||||
})
|
|
||||||
function bookingStatus(status: string) { return ({ PENDING: '待预约', SUCCESS: '已确认预约', FAILED: '未约成', CANCELLED: '已取消,分配保留' } as Record<string, string>)[status] || '预约状态待核实' }
|
|
||||||
async function openAppointment(number: string) { if (await canLeave()) emit('appointment', number) }
|
|
||||||
const canSubmit = computed(() => canWrite.value && ready.value && !loading.value && !error.value && !!context.value?.allowedActions.includes(mode.value === 'split' ? 'SPLIT' : 'MERGE') && (mode.value !== 'merge' || !!other.value?.allowedActions.includes('MERGE')))
|
|
||||||
async function load(preserve = false) {
|
|
||||||
loading.value = true; ready.value = false; error.value = null
|
|
||||||
try {
|
|
||||||
context.value = await getAppointmentBatch(activeKey.value)
|
|
||||||
if (other.value?.appointment.batchKey) other.value = await getAppointmentBatch(other.value.appointment.batchKey)
|
|
||||||
if (!preserve || initializedKey !== activeKey.value) {
|
|
||||||
Object.assign(form, { firstDate: context.value.appointment.plannedDate || '', nextDate: '', reason: '', remark: '', moved: Object.fromEntries(context.value.sources.map(source => [allocationKey(source), 0])) })
|
|
||||||
baseline.value = JSON.stringify(form)
|
|
||||||
initializedKey = activeKey.value
|
|
||||||
}
|
|
||||||
ready.value = true
|
|
||||||
} catch (cause) { error.value = getApiErrorDetails(cause, '批次资料读取失败') }
|
|
||||||
finally { loading.value = false }
|
|
||||||
}
|
|
||||||
async function searchCandidates(page = 1) {
|
|
||||||
const request = ++candidateRequest; candidatePage.value = page; candidates.value = null; candidateError.value = null; candidateLoading.value = true
|
|
||||||
try { const rows = await getWorkItems({ view: 'ALL', types: ['DELIVERY'], keyword: keyword.value.trim() || undefined, page, size: 8 }); if (request === candidateRequest) candidates.value = rows }
|
|
||||||
catch (cause) { if (request === candidateRequest) candidateError.value = getApiErrorDetails(cause, '可合并工作事项读取失败') }
|
|
||||||
finally { if (request === candidateRequest) candidateLoading.value = false }
|
|
||||||
}
|
|
||||||
async function chooseOther(key: string) {
|
|
||||||
if (!context.value || pending.value || saving.value) return
|
|
||||||
candidateLoading.value = true; candidateError.value = null
|
|
||||||
try {
|
|
||||||
const selected = await getAppointmentBatch(key)
|
|
||||||
if (!selected.allowedActions.includes('MERGE')) throw new Error(selected.blockReasons.join(';') || '该批次当前不允许合并')
|
|
||||||
mergeBatchSources([context.value, selected]); other.value = selected
|
|
||||||
} catch (cause) { candidateError.value = getApiErrorDetails(cause, '批次不能合并') }
|
|
||||||
finally { candidateLoading.value = false }
|
|
||||||
}
|
|
||||||
async function changeMode(next: 'split' | 'merge') {
|
|
||||||
if (!await canLeave()) return
|
|
||||||
mode.value = next; other.value = null; result.value = null; await load()
|
|
||||||
if (next === 'merge') await searchCandidates()
|
|
||||||
}
|
|
||||||
function sourceLabel(source: CargoVerificationSource) {
|
|
||||||
const item = context.value?.appointment.items.find(item => item.customerId === source.customerId && item.sourceKey === source.sourceKey)
|
|
||||||
return item?.inboundCode || '原票业务号未提供'
|
|
||||||
}
|
|
||||||
async function verify(source: CargoVerificationSource) { if (await canLeave()) { baseline.value = JSON.stringify(form); verification.value = source } }
|
|
||||||
async function verified() { verification.value = null; await load(); emit('updated') }
|
|
||||||
async function openBatch(key: string) { if (!await canLeave()) return; activeKey.value = key; context.value = null; result.value = null; other.value = null; mode.value = 'split'; await load() }
|
|
||||||
async function save() {
|
|
||||||
if (!context.value || !canSubmit.value || saving.value) return
|
|
||||||
if (!pending.value) {
|
|
||||||
try {
|
|
||||||
if (!form.reason.trim()) { ElMessage.warning('请填写分批或合并原因'); return }
|
|
||||||
const contexts = mode.value === 'merge' && other.value ? [context.value, other.value] : [context.value]
|
|
||||||
const allocations = mode.value === 'split' ? splitBatch(context.value, form.moved) : [mergeBatchSources(contexts).map(source => allocation(source, Number(source.packageCount)))]
|
|
||||||
pending.value = { originals: contexts.map(row => ({ appointmentNo: row.appointment.appointmentNo, version: row.appointment.version })), batches: allocations.map((rows, index) => ({ plannedDate: (index === 0 ? form.firstDate : form.nextDate) || null, remark: form.remark.trim() || null, allocations: rows })), reason: form.reason.trim(), idempotencyKey: crypto.randomUUID() }
|
|
||||||
} catch (cause) { saveError.value = getApiErrorDetails(cause, '请核对逐票分配数量'); return }
|
|
||||||
}
|
|
||||||
saving.value = true; saveError.value = null
|
|
||||||
try {
|
|
||||||
result.value = await repartitionAppointments(pending.value); pending.value = null; baseline.value = JSON.stringify(form)
|
|
||||||
ElMessage.success(mode.value === 'split' ? '已分为两个待安排批次' : '已合并为一个待安排批次'); emit('updated')
|
|
||||||
} catch (cause) { saveError.value = getApiErrorDetails(cause, '调整结果待确认,请重试本次提交'); if (rejectedCommand(cause)) { pending.value = null; await load(true) } }
|
|
||||||
finally { saving.value = false }
|
|
||||||
}
|
|
||||||
onMounted(() => load())
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section class="work-form" aria-label="预约分批合并">
|
|
||||||
<CargoVerificationForm v-if="verification" :key="`${verification.customerId}:${verification.sourceKey}`" :source="verification" @saved="verified" />
|
|
||||||
<template v-else>
|
|
||||||
<h3>{{ context?.appointment.appointmentNo || '预约批次' }} · 分批与合并</h3>
|
|
||||||
<LoadErrorState v-if="error" title="批次资料读取失败" :message="error.message" :loading="loading" @retry="load(true)"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<p v-if="loading">正在核对批次、来源和核实版本…</p>
|
|
||||||
<template v-if="result"><p>原批次 {{ result.replacedAppointmentNos.join('、') }} 已保留历史并被替代。</p><div v-for="appointment in result.appointments" :key="appointment.appointmentNo" class="batch-result"><strong>{{ appointment.appointmentNo }}</strong><span>{{ appointment.plannedDate || '日期未定' }} · 待安排</span><el-button @click="emit('appointment', appointment.appointmentNo)">登记安排</el-button><el-button v-if="appointment.batchKey" @click="openBatch(appointment.batchKey)">继续分批</el-button></div></template>
|
|
||||||
<template v-else-if="context">
|
|
||||||
<p>{{ context.appointment.fbaWarehouseCode }} · {{ context.appointment.items.length }} 条货物来源;客户与原来源逐票保留。</p>
|
|
||||||
<template v-if="hasCurrentDestinations">
|
|
||||||
<p v-if="replaced">该批次已被替代,原货物快照仅供追溯。{{ context.appointment.repartitionReason }}</p>
|
|
||||||
<p v-else>本批仍有保留货物,以下同时列出服务端返回的当前后送去向。</p>
|
|
||||||
<section aria-label="当前货物去向">
|
|
||||||
<h4>当前货物去向</h4><p>以下仅展示原批次客户、来源及目的仓对应的当前分配;合并批次可能还含其他货物,进入完整批次后可查看。</p>
|
|
||||||
<article v-for="destination in currentDestinations" :key="destination.appointment.batchKey" class="allocation-row">
|
|
||||||
<strong>{{ destination.appointment.appointmentNo }}</strong><p>{{ bookingStatus(destination.appointment.appointmentStatus) }} · {{ destination.appointment.plannedDate || '日期未定' }}</p>
|
|
||||||
<div v-for="item in destination.items" :key="item.id"><p>{{ item.inboundCode || '原票业务号未提供' }} · {{ item.fbaWarehouseCode }} · {{ item.packageCount == null ? '箱数待核实' : `${item.packageCount} 箱` }}</p><p>货件:{{ item.shipmentReferences?.join('、') || '待核实' }}</p></div>
|
|
||||||
<el-button :disabled="loading || !!error || saving || !!pending" @click="openAppointment(destination.appointment.appointmentNo)">查看本批预约</el-button>
|
|
||||||
<el-button v-if="destination.appointment.batchKey" :disabled="loading || !!error || saving || !!pending" @click="openBatch(destination.appointment.batchKey)">查看完整批次</el-button>
|
|
||||||
</article>
|
|
||||||
<p v-if="!currentDestinations.length && !loading && !error">当前没有与原货物范围匹配的分配;原快照不代表当前待办。</p>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
<p v-for="reason in context.blockReasons" :key="reason" role="status">{{ reason }}</p>
|
|
||||||
<div v-if="!context.sources.length" aria-label="原批次货物快照"><p>当前批次无分批资格,以下为原预约保留的货物资料。</p><div v-for="(item, index) in context.appointment.items" :key="item.id" class="allocation-row"><b>来源 {{ index + 1 }} · {{ item.inboundCode || '原票业务号未提供' }}</b><p>{{ item.fbaWarehouseCode }} · {{ item.packageCount ?? '箱数待核实' }}<span v-if="item.packageCount != null"> 箱</span></p><p>货件:{{ item.shipmentReferences?.join('、') || '待核实' }}</p></div></div>
|
|
||||||
<div class="batch-modes"><el-button :disabled="saving || !!pending || !context.allowedActions.includes('SPLIT')" @click="changeMode('split')">分成两次送仓</el-button><el-button :disabled="saving || !!pending || !context.allowedActions.includes('MERGE')" @click="changeMode('merge')">同仓合并安排</el-button></div>
|
|
||||||
<form class="density-form appointment-native-form" @submit.prevent="save"><fieldset :disabled="saving || !!pending || loading || !canWrite">
|
|
||||||
<div v-for="(source, index) in context.sources" :key="allocationKey(source)" class="allocation-row"><b>来源 {{ index + 1 }} · {{ sourceLabel(source) }}</b><p>本批 {{ source.packageCount ?? '待核实' }} 箱 · 原箱数 {{ source.originalPackages ?? '未知' }}</p><p>货件:{{ source.shipmentReferences.join('、') || '待核实' }}</p><label v-if="mode === 'split'">分到第二批的箱数<input v-model="form.moved[allocationKey(source)]" type="number" min="0" :max="source.packageCount ?? undefined" step="1" :aria-label="`来源${index + 1}分出箱数`" class="workbench-input"></label><el-button v-if="context.allowedActions.includes('VERIFY_CARGO')" @click="verify(source)">核实本票资料</el-button></div>
|
|
||||||
<template v-if="mode === 'merge'"><label>查找另一批工作事项<input v-model="keyword" placeholder="预约号、批次号、柜号" maxlength="80" @keydown.enter.prevent="searchCandidates()" class="workbench-input"></label><el-button :loading="candidateLoading" @click="searchCandidates()">查询批次</el-button><LoadErrorState v-if="candidateError" title="合并候选不可用" :message="candidateError.message" @retry="searchCandidates(candidatePage)" /><div v-for="candidate in candidates?.records.filter(item => item.batchKey && item.batchKey !== activeKey)" :key="candidate.workItemKey" class="batch-candidate"><span>{{ candidate.title }} · {{ candidate.destinationName || '目的仓待核实' }}</span><el-button :disabled="candidateLoading" @click="chooseOther(candidate.batchKey!)">核对并选择</el-button></div><p v-if="candidates && !candidates.records.length">本页未查询到工作事项。</p><div v-if="candidates && candidates.total > 8" class="batch-modes"><el-button :disabled="candidatePage === 1 || candidateLoading" @click="searchCandidates(candidatePage - 1)">上一页</el-button><span>第 {{ candidatePage }} 页</span><el-button :disabled="candidatePage * 8 >= candidates.total || candidateLoading" @click="searchCandidates(candidatePage + 1)">下一页</el-button></div><p v-if="other">已核对:{{ other.appointment.appointmentNo }},{{ other.sources.length }} 条来源;提交时再次逐来源校验。</p></template>
|
|
||||||
<label>{{ mode === 'split' ? '第一批目标日期(可不填)' : '合并后目标日期(可不填)' }}<el-date-picker v-model="form.firstDate" type="date" :disabled="saving || !!pending || loading || !canWrite" format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable /></label><label v-if="mode === 'split'">第二批目标日期(可不填)<el-date-picker v-model="form.nextDate" type="date" :disabled="saving || !!pending || loading || !canWrite" format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable /></label><label>调整原因<textarea v-model="form.reason" required maxlength="1000" class="workbench-input" /></label><label>批次备注<textarea v-model="form.remark" maxlength="1000" class="workbench-input" /></label>
|
|
||||||
</fieldset><LoadErrorState v-if="saveError" title="批次调整未完成" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState><div class="density-actions density-actions--footer appointment-form-actions"><el-button type="primary" native-type="submit" :loading="saving" :disabled="!canSubmit || !!result">{{ pending ? '重试本次调整' : mode === 'split' ? '拆分为两批预约安排' : '合并为一批继续预约' }}</el-button></div></form>
|
|
||||||
</template>
|
|
||||||
</template>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
<style scoped>.allocation-row, .batch-result, .batch-candidate { padding: var(--admin-space-3) 0; border-bottom: 1px solid var(--workbench-border); overflow-wrap: anywhere; }.batch-modes, .batch-result, .batch-candidate { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-3); }.batch-candidate > span { flex: 1; }</style>
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
import ElementPlus from 'element-plus'
|
|
||||||
import { DOMWrapper, enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import AppDialog from '@/shared/components/AppDialog.vue'
|
|
||||||
import LineClampText from '@/shared/components/LineClampText.vue'
|
|
||||||
import AppointmentCalendarView from './AppointmentCalendarView.vue'
|
|
||||||
import { getCalendarSources, getWarehouseArrivals, saveWarehouseArrival, type WarehouseArrival } from './scheduleApi'
|
|
||||||
import { listTripCalendar } from './tripCalendar'
|
|
||||||
import { createSourceAppointment, listPlanningCargo, previewPlanningBatch, resolvePlanningSource, type PlanningCargo, type PlanningBatchPreview } from './planningApi'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
import type { ScheduleEvent } from './schedule'
|
|
||||||
import { getWorkDetail, type WorkAction } from './workApi'
|
|
||||||
import { workDetail, workItem } from './work.test-support'
|
|
||||||
|
|
||||||
const routing = vi.hoisted(() => ({ query: { date: '2026-10-19' } as Record<string, string>, push: vi.fn(), replace: vi.fn(), denied: new Set<string>() }))
|
|
||||||
vi.mock('vue-router', () => ({ useRoute: () => routing, useRouter: () => routing, onBeforeRouteLeave: vi.fn(), onBeforeRouteUpdate: vi.fn() }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: (permission: string) => !routing.denied.has(permission) }) }))
|
|
||||||
vi.mock('./scheduleApi', () => ({ getCalendarSources: vi.fn(), getWarehouseArrivals: vi.fn(), saveWarehouseArrival: vi.fn() }))
|
|
||||||
vi.mock('./tripCalendar', async original => ({ ...await original<typeof import('./tripCalendar')>(), listTripCalendar: vi.fn() }))
|
|
||||||
vi.mock('./planningApi', async original => ({ ...await original<typeof import('./planningApi')>(), listPlanningCargo: vi.fn(), previewPlanningBatch: vi.fn(), resolvePlanningSource: vi.fn(), createSourceAppointment: vi.fn() }))
|
|
||||||
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), getWorkDetail: vi.fn() }))
|
|
||||||
enableAutoUnmount(afterEach)
|
|
||||||
afterEach(() => { vi.unstubAllGlobals() })
|
|
||||||
const warehouse: WarehouseArrival = { sourceContainerBookingId: '9007199254740999', containerNo: 'TEST-CONT', warehouseName: '美国仓', warehouseCode: 'US-W', plannedAt: null, actualAt: null, version: 3, planCount: 0, canEdit: true }
|
|
||||||
const event: ScheduleEvent = { key: 'warehouse-1', type: 'warehouse', date: '2026-10-21', time: '', title: 'TEST-CONT 计划到仓', fields: [], warehouse, canEdit: true }
|
|
||||||
const cargo: PlanningCargo = { sourceKey: 'ORDER:9007199254740998', orderId: '9007199254740998', customerId: '9007199254740997', customerName: '预约长客户名称'.repeat(12), inboundCode: 'IN-TEST', containerBookingId: 'container-1', containerNo: 'TEST-CONT', originWarehouseId: 'origin-1', originWarehouseCode: 'US-W', originWarehouseName: '美国长仓库名称'.repeat(12), destinationWarehouseCode: 'ONT8', packages: 20, receivedPackages: 0, shippedPackages: 0, sourcePalletCount: null, volumeCbm: null, estimatedArrivalAt: null, estimatedWarehouseAt: null, orderVersion: 1, standardNode: 'DEPARTED', shippingVersion: null, shippingObservedAt: null, shippingProvider: null, hasInboundPlan: false, hasActiveAppointment: false, detained: false, mixedDestinations: false }
|
|
||||||
const source = { sourceKey: cargo.sourceKey, customerId: cargo.customerId, orderId: cargo.orderId, inboundCode: cargo.inboundCode, bookingNo: null, containerNo: cargo.containerNo, originWarehouseId: cargo.originWarehouseId, originWarehouseName: cargo.originWarehouseName, destinationKey: 'FBA:LAX9', destinationWarehouseCode: 'LAX9', packages: 20, sourceVersion: 'v1', canFollowup: true, blockReasons: [] }
|
|
||||||
const preview: PlanningBatchPreview = { group: { originWarehouseId: cargo.originWarehouseId, destinationKey: source.destinationKey, packages: 20, sourceCount: 1, customerCount: 1, readinessIncomplete: true, readyFrom: null, readyTo: null, unknownQuantitySources: 0 }, originWarehouseName: cargo.originWarehouseName, destinationWarehouseCode: 'LAX9', destinationTimezone: 'America/Los_Angeles', sources: [source], missingFields: [] }
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks(); routing.denied.clear(); routing.query = { date: '2026-10-19' }
|
|
||||||
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} })
|
|
||||||
vi.mocked(getCalendarSources).mockResolvedValue({ containers: [], emptyReturns: [], emptyReturnsReadable: true })
|
|
||||||
vi.mocked(getWarehouseArrivals).mockResolvedValue([])
|
|
||||||
vi.mocked(listTripCalendar).mockResolvedValue({ records: [], unresolvedRecords: [] })
|
|
||||||
vi.mocked(saveWarehouseArrival).mockResolvedValue({})
|
|
||||||
vi.mocked(listPlanningCargo).mockResolvedValue({ records: [cargo], total: 1, page: 1, size: 20, pages: 1 })
|
|
||||||
vi.mocked(resolvePlanningSource).mockResolvedValue({ source, coverage: { status: 'NONE', missingFields: [], changeReviewRequired: false, appointments: [] } })
|
|
||||||
vi.mocked(previewPlanningBatch).mockResolvedValue(preview)
|
|
||||||
vi.mocked(createSourceAppointment).mockResolvedValue(batchContext().appointment)
|
|
||||||
vi.mocked(getWorkDetail).mockResolvedValue(workDetail())
|
|
||||||
})
|
|
||||||
async function open() {
|
|
||||||
const wrapper = mount(AppointmentCalendarView, { global: { plugins: [ElementPlus], stubs: {
|
|
||||||
AppointmentCalendarPanel: { name: 'AppointmentCalendarPanel', template: '<section data-calendar />' },
|
|
||||||
} } })
|
|
||||||
await flushPromises()
|
|
||||||
return wrapper
|
|
||||||
}
|
|
||||||
async function create(wrapper: Awaited<ReturnType<typeof open>>) {
|
|
||||||
wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('create'); await vi.dynamicImportSettled(); await flushPromises()
|
|
||||||
const dialog = wrapper.findAllComponents(AppDialog).find(item => item.props('title') === '新增FBA送仓预约')!
|
|
||||||
const content = creationBody()
|
|
||||||
await content.get('input[type="checkbox"]').setValue(true)
|
|
||||||
await content.findAll('button').find(button => button.text().startsWith('下一步'))!.trigger('click'); await flushPromises()
|
|
||||||
return dialog
|
|
||||||
}
|
|
||||||
function creationBody() { return new DOMWrapper(Array.from(document.querySelectorAll<HTMLElement>('.el-dialog')).find(item => item.textContent?.includes('新增FBA送仓预约'))!) }
|
|
||||||
it('keeps the arrival context and typed local time across native fullscreen and submits the original version', async () => {
|
|
||||||
const wrapper = await open()
|
|
||||||
wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('edit', event); await flushPromises()
|
|
||||||
const dialog = wrapper.findAllComponents(AppDialog).find(item => item.props('title') === '调整计划到仓')!
|
|
||||||
expect(dialog.props('width')).toBe('520px')
|
|
||||||
expect(dialog.get('[aria-label="到仓业务信息"]').text()).toContain('TEST-CONT 计划到仓')
|
|
||||||
expect(dialog.text()).not.toContain(warehouse.sourceContainerBookingId)
|
|
||||||
const picker = dialog.getComponent({ name: 'ElDatePicker' })
|
|
||||||
expect(picker.props()).toMatchObject({ type: 'datetime', valueFormat: 'YYYY-MM-DDTHH:mm', format: 'YYYY-MM-DD HH:mm' })
|
|
||||||
expect(dialog.getComponent({ name: 'ElForm' }).props('labelWidth')).toBe('150px')
|
|
||||||
picker.vm.$emit('update:modelValue', '2026-10-22T09:30'); await flushPromises()
|
|
||||||
await dialog.get('button[aria-label="展开全屏"]').trigger('click'); await flushPromises()
|
|
||||||
expect(dialog.findComponent({ name: 'ElDialog' }).props('fullscreen')).toBe(true)
|
|
||||||
expect(picker.props('modelValue')).toBe('2026-10-22T09:30')
|
|
||||||
await dialog.get('.el-dialog__footer .el-button--primary').trigger('click'); await flushPromises()
|
|
||||||
expect(saveWarehouseArrival).toHaveBeenCalledExactlyOnceWith(warehouse.sourceContainerBookingId, { estimatedWarehouseArrivalAt: '2026-10-22T09:30:00', expectedVersion: 3 }, expect.any(String))
|
|
||||||
})
|
|
||||||
it('locks the real arrival input after an unknown outcome and reuses its immutable request', async () => {
|
|
||||||
vi.mocked(saveWarehouseArrival).mockRejectedValueOnce(new Error('connection lost'))
|
|
||||||
const wrapper = await open(); wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('edit', event); await flushPromises()
|
|
||||||
const dialog = wrapper.findAllComponents(AppDialog).find(item => item.props('title') === '调整计划到仓')!
|
|
||||||
dialog.getComponent({ name: 'ElDatePicker' }).vm.$emit('update:modelValue', '2026-10-22T09:30'); await flushPromises()
|
|
||||||
await dialog.get('.el-dialog__footer .el-button--primary').trigger('click'); await flushPromises()
|
|
||||||
expect(dialog.get('input').attributes('disabled')).toBeDefined()
|
|
||||||
expect(dialog.text()).toContain('上次提交结果尚未确认')
|
|
||||||
expect(dialog.get('.el-dialog__footer .el-button--primary').text()).toBe('重试确认保存结果')
|
|
||||||
await dialog.get('.el-dialog__footer .el-button--primary').trigger('click'); await flushPromises()
|
|
||||||
expect(vi.mocked(saveWarehouseArrival).mock.calls[1]).toEqual(vi.mocked(saveWarehouseArrival).mock.calls[0])
|
|
||||||
})
|
|
||||||
it('clears the Element arrival picker without saving an empty required time', async () => {
|
|
||||||
const wrapper = await open(); wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('edit', event); await flushPromises()
|
|
||||||
const dialog = wrapper.findAllComponents(AppDialog).find(item => item.props('title') === '调整计划到仓')!
|
|
||||||
const picker = dialog.getComponent({ name: 'ElDatePicker' })
|
|
||||||
expect(dialog.find('input[type="datetime-local"]').exists()).toBe(false)
|
|
||||||
picker.vm.$emit('update:modelValue', '2026-10-22T09:30'); await flushPromises()
|
|
||||||
expect(dialog.props('confirmDisabled')).toBe(false)
|
|
||||||
picker.vm.$emit('update:modelValue', null); await flushPromises()
|
|
||||||
expect(dialog.props('confirmDisabled')).toBe(true)
|
|
||||||
expect(saveWarehouseArrival).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
it('keeps complete long cargo names accessible in the selectable table', async () => {
|
|
||||||
const wrapper = await open()
|
|
||||||
wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('create'); await vi.dynamicImportSettled(); await flushPromises()
|
|
||||||
const names = wrapper.findAllComponents(LineClampText).map(item => item.props('content'))
|
|
||||||
expect(names).toContain(cargo.customerName); expect(names).toContain(cargo.originWarehouseName)
|
|
||||||
expect(wrapper.getComponent({ name: 'DataTable' }).props('maxHeight')).toBe('')
|
|
||||||
expect(wrapper.text()).not.toMatch(/900719925474099[7-9]/)
|
|
||||||
expect(resolvePlanningSource).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
it('preserves real FBA fields and entered values when expanding the create dialog', async () => {
|
|
||||||
const wrapper = await open(); const dialog = await create(wrapper)
|
|
||||||
const fields = dialog.getComponent({ name: 'FbaAppointmentFields' })
|
|
||||||
expect(fields.props('continuous')).toBe(true)
|
|
||||||
const date = fields.findAllComponents({ name: 'ElDatePicker' })[0]!
|
|
||||||
date.vm.$emit('update:modelValue', '2026-10-25'); await flushPromises()
|
|
||||||
await creationBody().get('button[aria-label="展开全屏"]').trigger('click'); await flushPromises()
|
|
||||||
expect(dialog.findComponent({ name: 'ElDialog' }).props('fullscreen')).toBe(true)
|
|
||||||
expect(date.props('modelValue')).toBe('2026-10-25')
|
|
||||||
await creationBody().findAll('button').find(button => button.text() === '保存预约安排')!.trigger('click'); await flushPromises()
|
|
||||||
expect(createSourceAppointment).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ sources: [{ sourceKey: source.sourceKey, customerId: source.customerId, destinationKey: 'FBA:LAX9' }], details: expect.objectContaining({ plannedDate: '2026-10-25', plannedAt: null, appointmentStatus: 'PENDING' }), idempotencyKey: expect.any(String) }))
|
|
||||||
expect(creationBody().get('[aria-label="预约保存回执"]').findAll('input, textarea, select')).toHaveLength(0)
|
|
||||||
expect(creationBody().text()).toContain('AP-001')
|
|
||||||
})
|
|
||||||
it('shows every saved server field as readonly text including confirmed offsets and long remarks', async () => {
|
|
||||||
const saved = { ...batchContext().appointment, plannedDate: '2026-10-26', plannedAt: '2026-10-26T08:00:00', plannedEndAt: '2026-10-26T18:00:00', timezone: 'America/Los_Angeles', appointmentStatus: 'SUCCESS', confirmationNo: 'CONFIRM-001', appointmentAt: '2026-11-01T01:30:00', appointmentEndAt: '2026-11-01T01:45:00', appointmentStartUtc: '2026-11-01T08:30:00Z', appointmentEndUtc: '2026-11-01T09:45:00Z', appointmentRemark: '完整预约备注'.repeat(30) }
|
|
||||||
vi.mocked(createSourceAppointment).mockResolvedValue(saved)
|
|
||||||
const wrapper = await open(); await create(wrapper)
|
|
||||||
await creationBody().findAll('button').find(button => button.text() === '保存预约安排')!.trigger('click'); await flushPromises()
|
|
||||||
const receipt = creationBody().get('[aria-label="预约保存回执"]')
|
|
||||||
for (const text of ['AP-001', saved.plannedDate, saved.plannedAt, saved.plannedEndAt, saved.timezone, '已取得对方正式确认', saved.confirmationNo, saved.appointmentAt, saved.appointmentEndAt, '-07:00', '-08:00', saved.appointmentRemark]) expect(receipt.text()).toContain(text)
|
|
||||||
expect(receipt.findAll('input, textarea, select')).toHaveLength(0)
|
|
||||||
expect(receipt.text()).not.toMatch(/item-1|customer-a|FBA_APPOINTMENT:1/)
|
|
||||||
})
|
|
||||||
it('does not open or request creation data without its original write permission', async () => {
|
|
||||||
routing.denied.add('platform:overseas-warehouse:inbound-order:fba-appointment')
|
|
||||||
const wrapper = await open(); wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('create'); await flushPromises()
|
|
||||||
expect(listPlanningCargo).not.toHaveBeenCalled(); expect(createSourceAppointment).not.toHaveBeenCalled()
|
|
||||||
expect(wrapper.findAllComponents(AppDialog).some(dialog => dialog.props('title') === '新增FBA送仓预约')).toBe(false)
|
|
||||||
})
|
|
||||||
it('uses the same real continuous form through the original work detail deep link', async () => {
|
|
||||||
routing.query.workItem = 'work-delivery-1'
|
|
||||||
const action: WorkAction = { code: 'SAVE_PLAN', label: '安排预约', targetWorkItemKey: null, target: { kind: 'FBA_APPOINTMENT', appointmentId: null, batchKey: null, sources: [{ sourceKey: source.sourceKey, customerId: source.customerId, destinationKey: source.destinationKey }] } }
|
|
||||||
vi.mocked(getWorkDetail).mockResolvedValue(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }))
|
|
||||||
const wrapper = await open(); await vi.dynamicImportSettled(); await flushPromises()
|
|
||||||
const content = new DOMWrapper(Array.from(document.querySelectorAll<HTMLElement>('.el-dialog')).find(item => item.textContent?.includes('原业务预约办理'))!)
|
|
||||||
await content.get('.primary-next-action').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('continuous')).toBe(true)
|
|
||||||
expect(previewPlanningBatch).toHaveBeenCalledExactlyOnceWith(action.target.kind === 'FBA_APPOINTMENT' ? action.target.sources : [])
|
|
||||||
await content.findAll('button').find(button => button.text() === '保存预约安排')!.trigger('click'); await flushPromises()
|
|
||||||
expect(createSourceAppointment).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ sources: [{ sourceKey: source.sourceKey, customerId: source.customerId, destinationKey: source.destinationKey }], details: expect.objectContaining({ plannedAt: null, appointmentStatus: 'PENDING' }) }))
|
|
||||||
expect(content.text()).toContain('本次保存已完成')
|
|
||||||
})
|
|
||||||
@@ -1,114 +1,120 @@
|
|||||||
import { mount } from '@vue/test-utils'
|
import { mount } from '@vue/test-utils'
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import AppointmentCalendarPanel from './AppointmentCalendarPanel.vue'
|
import AppointmentCalendarPanel from './AppointmentCalendarPanel.vue'
|
||||||
import { scheduleTypes, type ScheduleEvent } from './schedule'
|
|
||||||
import { projectTripCalendar, type TripCalendarEntry } from './tripCalendar'
|
|
||||||
|
|
||||||
const event = (type: ScheduleEvent['type'], index = 0): ScheduleEvent => ({ key: `${type}-${index}`, type, date: '2026-10-19', time: '', title: `TEST-CONT ${type}`, fields: [{ label: '仓库', value: 'ONT8' }] })
|
describe('appointment calendar interactions', () => {
|
||||||
const render = (events: ScheduleEvent[] = [], initialDate = '2026-10-19') => mount(AppointmentCalendarPanel, { props: { initialDate, events },
|
it('keeps creation beside the title and record actions beside data notices', () => {
|
||||||
global: { stubs: { ElButton: { template: '<button><slot /></button>' } } } })
|
const wrapper = mount(AppointmentCalendarPanel, {
|
||||||
function reportedDispatch() {
|
props: { canCreate: true, events: [], notices: ['数据范围不完整'] },
|
||||||
const row: TripCalendarEntry = { sourceType: 'DISPATCH', dispatchNo: 'PC-CALENDAR-001', containerNumbers: ['TSTU1234567', 'TSTU7654321'], status: 'PLANNED', originWarehouseId: '1', originWarehouseCode: 'LAX', originWarehouseName: '洛杉矶仓', originCountryCode: 'US', originTimezone: 'America/Los_Angeles', originWarehouseStatus: 'ACTIVE', plannedDepartureAt: '2026-10-22T16:00:00Z', expectedDriverEndAt: null, departedAt: null, completedAt: null, stops: [{ name: '洛杉矶仓' }, { name: 'ONT8' }], incompleteReasons: [] }
|
slots: { 'toolbar-actions': '<button>未定时安排</button><button>取消记录</button>' },
|
||||||
return projectTripCalendar({ records: [row, row], unresolvedRecords: [] }, { from: '2026-10-01', to: '2026-11-01' }).events
|
global: { stubs: { ElButton: { template: '<button><slot /></button>' } }, directives: { loading: {} } },
|
||||||
}
|
})
|
||||||
describe('four-type appointment calendar', () => {
|
expect(wrapper.get('.calendar-label').text()).toContain('新增预约')
|
||||||
it.each(['TSTU1234567', 'tstu1234567', 'TSTU7654321', ' tstu7654321 '])('finds the one shared dispatch by associated container %s on its origin-local date, not the Beijing date', async keyword => {
|
const actions = wrapper.get('[aria-label="预约记录与数据提示"]')
|
||||||
const wrapper = render(reportedDispatch(), '2026-10-23')
|
expect(actions.text()).toContain('未定时安排')
|
||||||
const search = wrapper.get('[aria-label="搜索当前日历"]')
|
expect(actions.text()).toContain('取消记录')
|
||||||
expect(search.attributes('placeholder')).toBe('柜号、排车单号、仓库')
|
expect(actions.get('summary').text()).toContain('数据提示')
|
||||||
await search.setValue(keyword)
|
|
||||||
expect(wrapper.findAll('.detail-event')).toHaveLength(0)
|
|
||||||
expect(wrapper.get('[aria-label="当天安排"]').text()).toContain('当天暂无安排')
|
|
||||||
expect(wrapper.get('[data-date="2026-10-23"]').findAll('.event-chip')).toHaveLength(0)
|
|
||||||
expect(wrapper.get('[data-date="2026-10-22"]').findAll('.event-chip')).toHaveLength(1)
|
|
||||||
await wrapper.get('[data-date="2026-10-22"]').trigger('click')
|
|
||||||
expect(wrapper.findAll('.detail-event')).toHaveLength(1)
|
|
||||||
expect(wrapper.get('.detail-event').text()).toContain('PC-CALENDAR-001')
|
|
||||||
expect(wrapper.get('.detail-event').text()).toContain('09:00')
|
|
||||||
expect(wrapper.get('.detail-event').text()).toContain('TSTU1234567、TSTU7654321')
|
|
||||||
expect(wrapper.get('.detail-event').text()).toContain('2026-10-22 09:00')
|
|
||||||
expect(wrapper.emitted('range')).toBeUndefined()
|
|
||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
it('does not match an unrelated container and can find the same event by the dispatch number', async () => {
|
const render = () => mount(AppointmentCalendarPanel, {
|
||||||
const wrapper = render(reportedDispatch(), '2026-10-22')
|
props: { initialDate: '2026-09-24', canCreate: true, events: [
|
||||||
await wrapper.get('[aria-label="搜索当前日历"]').setValue('UNRELATED9999')
|
{ key: 'a', type: 'delivery', date: '2026-09-24', time: '09:00-11:00', title: 'ONT8 预约送货', fields: [], canEdit: true, canDelete: true },
|
||||||
expect(wrapper.findAll('.detail-event')).toHaveLength(0)
|
] },
|
||||||
expect(wrapper.findAll('.event-chip')).toHaveLength(0)
|
global: { stubs: { ElButton: { template: '<button><slot /></button>' } }, directives: { loading: {} } },
|
||||||
await wrapper.get('[aria-label="搜索当前日历"]').setValue('PC-CALENDAR-001')
|
|
||||||
expect(wrapper.findAll('.detail-event')).toHaveLength(1)
|
|
||||||
expect(wrapper.findAll('.event-chip')).toHaveLength(1)
|
|
||||||
expect(wrapper.emitted('range')).toBeUndefined()
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
})
|
||||||
it('shows all four types by default with a calendar and persistent daily detail', () => {
|
|
||||||
const wrapper = render(scheduleTypes.map(type => event(type)))
|
it('opens a readable appointment without exposing write actions', async () => {
|
||||||
expect(wrapper.findAll('[aria-label="安排类型"] input')).toHaveLength(4)
|
|
||||||
expect(wrapper.get('[aria-label="安排类型"]').text()).toBe('到港排车还柜计划到仓')
|
|
||||||
expect(wrapper.findAll('.detail-event')).toHaveLength(4)
|
|
||||||
expect(wrapper.get('[aria-label="当天安排"] header').text()).toContain('4 项安排')
|
|
||||||
expect(wrapper.findAll('.calendar-day')).toHaveLength(35)
|
|
||||||
expect(wrapper.find('[data-date="2026-11-01"]').exists()).toBe(true)
|
|
||||||
expect(wrapper.find('[data-date="2026-11-02"]').exists()).toBe(false)
|
|
||||||
expect(wrapper.text()).not.toMatch(/新增预约|全局待办|需复核|中转|直送/)
|
|
||||||
})
|
|
||||||
it('filters locally without requesting another range', async () => {
|
|
||||||
const wrapper = render([event('arrival'), event('dispatch')])
|
|
||||||
await wrapper.get('[aria-label="安排类型"] input').setValue(false)
|
|
||||||
expect(wrapper.findAll('.detail-event')).toHaveLength(1)
|
|
||||||
await wrapper.get('[aria-label="搜索当前日历"]').setValue('missing')
|
|
||||||
expect(wrapper.text()).toContain('当天暂无安排')
|
|
||||||
expect(wrapper.emitted('range')).toBeUndefined()
|
|
||||||
})
|
|
||||||
it('offers creation in the header only when authorized', async () => {
|
|
||||||
const wrapper = render()
|
const wrapper = render()
|
||||||
expect(wrapper.findAll('button').some(button => button.text() === '新增预约')).toBe(false)
|
const event = {key:'a',type:'delivery' as const,date:'2026-09-24',time:'09:00',title:'预约',fields:[],canView:true,canEdit:false,canDelete:false}
|
||||||
await wrapper.setProps({ canCreate: true })
|
await wrapper.setProps({events:[event]})
|
||||||
await wrapper.findAll('.calendar-controls button').find(button => button.text() === '新增预约')!.trigger('click')
|
const actions=wrapper.get('.detail-event footer')
|
||||||
expect(wrapper.emitted('create')).toEqual([[]])
|
expect(actions.text()).toBe('查看预约')
|
||||||
expect(wrapper.emitted('range')).toBeUndefined()
|
await actions.get('button').trigger('click')
|
||||||
|
expect(wrapper.emitted('view')?.[0]).toEqual([event])
|
||||||
|
expect(wrapper.emitted('edit')).toBeUndefined()
|
||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
it('changes the selected date locally and requests one range per mode or period change', async () => {
|
it('hides optional references by default and counts only appointments after enabling them', async () => {
|
||||||
const wrapper = render()
|
const wrapper = render()
|
||||||
await wrapper.get('[data-date="2026-10-20"]').trigger('click')
|
await wrapper.setProps({ events: [
|
||||||
|
{ key: 'a', type: 'delivery', date: '2026-09-24', time: '09:00', title: '收货预约', fields: [] },
|
||||||
|
{ key: 'b', type: 'arrival', date: '2026-09-24', time: '08:00', title: '到港参考', fields: [] },
|
||||||
|
{ key: 'c', type: 'trip', date: '2026-09-24', time: '07:00', title: '运输计划', fields: [] },
|
||||||
|
] })
|
||||||
|
expect(wrapper.findAll('.detail-event')).toHaveLength(1)
|
||||||
|
const switches = wrapper.get('[aria-label="参考图层"]').findAll('input')
|
||||||
|
await switches[0]!.setValue(true); await switches[1]!.setValue(true)
|
||||||
|
expect(wrapper.findAll('.detail-event')).toHaveLength(3)
|
||||||
|
expect(wrapper.get('[aria-label="当天安排"] header').text()).toContain('1 项预约')
|
||||||
|
expect(wrapper.get('[aria-label="当天安排"] header').text()).toContain('2 条参考计划')
|
||||||
expect(wrapper.emitted('range')).toBeUndefined()
|
expect(wrapper.emitted('range')).toBeUndefined()
|
||||||
expect(wrapper.get('[aria-label="当天安排"]').text()).toContain('2026-10-20')
|
})
|
||||||
|
it('selects an already loaded date without requesting data again', async () => {
|
||||||
|
const wrapper = render()
|
||||||
|
await wrapper.get('[aria-label="2026-09-25,0 项安排"]').trigger('click')
|
||||||
|
expect(wrapper.emitted('range')).toBeUndefined()
|
||||||
|
expect(wrapper.get('[aria-label="当天安排"]').text()).toContain('当天暂无预约')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows an overnight slot on both days without fetching again and excludes midnight ends', async () => {
|
||||||
|
const wrapper = render()
|
||||||
|
await wrapper.setProps({ events: [
|
||||||
|
{ key: 'overnight', type: 'delivery', date: '2026-09-23', endAt: '2026-09-24T01:00:00', time: '23:00–01:00', title: '跨日送仓', fields: [] },
|
||||||
|
{ key: 'midnight', type: 'delivery', date: '2026-09-23', endAt: '2026-09-24T00:00:00', time: '23:00–00:00', title: '午夜结束', fields: [] },
|
||||||
|
] })
|
||||||
|
expect(wrapper.find('[aria-label="2026-09-23,2 项安排"]').exists()).toBe(true)
|
||||||
|
expect(wrapper.find('[aria-label="2026-09-24,1 项安排"]').exists()).toBe(true)
|
||||||
|
expect(wrapper.get('[aria-label="当天安排"]').text()).toContain('跨日送仓')
|
||||||
|
expect(wrapper.get('[aria-label="当天安排"]').text()).not.toContain('午夜结束')
|
||||||
|
expect(wrapper.emitted('range')).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('requests exactly one range for a view switch and navigates seven days', async () => {
|
||||||
|
const wrapper = render()
|
||||||
await wrapper.get('[aria-label="预约视图"]').findAll('button')[1]!.trigger('click')
|
await wrapper.get('[aria-label="预约视图"]').findAll('button')[1]!.trigger('click')
|
||||||
expect(wrapper.emitted('range')).toEqual([[{ from: '2026-10-19', to: '2026-10-26' }]])
|
expect(wrapper.emitted('range')).toEqual([[{ from: '2026-09-21', to: '2026-09-28' }]])
|
||||||
await wrapper.get('[aria-label="下一周"]').trigger('click')
|
await wrapper.get('[aria-label="下一周"]').trigger('click')
|
||||||
expect(wrapper.emitted('range')?.at(-1)).toEqual([{ from: '2026-10-26', to: '2026-11-02' }])
|
expect(wrapper.emitted('range')?.at(-1)).toEqual([{ from: '2026-09-28', to: '2026-10-05' }])
|
||||||
})
|
})
|
||||||
it('limits previews to three while retaining every event in the daily details', () => {
|
|
||||||
const wrapper = render(Array.from({ length: 23 }, (_, index) => event('arrival', index)))
|
it('keeps busy days to three previews in both views and exposes the full count', async () => {
|
||||||
expect(wrapper.get('[data-date="2026-10-19"]').findAll('.event-chip')).toHaveLength(3)
|
|
||||||
expect(wrapper.get('.event-more').text()).toBe('还有 20 条')
|
|
||||||
expect(wrapper.findAll('.detail-event')).toHaveLength(23)
|
|
||||||
})
|
|
||||||
it('keeps undated records outside date cells and exposes them explicitly', async () => {
|
|
||||||
const wrapper = render([{ ...event('warehouse'), date: null }])
|
|
||||||
expect(wrapper.findAll('.event-chip')).toHaveLength(0)
|
|
||||||
await wrapper.get('.undated-button').trigger('click')
|
|
||||||
expect(wrapper.findAll('.detail-event')).toHaveLength(1)
|
|
||||||
expect(wrapper.get('[aria-label="当天安排"]').text()).toContain('日期未定')
|
|
||||||
})
|
|
||||||
it('retains business links and exposes editing only with authoritative eligibility', async () => {
|
|
||||||
const row = { ...event('warehouse'), sourcePath: '/container-loading/overseas/1', canEdit: true }
|
|
||||||
const wrapper = render([row])
|
|
||||||
await wrapper.get('.detail-event footer').findAll('button')[0]!.trigger('click')
|
|
||||||
await wrapper.get('.detail-event footer').findAll('button')[1]!.trigger('click')
|
|
||||||
expect(wrapper.emitted('open')).toEqual([[row]])
|
|
||||||
expect(wrapper.emitted('edit')).toEqual([[row]])
|
|
||||||
await wrapper.setProps({ events: [{ ...row, canEdit: false, sourcePath: undefined }] })
|
|
||||||
expect(wrapper.find('.detail-event footer').exists()).toBe(false)
|
|
||||||
})
|
|
||||||
it('distinguishes loading and partial failure from a complete empty day', async () => {
|
|
||||||
const wrapper = render()
|
const wrapper = render()
|
||||||
await wrapper.setProps({ loading: true })
|
await wrapper.setProps({ events: Array.from({ length: 233 }, (_, index) => ({
|
||||||
expect(wrapper.text()).toContain('正在读取安排')
|
key: `arrival-${index}`, type: 'arrival' as const, date: '2026-09-24', time: '09:00',
|
||||||
expect(wrapper.text()).not.toContain('当天暂无安排')
|
title: `船舶 ${index}`, fields: [],
|
||||||
await wrapper.setProps({ loading: false, incomplete: true })
|
})) })
|
||||||
expect(wrapper.text()).toContain('部分数据不可用')
|
await wrapper.get('[aria-label="参考图层"] input').setValue(true)
|
||||||
expect(wrapper.text()).not.toContain('当天暂无安排')
|
for (const view of ['month', 'week']) {
|
||||||
|
if (view === 'week') await wrapper.get('[aria-label="预约视图"]').findAll('button')[1]!.trigger('click')
|
||||||
|
const day = wrapper.get('[aria-label="2026-09-24,233 项安排"]')
|
||||||
|
expect(day.findAll('.event-chip')).toHaveLength(3)
|
||||||
|
expect(day.attributes('title')).toContain('共 233 条安排')
|
||||||
|
expect(day.get('.event-more').text()).toBe('还有 230 条')
|
||||||
|
expect(wrapper.findAll('.detail-event')).toHaveLength(233)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses the selected day for creation and emits edit/delete only from detail actions', async () => {
|
||||||
|
const wrapper = render()
|
||||||
|
await wrapper.findAll('button').find(button => button.text() === '+ 新增预约')!.trigger('click')
|
||||||
|
expect(wrapper.emitted('create')).toEqual([['2026-09-24']])
|
||||||
|
await wrapper.findAll('button').find(button => button.text() === '编辑')!.trigger('click')
|
||||||
|
await wrapper.findAll('button').find(button => button.text() === '取消预约')!.trigger('click')
|
||||||
|
expect(wrapper.emitted('edit')?.[0]?.[0]).toMatchObject({ key: 'a' })
|
||||||
|
expect(wrapper.emitted('delete')?.[0]?.[0]).toMatchObject({ key: 'a' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders many inbound codes outside the two-column fields with only three previews', async () => {
|
||||||
|
const wrapper = render()
|
||||||
|
await wrapper.setProps({ events: [{
|
||||||
|
key: 'many', type: 'delivery', date: '2026-09-24', time: '09:00', title: 'ONT8 预约送仓',
|
||||||
|
fields: [{ label: '货物信息', value: '20 票 / 12 个客户' }],
|
||||||
|
inboundCodes: Array.from({ length: 20 }, (_, index) => `WT-INBOUND-${index}`), canEdit: true,
|
||||||
|
}] })
|
||||||
|
const card = wrapper.get('.detail-event')
|
||||||
|
expect(card.get('dl').text()).not.toContain('WT-INBOUND')
|
||||||
|
expect(card.findAll('.inbound-codes li')).toHaveLength(3)
|
||||||
|
expect(card.get('.inbound-codes').text()).toContain('20 个')
|
||||||
|
expect(card.get('footer').text()).toContain('编辑')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,119 +1,209 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import '@/styles/adminDensity.css'
|
import '@/styles/adminDensity.css'
|
||||||
import { computed, ref } from 'vue'
|
import { computed, ref } from 'vue'
|
||||||
import { Plus } from '@lucide/vue'
|
import AppointmentInboundCodes from './AppointmentInboundCodes.vue'
|
||||||
import { calendarDates, calendarRange, dateKey, moveCalendar, type CalendarMode } from './calendar'
|
import { addDays, calendarDates, calendarRange, dateKey, moveCalendar, occursOnDate, type CalendarMode } from './calendar'
|
||||||
import { scheduleLabels, scheduleTypes, type ScheduleEvent, type ScheduleType } from './schedule'
|
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{ events: ScheduleEvent[]; loading?: boolean; incomplete?: boolean; initialDate?: string; initialMode?: CalendarMode; canCreate?: boolean }>(),
|
export interface CalendarEvent {
|
||||||
{ loading: false, incomplete: false, initialDate: '', initialMode: 'month', canCreate: false })
|
key: string
|
||||||
const emit = defineEmits<{ range: [range: { from: string; to: string }]; select: [date: string, mode: CalendarMode]; open: [event: ScheduleEvent]; edit: [event: ScheduleEvent]; create: [] }>()
|
date: string
|
||||||
const selectedDate = ref(props.initialDate || dateKey(new Date())), mode = ref<CalendarMode>(props.initialMode)
|
endAt?: string
|
||||||
const types = ref<ScheduleType[]>([...scheduleTypes]), keyword = ref(''), undated = ref(false)
|
time: string
|
||||||
|
type: 'arrival' | 'delivery' | 'pickup' | 'trip'
|
||||||
|
title: string
|
||||||
|
subtitle?: string
|
||||||
|
fields: Array<{ label: string; value?: string | null }>
|
||||||
|
inboundCodes?: Array<string | null | undefined>
|
||||||
|
canEdit?: boolean
|
||||||
|
canView?: boolean
|
||||||
|
canDelete?: boolean
|
||||||
|
sourcePath?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<{
|
||||||
|
notices?: string[]
|
||||||
|
events: CalendarEvent[]
|
||||||
|
loading?: boolean
|
||||||
|
incomplete?: boolean
|
||||||
|
canCreate?: boolean
|
||||||
|
initialDate?: string
|
||||||
|
}>(), { notices: () => [], loading: false, incomplete: false, canCreate: false, initialDate: '' })
|
||||||
|
const emit = defineEmits<{
|
||||||
|
layers: [layers: { arrivals: boolean; trips: boolean }]
|
||||||
|
range: [range: { from: string; to: string }]
|
||||||
|
create: [date: string]
|
||||||
|
edit: [event: CalendarEvent]
|
||||||
|
view: [event: CalendarEvent]
|
||||||
|
delete: [event: CalendarEvent]
|
||||||
|
open: [event: CalendarEvent]
|
||||||
|
}>()
|
||||||
|
const showArrivals = ref(false), showTrips = ref(false)
|
||||||
|
function updateLayers() { emit('layers', { arrivals: showArrivals.value, trips: showTrips.value }) }
|
||||||
|
const visibleEvents = computed(() => props.events.filter(event => (event.type !== 'arrival' || showArrivals.value) && (event.type !== 'trip' || showTrips.value)))
|
||||||
|
const selectedDate = ref(props.initialDate || dateKey(new Date()))
|
||||||
|
const mode = ref<CalendarMode>('month')
|
||||||
const dates = computed(() => calendarDates(selectedDate.value, mode.value))
|
const dates = computed(() => calendarDates(selectedDate.value, mode.value))
|
||||||
const visibleEvents = computed(() => props.events.filter(event => types.value.includes(event.type) &&
|
|
||||||
`${event.title} ${event.fields.map(field => field.value || '').join(' ')}`.toLowerCase().includes(keyword.value.trim().toLowerCase())))
|
|
||||||
const grouped = computed(() => {
|
const grouped = computed(() => {
|
||||||
const result = new Map<string, ScheduleEvent[]>()
|
const result = new Map<string, CalendarEvent[]>()
|
||||||
for (const event of visibleEvents.value) {
|
for (const event of visibleEvents.value) {
|
||||||
const date = event.date || 'undated'
|
for (const date of dates.value) {
|
||||||
const rows = result.get(date) || []; rows.push(event); result.set(date, rows)
|
if (!occursOnDate(event.date, event.endAt, date)) continue
|
||||||
|
const group = result.get(date) || []
|
||||||
|
group.push(event)
|
||||||
|
result.set(date, group)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for (const rows of result.values()) rows.sort((a, b) => a.time.localeCompare(b.time) || a.key.localeCompare(b.key))
|
for (const group of result.values()) group.sort((a, b) => a.time.localeCompare(b.time) || a.key.localeCompare(b.key))
|
||||||
return result
|
return result
|
||||||
})
|
})
|
||||||
const selectedEvents = computed(() => grouped.value.get(undated.value ? 'undated' : selectedDate.value) || [])
|
const selectedEvents = computed(() => grouped.value.get(selectedDate.value) || [])
|
||||||
const heading = computed(() => mode.value === 'month' ? `${selectedDate.value.slice(0, 4)}年${Number(selectedDate.value.slice(5, 7))}月` : `${dates.value[0]} — ${dates.value.at(-1)}`)
|
const appointmentCount = computed(() => selectedEvents.value.filter(event => event.type === 'delivery' || event.type === 'pickup').length)
|
||||||
|
const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
|
||||||
|
const eventTypeLabels = { arrival: '船舶到港', delivery: '预约送仓', pickup: '预约提柜', trip: '用车计划' }
|
||||||
|
const heading = computed(() => mode.value === 'month'
|
||||||
|
? `${selectedDate.value.slice(0, 4)}年${Number(selectedDate.value.slice(5, 7))}月`
|
||||||
|
: `${dates.value[0]} — ${addDays(calendarRange(selectedDate.value, mode.value).to, -1)}`)
|
||||||
function select(date: string) {
|
function select(date: string) {
|
||||||
const before = calendarRange(selectedDate.value, mode.value)
|
const before = calendarRange(selectedDate.value, mode.value)
|
||||||
selectedDate.value = date; undated.value = false
|
selectedDate.value = date
|
||||||
const after = calendarRange(date, mode.value)
|
const after = calendarRange(date, mode.value)
|
||||||
emit('select', date, mode.value)
|
|
||||||
if (before.from !== after.from || before.to !== after.to) emit('range', after)
|
if (before.from !== after.from || before.to !== after.to) emit('range', after)
|
||||||
}
|
}
|
||||||
function changeMode(next: CalendarMode) {
|
function changeMode(next: CalendarMode) {
|
||||||
if (mode.value === next) return
|
if (mode.value === next) return
|
||||||
mode.value = next; emit('select', selectedDate.value, next); emit('range', calendarRange(selectedDate.value, next))
|
mode.value = next
|
||||||
|
emit('range', calendarRange(selectedDate.value, next))
|
||||||
}
|
}
|
||||||
|
defineExpose({ selectedDate, mode })
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="appointment-calendar admin-density admin-workbench" :aria-busy="loading">
|
<section class="appointment-calendar admin-density" :aria-busy="loading">
|
||||||
<div class="calendar-main workbench-panel is-flush">
|
<div class="calendar-main">
|
||||||
<header class="calendar-toolbar">
|
<header class="calendar-toolbar">
|
||||||
<div class="calendar-label">
|
<div class="calendar-label">
|
||||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true"><rect x="3" y="5" width="18" height="16" rx="2" stroke="currentColor" stroke-width="1.8"/><path d="M8 3v4M16 3v4M3 10h18M8 15h3M14 15h3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
|
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true"><rect x="3" y="5" width="18" height="16" rx="2" stroke="currentColor" stroke-width="1.8"/><path d="M8 3v4M16 3v4M3 10h18M8 15h3M14 15h3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
|
||||||
<strong>预约日历</strong>
|
<strong>预约日历</strong>
|
||||||
|
<el-button v-if="canCreate" type="primary" :disabled="loading" @click="emit('create', selectedDate)">+ 新增预约</el-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="calendar-controls">
|
<div class="calendar-controls">
|
||||||
<el-button v-if="canCreate" type="primary" @click="emit('create')"><Plus :size="16" aria-hidden="true" />新增预约</el-button>
|
<div class="view-toggle" role="group" aria-label="预约视图">
|
||||||
<div class="view-toggle workbench-tabs" role="group" aria-label="预约视图"><button type="button" :aria-pressed="mode === 'month'" @click="changeMode('month')">月</button><button type="button" :aria-pressed="mode === 'week'" @click="changeMode('week')">周</button></div>
|
<button type="button" :aria-pressed="mode === 'month'" @click="changeMode('month')">月</button>
|
||||||
|
<button type="button" :aria-pressed="mode === 'week'" @click="changeMode('week')">周</button>
|
||||||
|
</div>
|
||||||
<button class="nav-button" type="button" :aria-label="mode === 'month' ? '上个月' : '上一周'" @click="select(moveCalendar(selectedDate, mode, -1))">‹</button>
|
<button class="nav-button" type="button" :aria-label="mode === 'month' ? '上个月' : '上一周'" @click="select(moveCalendar(selectedDate, mode, -1))">‹</button>
|
||||||
<strong class="calendar-period">{{ heading }}</strong>
|
<strong class="calendar-period">{{ heading }}</strong>
|
||||||
<button class="nav-button" type="button" :aria-label="mode === 'month' ? '下个月' : '下一周'" @click="select(moveCalendar(selectedDate, mode, 1))">›</button>
|
<button class="nav-button" type="button" :aria-label="mode === 'month' ? '下个月' : '下一周'" @click="select(moveCalendar(selectedDate, mode, 1))">›</button>
|
||||||
<el-button @click="select(dateKey(new Date()))">今天</el-button>
|
<el-button @click="select(dateKey(new Date()))">今天</el-button>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="calendar-record-actions" role="group" aria-label="预约记录与数据提示">
|
||||||
|
<slot name="toolbar-actions" />
|
||||||
|
<details v-if="notices.length" class="calendar-data-notices"><summary>数据提示 · {{ notices.length }}</summary><div class="calendar-notice-content" role="status"><p v-for="notice in notices" :key="notice">{{ notice }}</p><slot name="notice-actions" /></div></details>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<div class="calendar-options">
|
<div class="calendar-options">
|
||||||
<div class="calendar-layers" role="group" aria-label="安排类型"><label v-for="type in scheduleTypes" :key="type" class="legend" :class="type"><input v-model="types" type="checkbox" :value="type">{{ scheduleLabels[type] }}</label></div>
|
<div class="calendar-legend"><span v-if="showArrivals" class="legend arrival">船舶到港</span><span class="legend delivery">预约送仓</span><span class="legend pickup">预约提柜</span><span v-if="showTrips" class="legend trip">用车计划</span></div>
|
||||||
<label class="calendar-search"><span class="sr-only">搜索当前日历</span><input class="workbench-input" v-model="keyword" type="search" maxlength="128" placeholder="柜号、排车单号、仓库" aria-label="搜索当前日历"></label>
|
<div class="calendar-layers" role="group" aria-label="参考图层"><label><input v-model="showArrivals" type="checkbox" @change="updateLayers">显示到港参考</label><label><input v-model="showTrips" type="checkbox" @change="updateLayers">显示用车计划</label></div>
|
||||||
<button class="undated-button" type="button" :aria-pressed="undated" @click="undated = !undated">未定日期 {{ grouped.get('undated')?.length || 0 }}</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="weekdays"><span v-for="day in ['周一', '周二', '周三', '周四', '周五', '周六', '周日']" :key="day">{{ day }}</span></div>
|
<div class="weekdays"><span v-for="day in weekdays" :key="day">{{ day }}</span></div>
|
||||||
<div class="calendar-grid" :class="{ 'week-grid': mode === 'week' }">
|
<div v-loading="loading" class="calendar-grid" :class="{ 'week-grid': mode === 'week' }">
|
||||||
<button v-for="date in dates" :key="date" type="button" class="calendar-day" :data-date="date"
|
<button v-for="date in dates" :key="date" type="button" class="calendar-day"
|
||||||
:class="{ selected: !undated && selectedDate === date, outside: mode === 'month' && date.slice(0, 7) !== selectedDate.slice(0, 7) }"
|
:class="{ selected: selectedDate === date, outside: mode === 'month' && date.slice(0, 7) !== selectedDate.slice(0, 7) }"
|
||||||
:aria-label="`${date},${loading ? '加载中' : `${(grouped.get(date) || []).length} 项安排`}`" :aria-pressed="!undated && selectedDate === date" @click="select(date)">
|
:title="`${date},${incomplete ? '已加载' : '共'} ${(grouped.get(date) || []).length} 条安排${incomplete ? '(当前范围不完整)' : ''}`" :aria-label="`${date},${(grouped.get(date) || []).length} 项安排${incomplete ? '(当前范围不完整)' : ''}`" :aria-pressed="selectedDate === date" @click="select(date)">
|
||||||
<span class="day-number">{{ Number(date.slice(8)) }}</span>
|
<span class="day-number">{{ mode === 'week' ? `${Number(date.slice(5, 7))}月` : '' }}{{ Number(date.slice(8)) }}</span>
|
||||||
<span v-if="!loading" class="day-events"><span v-for="event in (grouped.get(date) || []).slice(0, 3)" :key="event.key" class="event-chip" :class="event.type" :title="event.title">{{ event.title }}</span><span v-if="(grouped.get(date) || []).length > 3" class="event-more">还有 {{ (grouped.get(date) || []).length - 3 }} 条</span></span>
|
<span class="day-events">
|
||||||
|
<span v-for="event in (grouped.get(date) || []).slice(0, 3)" :key="event.key" class="event-chip" :class="event.type" :title="`${event.time} ${event.title} · 当天${incomplete ? '已加载' : '共'} ${(grouped.get(date) || []).length} 条安排${incomplete ? '(当前范围不完整)' : ''}`">
|
||||||
|
{{ event.title }}<small v-if="mode === 'week'">{{ event.time }}</small>
|
||||||
|
</span>
|
||||||
|
<span v-if="(grouped.get(date) || []).length > 3" class="event-more">还有 {{ (grouped.get(date) || []).length - 3 }} 条</span>
|
||||||
|
</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<aside class="calendar-detail workbench-panel is-flush" aria-label="当天安排">
|
<aside class="calendar-detail" aria-label="当天安排">
|
||||||
<header><strong>{{ undated ? '未定日期' : selectedDate }}</strong><p v-if="loading">正在读取安排…</p><p v-else>{{ incomplete ? '当前已加载' : undated ? '共有' : '当天共有' }} <b>{{ selectedEvents.length }}</b> 项安排<span v-if="incomplete">(部分数据不可用)</span></p></header>
|
<header><strong>{{ selectedDate }}</strong><p>{{ incomplete ? '当天已加载' : '当天共有' }} <b>{{ appointmentCount }}</b> 项预约<span v-if="selectedEvents.length > appointmentCount">,{{ selectedEvents.length - appointmentCount }} 条参考计划</span><span v-if="incomplete">(当前范围不完整)</span></p></header>
|
||||||
<div class="detail-events" aria-live="polite">
|
<div class="detail-events" aria-live="polite">
|
||||||
<p v-if="!selectedEvents.length && !loading" class="empty-day">{{ incomplete ? '已加载数据中没有安排,请先处理上方数据提示。' : undated ? '没有未定日期的安排' : '当天暂无安排' }}</p>
|
<p v-if="!selectedEvents.length && !loading" class="empty-day">{{ incomplete ? '当前范围内暂无预约;请按上方提示核对缺失资料或失败来源' : '当天暂无预约' }}</p>
|
||||||
<article v-for="event in selectedEvents" :key="event.key" class="detail-event">
|
<article v-for="event in selectedEvents" :key="event.key" class="detail-event">
|
||||||
<div class="event-heading"><span class="event-type" :class="event.type">{{ scheduleLabels[event.type] }}</span><span>{{ event.time || (event.date ? '日期计划' : '日期未定') }}</span></div>
|
<div class="event-heading"><span class="event-type" :class="event.type">{{ eventTypeLabels[event.type] }}</span><span>{{ event.time || '—' }}</span></div>
|
||||||
<h3>{{ event.title }}</h3><p v-if="event.subtitle" class="event-subtitle">{{ event.subtitle }}</p>
|
<h3>{{ event.title }}</h3><p v-if="event.subtitle" class="event-subtitle">{{ event.subtitle }}</p>
|
||||||
<dl><div v-for="field in event.fields" :key="field.label"><dt>{{ field.label }}</dt><dd>{{ field.value || '—' }}</dd></div></dl>
|
<dl><div v-for="field in event.fields" :key="field.label" :class="{ 'wide-field': ['系统单号', '完整时段', '预约备注'].includes(field.label) }"><dt>{{ field.label }}</dt><dd>{{ field.value || '—' }}</dd></div></dl>
|
||||||
<footer v-if="event.sourcePath || event.canEdit"><el-button v-if="event.sourcePath" link type="primary" :disabled="loading" @click="emit('open', event)">{{ event.type === 'dispatch' ? '查看排车' : '查看货柜' }}</el-button><el-button v-if="event.canEdit" link type="primary" :disabled="loading" @click="emit('edit', event)">调整计划到仓</el-button></footer>
|
<AppointmentInboundCodes v-if="event.inboundCodes" :codes="event.inboundCodes" />
|
||||||
|
<footer v-if="event.canView || event.canEdit || event.canDelete || event.sourcePath" class="density-actions">
|
||||||
|
<el-button v-if="event.canView" class="density-action" :disabled="loading" @click="emit('view', event)">查看预约</el-button>
|
||||||
|
<el-button v-if="event.sourcePath" class="density-action" :disabled="loading" @click="emit('open', event)">查看来源</el-button>
|
||||||
|
<el-button v-if="event.canEdit" class="density-action" :disabled="loading" @click="emit('edit', event)">编辑</el-button>
|
||||||
|
<el-button v-if="event.canDelete" class="density-action" data-tone="danger" :disabled="loading" @click="emit('delete', event)">取消预约</el-button>
|
||||||
|
</footer>
|
||||||
</article>
|
</article>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.appointment-calendar { display: grid; align-items: start; grid-template-columns: minmax(0, 1fr) 360px; gap: var(--admin-space-5); color: var(--el-text-color-regular); }
|
.calendar-data-notices { position: relative; font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }
|
||||||
.calendar-main, .calendar-detail { overflow: hidden; }
|
.calendar-data-notices summary { cursor: pointer; padding: var(--admin-space-2) var(--admin-space-3); }
|
||||||
.calendar-toolbar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: var(--admin-space-3); padding: var(--admin-space-5); border-bottom: 1px solid var(--workbench-border); }
|
.calendar-notice-content { position: absolute; top: 100%; right: 0; z-index: 5; width: 320px; padding: var(--admin-space-5); border: 1px solid var(--admin-table-border); border-radius: var(--admin-radius); background: var(--admin-surface); box-shadow: var(--el-box-shadow-light); }
|
||||||
.calendar-label, .calendar-controls { display: flex; align-items: center; gap: var(--admin-space-3); }
|
.calendar-notice-content p { margin: 0; line-height: 1.6; }
|
||||||
.calendar-label > svg { color: var(--workbench-primary); }.calendar-label > strong { font-size: var(--admin-font-section); }
|
.calendar-notice-content p + p { margin-top: var(--admin-space-3); }
|
||||||
.calendar-options, .calendar-layers { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-3); }
|
|
||||||
.calendar-options { padding: var(--admin-space-3) var(--admin-space-5); border-bottom: 1px solid var(--workbench-border); }
|
.appointment-calendar { display: grid; align-items: start; grid-template-columns: minmax(0, 1fr) 360px; gap: var(--admin-space-5); color: #344054; }
|
||||||
.legend { display: inline-flex; align-items: center; gap: var(--admin-space-1); font-size: var(--admin-font-caption); cursor: pointer; color: var(--event-fg); }.legend input { accent-color: var(--event-fg); }
|
.calendar-main, .calendar-detail { background: #fff; border: 1px solid #e4e9f2; border-radius: 10px; overflow: hidden; }
|
||||||
.calendar-search { margin-left: auto; }.calendar-search input { width: 190px; }
|
.calendar-toolbar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: var(--admin-space-3); padding: var(--admin-space-5); border-bottom: 1px solid #edf0f6; }
|
||||||
.view-toggle { display: flex; }
|
.calendar-label, .calendar-controls { display: flex; align-items: center; gap: 10px; }
|
||||||
.nav-button, .undated-button { border: 0; border-radius: var(--admin-radius); background: transparent; cursor: pointer; color: var(--el-text-color-regular); min-width: var(--admin-control-height); min-height: var(--admin-control-height); font: inherit; }
|
.calendar-record-actions { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-3); }
|
||||||
.undated-button[aria-pressed='true'] { background: var(--workbench-surface); color: var(--workbench-primary); font-weight: 600; }.nav-button { border: 1px solid var(--workbench-border); font-size: 22px; }
|
.calendar-record-actions :deep(.el-button + .el-button) { margin-left: 0; }
|
||||||
.calendar-period { font-size: var(--admin-font-section); white-space: nowrap; }
|
.calendar-label > svg { color: #617ce9; }
|
||||||
.weekdays, .calendar-grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); }.weekdays { text-align: center; color: var(--workbench-muted); background: var(--workbench-surface-soft); padding: var(--admin-space-3); font-size: var(--admin-font-caption); }
|
.calendar-label > strong { font-size: var(--admin-font-section); }
|
||||||
.calendar-grid { gap: var(--admin-space-2); padding: var(--admin-space-3); background: var(--workbench-surface-soft); }
|
.calendar-options { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--admin-space-3); padding: var(--admin-space-3) var(--admin-space-5); border-bottom: 1px solid var(--admin-table-border); }
|
||||||
.calendar-day { display: flex; flex-direction: column; align-items: stretch; height: 146px; min-width: 0; padding: var(--admin-space-3); border: 1px solid var(--workbench-border); border-radius: 8px; background: var(--workbench-surface); text-align: left; cursor: pointer; color: inherit; font: inherit; }
|
.calendar-legend, .calendar-layers { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-5); }
|
||||||
.calendar-day.outside { background: var(--workbench-surface-soft); color: var(--workbench-muted); }.calendar-day:hover { border-color: var(--workbench-accent-border); }.calendar-day.selected { border-color: var(--workbench-primary); background: var(--workbench-accent-soft); }
|
.calendar-layers label { display: inline-flex; align-items: center; gap: var(--admin-space-1); cursor: pointer; font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }
|
||||||
button:focus-visible, input:focus-visible { outline: 2px solid var(--workbench-primary); outline-offset: 2px; }
|
.calendar-layers input { margin: 0; accent-color: var(--el-color-primary); }
|
||||||
.day-number { font-size: var(--admin-font-caption); font-weight: 600; }.day-events { display: flex; flex-direction: column; gap: var(--admin-space-1); margin-top: var(--admin-space-2); }
|
.legend { font-size: 12px; white-space: nowrap; }
|
||||||
.event-chip { display: block; padding: 2px 6px; line-height: 18px; border-radius: var(--admin-radius); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--admin-font-caption); }
|
.legend::before { content: ''; display: inline-block; width: 7px; height: 7px; border-radius: 50%; margin-right: 5px; background: #4b78e8; }
|
||||||
.arrival { --event-bg: #edf3ff; --event-fg: #3765d4; }.warehouse { --event-bg: #e8f8f1; --event-fg: #18845f; }.return { --event-bg: #fff4e3; --event-fg: #995a10; }.dispatch { --event-bg: #f2edfa; --event-fg: #725199; }
|
.legend.delivery::before { background: #27a87a; }
|
||||||
.event-chip, .event-type { background: var(--event-bg); color: var(--event-fg); }.event-more, .empty-day { color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); }
|
.legend.pickup::before { background: #c17a20; }
|
||||||
.week-grid .calendar-day { height: 270px; }.calendar-detail > header { padding: var(--admin-space-5); border-bottom: 1px solid var(--workbench-border); }.calendar-detail > header > strong { font-size: var(--admin-font-title); }
|
.legend.trip::before { background: #8562b0; }
|
||||||
.calendar-detail header p { margin: var(--admin-space-2) 0 0; font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }.calendar-detail header b { color: var(--workbench-primary); }
|
.view-toggle { display: flex; border: 1px solid #dbe3ee; border-radius: 6px; padding: 2px; background: #f7f9fc; }
|
||||||
.detail-events { padding: var(--admin-space-5); max-height: calc(100dvh - 260px); overflow-y: auto; }
|
.view-toggle button, .nav-button { border: 0; border-radius: 5px; background: transparent; cursor: pointer; color: #64748b; min-width: 30px; height: 30px; }
|
||||||
.detail-event + .detail-event { border-top: 1px solid var(--workbench-border); margin-top: var(--admin-space-5); padding-top: var(--admin-space-5); }
|
.view-toggle button[aria-pressed='true'] { background: #fff; color: #4167d8; font-weight: 700; }
|
||||||
.event-heading { display: flex; justify-content: space-between; align-items: center; gap: var(--admin-space-3); font-size: var(--admin-font-caption); }.event-type { padding: var(--admin-space-2) var(--admin-space-3); border-radius: var(--admin-radius); }
|
.nav-button { border: 1px solid #dbe3ee; font-size: 22px; }
|
||||||
.detail-event h3 { font-size: var(--admin-font-section); margin: var(--admin-space-3) 0; overflow-wrap: anywhere; }.event-subtitle { color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); overflow-wrap: anywhere; }
|
.calendar-period { font-size: 14px; white-space: nowrap; }
|
||||||
.detail-event dl { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--admin-space-3) var(--admin-space-5); margin: var(--admin-space-3) 0; }.detail-event dt { font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }.detail-event dd { margin: var(--admin-space-1) 0 0; font-size: var(--admin-font-body); overflow-wrap: anywhere; }
|
.weekdays, .calendar-grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); }
|
||||||
.detail-event footer { display: flex; justify-content: flex-end; gap: var(--admin-space-3); border-top: 1px solid var(--workbench-border); padding-top: var(--admin-space-3); }.detail-event footer :deep(.el-button + .el-button) { margin-left: 0; }
|
.weekdays { text-align: center; color: #8491a5; background: #f8faff; padding: var(--admin-space-3) var(--admin-space-5); font-size: var(--admin-font-caption); }
|
||||||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
.calendar-grid { gap: var(--admin-space-2); padding: var(--admin-space-3); background: #fbfcff; }
|
||||||
@media (max-width: 1100px) { .appointment-calendar { grid-template-columns: minmax(0, 1fr); } }
|
.calendar-day { display: flex; flex-direction: column; align-items: stretch; justify-content: flex-start; height: 112px; min-width: 0; padding: var(--admin-space-2); border: 1px solid #e5eaf2; border-radius: 8px; background: #fff; text-align: left; cursor: pointer; color: inherit; font: inherit; overflow: hidden; }
|
||||||
|
.calendar-day.outside { background: #f7f8fa; color: #98a2b3; }
|
||||||
|
.calendar-day:hover { border-color: #bac8ed; background: #f8faff; }
|
||||||
|
.calendar-day.selected { border-color: #617ce9; background: #f5f7ff; }
|
||||||
|
.calendar-day:focus-visible, .nav-button:focus-visible, .view-toggle button:focus-visible { outline: 2px solid #4167d8; outline-offset: 2px; }
|
||||||
|
.day-number { display: block; font-size: 12px; font-weight: 600; }
|
||||||
|
.day-events { display: flex; flex-direction: column; gap: 2px; margin-top: var(--admin-space-1); }
|
||||||
|
.event-chip { display: block; padding: 1px 6px; line-height: 16px; border-radius: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
|
||||||
|
.arrival { --event-bg: #edf3ff; --event-fg: #3765d4; }
|
||||||
|
.delivery { --event-bg: #e8f8f1; --event-fg: #18845f; }
|
||||||
|
.pickup { --event-bg: #fff4e3; --event-fg: #995a10; }
|
||||||
|
.trip { --event-bg: #f2edfa; --event-fg: #725199; }
|
||||||
|
.event-chip, .event-type { background: var(--event-bg); color: var(--event-fg); }
|
||||||
|
.event-chip small { display: block; margin-top: 2px; font-size: 11px; opacity: .8; }
|
||||||
|
.event-more { padding: 1px 6px; line-height: 16px; }
|
||||||
|
.event-more, .empty-day { color: #667085; font-size: 12px; }
|
||||||
|
.week-grid .calendar-day { height: 220px; }
|
||||||
|
.calendar-detail { align-self: start; }
|
||||||
|
.calendar-detail > header { padding: var(--admin-space-5); border-bottom: 1px solid #edf0f6; }
|
||||||
|
.calendar-detail > header > strong { font-size: var(--admin-font-title); }
|
||||||
|
.calendar-detail header p { margin: var(--admin-space-1) 0 0; font-size: var(--admin-font-caption); color: #8491a5; }
|
||||||
|
.calendar-detail header b { color: #617ce9; font-size: var(--admin-font-title); }
|
||||||
|
.detail-events { padding: var(--admin-space-5); max-height: 660px; overflow-y: auto; }
|
||||||
|
.detail-event + .detail-event { border-top: 1px solid #e4e9f2; margin-top: var(--admin-space-5); padding-top: var(--admin-space-5); }
|
||||||
|
.event-heading { display: flex; justify-content: space-between; align-items: center; gap: 10px; font-size: 12px; }
|
||||||
|
.event-type { padding: 5px 8px; border-radius: 4px; font-weight: 600; }
|
||||||
|
.detail-event h3 { font-size: var(--admin-font-section); margin: var(--admin-space-3) 0; overflow-wrap: anywhere; }
|
||||||
|
.event-subtitle { color: #667085; font-size: 13px; overflow-wrap: anywhere; }
|
||||||
|
.detail-event dl { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--admin-space-3) var(--admin-space-5); margin: var(--admin-space-3) 0; }
|
||||||
|
.detail-event .wide-field { grid-column: 1 / -1; }
|
||||||
|
.detail-event dt { font-size: 12px; color: #8491a5; }
|
||||||
|
.detail-event dd { margin: 4px 0 0; font-size: 13px; overflow-wrap: anywhere; }
|
||||||
|
.detail-event footer { display: flex; justify-content: flex-end; border-top: 1px solid #edf0f6; padding-top: 10px; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,185 +1,408 @@
|
|||||||
import { DatePickerStub, TimePickerStub } from './temporal-picker.test-support'
|
import { inject, onBeforeUnmount } from 'vue'
|
||||||
|
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
|
||||||
import { flushPromises, mount } from '@vue/test-utils'
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
import { onBeforeRouteLeave } from 'vue-router'
|
|
||||||
import { ElMessageBox } from 'element-plus'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
import AppointmentCalendarView from './AppointmentCalendarView.vue'
|
import AppointmentCalendarView from './AppointmentCalendarView.vue'
|
||||||
import { getCalendarSources, getWarehouseArrivals, saveWarehouseArrival, type WarehouseArrival } from './scheduleApi'
|
import { createFbaAppointment, getFbaAppointment, updateFbaAppointment, listFbaAppointmentCalendar, listInboundOrders } from '@/modules/overseas-warehouse'
|
||||||
import { listTripCalendar, type TripCalendarEntry } from './tripCalendar'
|
import { listArrivalCalendar, listPickupCalendar } from './api'
|
||||||
import type { ScheduleEvent } from './schedule'
|
import { listTripCalendar } from './tripCalendar'
|
||||||
const routing = vi.hoisted(() => ({ query: { date: '2026-10-19' } as Record<string, string>, push: vi.fn(), replace: vi.fn(), denied: new Set<string>() }))
|
vi.mock('./tripCalendar', async (original) => ({...(await original<typeof import('./tripCalendar')>()),listTripCalendar:vi.fn()}))
|
||||||
vi.mock('vue-router', () => ({ useRoute: () => routing, useRouter: () => routing, onBeforeRouteLeave: vi.fn(), onBeforeRouteUpdate: vi.fn() }))
|
import { resolvePlanningSource, saveFollowup, listUnscheduledAppointments } from './planningApi'
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: (permission: string) => !routing.denied.has(permission) }) }))
|
const routing = vi.hoisted(() => ({ query: {} as Record<string,string>, canSourceRead: true, canPickup: true, canTrips: true, canWrite: true, containerPending: false }))
|
||||||
vi.mock('./scheduleApi', () => ({ getCalendarSources: vi.fn(), getWarehouseArrivals: vi.fn(), saveWarehouseArrival: vi.fn() }))
|
vi.mock('./planningApi', () => ({ resolvePlanningSource: vi.fn(), listPlanningCargo: vi.fn(), getFollowups: vi.fn(), saveFollowup: vi.fn(), listUnscheduledAppointments: vi.fn() }))
|
||||||
vi.mock('./tripCalendar', async original => ({ ...await original<typeof import('./tripCalendar')>(), listTripCalendar: vi.fn() }))
|
import { listPlatformWarehouses } from '@/modules/warehouses'
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
vi.mock('@/modules/warehouses', () => ({ listPlatformWarehouses: vi.fn() }))
|
||||||
const warehouse: WarehouseArrival = { sourceContainerBookingId: '1', containerNo: 'TEST-CONT', warehouseName: '美国仓', warehouseCode: 'US-W', plannedAt: null, actualAt: null, version: 0, planCount: 0, canEdit: true }
|
|
||||||
const row: ScheduleEvent = { key: 'warehouse-1', type: 'warehouse', date: '2026-10-21', time: '', title: 'TEST-CONT 计划到仓', fields: [], warehouse, canEdit: true }
|
vi.mock('vue-router', () => ({ onBeforeRouteLeave: vi.fn(), onBeforeRouteUpdate: vi.fn(), useRoute: () => routing, useRouter: () => ({ push: vi.fn() }) }))
|
||||||
function dispatchEntry(overrides: Partial<TripCalendarEntry> = {}): TripCalendarEntry {
|
|
||||||
return { sourceType: 'DISPATCH', dispatchNo: 'PC-CALENDAR-001', containerNumbers: ['TSTU1234567', 'TSTU7654321'], status: 'PLANNED', originWarehouseId: '1', originWarehouseCode: 'LAX', originWarehouseName: '洛杉矶仓', originCountryCode: 'US', originTimezone: 'America/Los_Angeles', originWarehouseStatus: 'ACTIVE', plannedDepartureAt: '2026-10-22T16:00:00Z', expectedDriverEndAt: null, departedAt: null, completedAt: null, stops: [{ name: '洛杉矶仓' }, { name: 'ONT8' }], incompleteReasons: [], ...overrides }
|
vi.mock('./api', () => ({ listArrivalCalendar: vi.fn(), listPickupCalendar: vi.fn(), deleteAppointment: vi.fn() }))
|
||||||
}
|
|
||||||
export function renderSchedule() {
|
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: (permission: string) => (permission !== 'write' || routing.canWrite) && (permission !== 'source-read' || routing.canSourceRead) && (permission !== 'platform:firstleg:terminal-drayage:list' || routing.canPickup) && (permission !== 'platform:fleet:trip:list' || routing.canTrips) }) }))
|
||||||
return mount(AppointmentCalendarView, { global: { stubs: {
|
vi.mock('@/modules/overseas-warehouse', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/modules/overseas-warehouse')>()),
|
||||||
ElDatePicker: DatePickerStub, ElTimePicker: TimePickerStub,
|
createFbaAppointment: vi.fn(), getFbaAppointment: vi.fn(), listFbaAppointmentCalendar: vi.fn(),
|
||||||
|
listInboundOrders: vi.fn(), updateFbaAppointment: vi.fn(),
|
||||||
|
overseasWarehousePermissions: { inboundOrderAppointment: 'write', lastMileOrderList: 'source-read' },
|
||||||
|
}))
|
||||||
|
vi.mock('element-plus', () => ({ ElMessage: { success: vi.fn(), warning: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
||||||
|
|
||||||
|
const candidates = [
|
||||||
|
{ lineId: '9007199254740993', customerId: 'A', overseasWarehouseId: '100', fbaWarehouseCode: 'ONT8', planId: '1', planNo: 'IN-A', orderId: '10' },
|
||||||
|
{ lineId: '9007199254740994', customerId: 'B', overseasWarehouseId: '100', fbaWarehouseCode: 'ONT8', planId: '2', planNo: 'IN-B', orderId: '20' },
|
||||||
|
]
|
||||||
|
function render(openCalendar = true) {
|
||||||
|
const wrapper = mount(AppointmentCalendarView, { global: { directives: { loading: {} }, stubs: {
|
||||||
|
AppointmentCancellationDialog: {name:'AppointmentCancellationDialog',template:'<div>取消弹窗</div>'},
|
||||||
|
AppointmentCancellationHistory: {name:'AppointmentCancellationHistory',template:'<div>取消历史详情</div>'},
|
||||||
|
AppointmentCancellationRecords: {name:'AppointmentCancellationRecords',template:'<button data-history-view @click="$emit(\'view\',\'AP-CANCEL\')">查看取消记录</button>'},
|
||||||
AdminPage: { template: '<main><slot /></main>' },
|
AdminPage: { template: '<main><slot /></main>' },
|
||||||
AppointmentCalendarPanel: { name: 'AppointmentCalendarPanel', props: ['events', 'loading', 'incomplete', 'initialDate', 'initialMode', 'canCreate'], template: '<section data-calendar />' },
|
AppointmentContainerPanel: { name: 'AppointmentContainerPanel', setup() {
|
||||||
AppDialog: { name: 'AppDialog', props: ['modelValue', 'beforeClose', 'confirmDisabled', 'confirmLoading'], emits: ['confirm'], template: '<section v-if="modelValue" data-dialog><slot /><button data-save :disabled="confirmDisabled" @click="$emit(\'confirm\')">保存</button><button data-close @click="beforeClose(() => {})">关闭</button></section>' },
|
const register = inject<(guard: () => boolean) => () => void>('appointment-register-leave-guard')!
|
||||||
WorkDetailPanel: true, SourceAppointmentPanel: true, ApiErrorMeta: true,
|
const unregister = register(() => !routing.containerPending)
|
||||||
|
onBeforeUnmount(unregister)
|
||||||
|
}, template: '<div>整柜跟进工作区</div>' },
|
||||||
|
AppointmentCalendarPanel: { name: 'AppointmentCalendarPanel', mounted() { this.$emit('layers', { arrivals: true, trips: true }) }, props: ['events', 'incomplete', 'notices'], template: '<div><button data-create @click="$emit(\'create\', \'2026-10-09\')">新增预约</button><slot name="notice-actions" /><slot name="toolbar-actions" /></div>' },
|
||||||
|
AppDialog: { name: 'AppDialog', props: ['modelValue', 'showConfirm', 'beforeClose'], template: '<div v-if="modelValue"><slot /><button data-close @click="$emit(\'update:model-value\',false)">关闭</button><button v-if="showConfirm !== false" data-save @click="$emit(\'confirm\')">保存</button></div>' },
|
||||||
ElForm: { template: '<form><slot /></form>' },
|
ElForm: { template: '<form><slot /></form>' },
|
||||||
ElFormItem: { props: ['label'], template: '<label>{{ label }}<slot /></label>' },
|
ElFormItem: { template: '<label><slot /></label>' },
|
||||||
ElInput: { props: ['modelValue', 'disabled'], emits: ['update:modelValue'], template: '<input :value="modelValue" :disabled="disabled" @input="$emit(\'update:modelValue\', $event.target.value)">' },
|
ElInput: { props: ['modelValue', 'placeholder'], template: '<input :placeholder="placeholder" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
||||||
AppointmentCreatePanel: { name: 'AppointmentCreatePanel', props: ['canWrite', 'canLeave'], emits: ['created'], template: '<section data-create-panel />' },
|
ElDatePicker: { props: ['modelValue'], template: '<input data-date :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
||||||
LoadErrorState: { props: ['title', 'message'], emits: ['retry'], template: '<section role="alert">{{ title }} {{ message }}<slot name="details" /><button data-retry @click="$emit(\'retry\')">重试</button></section>' },
|
ElButton: { template: '<button><slot /></button>' },
|
||||||
|
ElSelect: { name: 'ElSelect', emits: ['update:modelValue', 'change'], props: ['modelValue', 'remoteMethod'], template: '<select :value="modelValue" @change="$emit(\'update:modelValue\', $event.target.value); $emit(\'change\', $event.target.value)"><option value="">请选择</option><slot /></select>' },
|
||||||
|
ElOption: { props: ['value', 'label'], template: '<option :value="value">{{ label }}</option>' },
|
||||||
|
DataTable: { name: 'DataTable', props: ['data'], template: '<div><slot name="toolbar-actions" /><slot v-for="row in data" name="actions" :row="row"/><button data-select @click="$emit(\'selection-change\', data)">选择货物</button></div>' },
|
||||||
|
LoadErrorState: true, ApiErrorMeta: true, AppointmentFollowupDialog: true, AppointmentCargoPanel: { name: 'AppointmentCargoPanel', props: ['externalSource'], template: '<div>合批工作区</div>' },
|
||||||
} } })
|
} } })
|
||||||
|
if (openCalendar) void wrapper.findAll('button').find(button => button.text() === '预约日历')!.trigger('click')
|
||||||
|
return wrapper
|
||||||
}
|
}
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks(); routing.query = { date: '2026-10-19' }; routing.denied.clear()
|
describe('appointment calendar data integration', () => {
|
||||||
vi.mocked(getCalendarSources).mockResolvedValue({ containers: [{ containerBookingId: '1', cabinetNo: 'D0001', containerNo: 'TEST-CONT', vesselName: null, voyageNo: null, destinationPortName: null, destinationWarehouseCode: null, arrivalAt: '2026-10-19T10:00:00', arrivalType: 'ACTUAL' }], emptyReturns: [], emptyReturnsReadable: true })
|
beforeEach(() => {
|
||||||
vi.mocked(getWarehouseArrivals).mockResolvedValue([warehouse])
|
vi.resetAllMocks()
|
||||||
vi.mocked(listTripCalendar).mockResolvedValue({ records: [], unresolvedRecords: [] })
|
routing.query = {}; routing.canSourceRead = true; routing.canPickup = true; routing.canTrips = true; routing.canWrite = true; routing.containerPending = false
|
||||||
vi.mocked(saveWarehouseArrival).mockResolvedValue({})
|
vi.mocked(listPlatformWarehouses).mockResolvedValue({ records: ['ONT8', 'LAX9'].map(code => ({ id: code, tenantId: 0, warehouseCode: code, warehouseName: code, warehouseType: 'FBA' as const, status: 'ACTIVE' as const, internalCode: null, countryCode: 'US', timezone: 'America/Los_Angeles', contactName: null, contactPhone: null, contactEmail: null, remark: null })), page: 1, size: 50, pages: 1, total: 2 })
|
||||||
})
|
vi.mocked(listFbaAppointmentCalendar).mockResolvedValue([])
|
||||||
describe('simplified appointment entry', () => {
|
vi.mocked(listUnscheduledAppointments).mockResolvedValue({records: [], total: 0})
|
||||||
it('opens creation lazily with the original read and write permissions and refreshes after creation', async () => {
|
vi.mocked(listArrivalCalendar).mockResolvedValue([])
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
vi.mocked(listTripCalendar).mockResolvedValue({records:[],unresolvedRecords:[]})
|
||||||
expect(wrapper.find('[data-create-panel]').exists()).toBe(false)
|
vi.mocked(listPickupCalendar).mockResolvedValue({records: [], truncated: false, unclassifiedCount: 0, scopeBasis: 'US_DESTINATION_WAREHOUSE', timeBasis: 'SOURCE_LOCAL_UNSPECIFIED'})
|
||||||
const calendar = wrapper.getComponent({ name: 'AppointmentCalendarPanel' })
|
vi.mocked(listInboundOrders).mockResolvedValue({ records: candidates, total: 2, page: 1, size: 10, pages: 1 })
|
||||||
expect(calendar.props('canCreate')).toBe(true)
|
vi.mocked(createFbaAppointment).mockResolvedValue({ version: 0, id: '1', appointmentNo: 'APT-AB', plannedDate: '2026-10-09', appointmentAt: null, originWarehouseId: '100', appointmentStatus: 'PENDING', selectedCount: 2, fbaWarehouseCode: 'ONT8', items: [] })
|
||||||
calendar.vm.$emit('create'); await flushPromises()
|
})
|
||||||
const panel = wrapper.getComponent({ name: 'AppointmentCreatePanel' })
|
|
||||||
expect(panel.props('canWrite')).toBe(true)
|
it('displays the existing D cabinet number in both arrival and pickup events', async () => {
|
||||||
vi.mocked(getCalendarSources).mockClear()
|
vi.mocked(listArrivalCalendar).mockResolvedValueOnce([{ containerBookingId: '1', cabinetNo: 'D0007', arrivalAt: '2026-10-09T08:00:00', arrivalType: 'ESTIMATED' }])
|
||||||
panel.vm.$emit('created'); await flushPromises()
|
vi.mocked(listPickupCalendar).mockResolvedValueOnce({ records: [{ containerBookingId: '1', cabinetNo: 'D0007', containerNo: null, destinationPortName: null, destinationWarehouseCode: null, fleetSupplierName: null, pickupAppointmentAt: '2026-10-09T09:00:00', actualPickupAt: null }], truncated: false, unclassifiedCount: 0, scopeBasis: 'US_DESTINATION_WAREHOUSE', timeBasis: 'SOURCE_LOCAL_UNSPECIFIED' })
|
||||||
expect(getCalendarSources).toHaveBeenCalledTimes(1)
|
const wrapper = render(); await flushPromises()
|
||||||
await wrapper.get('[data-close]').trigger('click'); await flushPromises()
|
const events = wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).props('events')
|
||||||
expect(wrapper.find('[data-create-panel]').exists()).toBe(false)
|
expect(events).toHaveLength(2)
|
||||||
|
for (const event of events) {
|
||||||
|
expect(event.fields).toContainEqual({ label: '柜次号', value: 'D0007' })
|
||||||
|
expect(event.title).toContain('D0007')
|
||||||
|
}
|
||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
it.each(['platform:overseas-warehouse:inbound-order:fba-appointment', 'platform:overseas-warehouse:last-mile-order:list'])('does not open creation without %s', async permission => {
|
|
||||||
routing.denied.add(permission)
|
it('opens a dated calendar appointment read-only for list-only users', async () => {
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
routing.canWrite=false
|
||||||
const calendar = wrapper.getComponent({ name: 'AppointmentCalendarPanel' })
|
const record={version:0,id:'1',appointmentNo:'AP-DATED',plannedDate:'2026-10-15',originWarehouseId:'100',appointmentStatus:'PENDING',selectedCount:1,fbaWarehouseCode:'ABE3',items:[]}
|
||||||
expect(calendar.props('canCreate')).toBe(false)
|
vi.mocked(listFbaAppointmentCalendar).mockResolvedValue([record])
|
||||||
calendar.vm.$emit('create'); await flushPromises()
|
vi.mocked(getFbaAppointment).mockResolvedValue(record)
|
||||||
expect(wrapper.find('[data-create-panel]').exists()).toBe(false)
|
const wrapper=render();await flushPromises()
|
||||||
|
const panel=wrapper.findComponent({name:'AppointmentCalendarPanel'})
|
||||||
|
expect(panel.props('events')).toEqual(expect.arrayContaining([expect.objectContaining({key:'AP-DATED',canView:true,canEdit:false})]))
|
||||||
|
panel.vm.$emit('view',{key:'AP-DATED'});await flushPromises()
|
||||||
|
expect(getFbaAppointment).toHaveBeenCalledWith('AP-DATED')
|
||||||
|
expect(wrapper.findComponent({name:'FbaAppointmentFields'}).props('disabled')).toBe(true)
|
||||||
|
expect(wrapper.find('[data-save]').exists()).toBe(false)
|
||||||
|
wrapper.findComponent({name:'AppDialog'}).vm.$emit('confirm');await flushPromises()
|
||||||
|
expect(updateFbaAppointment).not.toHaveBeenCalled();wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('uses the dedicated cancellation dialog for an undated appointment instead of editing its status', async () => {
|
||||||
|
const record = { version: 3, id: '1', appointmentNo: 'AP-UNDATED', originWarehouseId: '100', appointmentStatus: 'PENDING', selectedCount: 1, fbaWarehouseCode: 'ABE3', items: [] }
|
||||||
|
vi.mocked(listUnscheduledAppointments).mockResolvedValue({records: [record], total: 1})
|
||||||
|
vi.mocked(getFbaAppointment).mockResolvedValue(record)
|
||||||
|
const wrapper=render(); await flushPromises()
|
||||||
|
await wrapper.get('[data-unscheduled]').trigger('click')
|
||||||
|
await wrapper.findAll('button').find(button=>button.text()==='查看 / 继续')!.trigger('click'); await flushPromises()
|
||||||
|
expect(wrapper.find('option[value="CANCELLED"]').exists()).toBe(false)
|
||||||
|
await wrapper.get('[data-cancel-editing]').trigger('click'); await flushPromises()
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCancellationDialog'}).attributes('appointment-no')).toBe('AP-UNDATED')
|
||||||
|
expect(wrapper.find('[data-save]').exists()).toBe(false)
|
||||||
|
expect(updateFbaAppointment).not.toHaveBeenCalled(); wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('loads cancellation records only after opening the dialog and opens cancelled appointments read-only', async () => {
|
||||||
|
const record = { version: 1, id: '1', appointmentNo: 'AP-CANCEL', originWarehouseId: '100', appointmentStatus: 'CANCELLED', selectedCount: 1, fbaWarehouseCode: 'ABE3', items: [] }
|
||||||
|
vi.mocked(getFbaAppointment).mockResolvedValue(record)
|
||||||
|
const wrapper=render();await flushPromises()
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCancellationRecords'}).exists()).toBe(false)
|
||||||
|
const records=wrapper.get('[data-cancellations]')
|
||||||
|
await records.trigger('click')
|
||||||
|
await wrapper.get('[data-history-view]').trigger('click');await flushPromises()
|
||||||
|
expect(getFbaAppointment).toHaveBeenCalledWith('AP-CANCEL')
|
||||||
|
expect(wrapper.find('[data-save]').exists()).toBe(false)
|
||||||
|
expect(wrapper.findComponent({name:'FbaAppointmentFields'}).props('disabled')).toBe(true)
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCancellationHistory'}).exists()).toBe(false)
|
||||||
|
const history=wrapper.findAll('details').find(d=>d.find('summary').text()==='取消历史')!
|
||||||
|
;(history.element as HTMLDetailsElement).open=true;await history.trigger('toggle')
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCancellationHistory'}).exists()).toBe(true)
|
||||||
|
wrapper.findAllComponents({name:'AppDialog'}).at(-1)!.vm.$emit('confirm');await flushPromises()
|
||||||
|
expect(updateFbaAppointment).not.toHaveBeenCalled();wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refreshes an expanded cancellation list after a successful cancellation', async () => {
|
||||||
|
vi.mocked(listFbaAppointmentCalendar).mockResolvedValue([{version:0,id:'1',appointmentNo:'AP-CANCEL',originWarehouseId:'100',appointmentStatus:'PENDING',selectedCount:1,fbaWarehouseCode:'ABE3',items:[],plannedDate:'2026-10-15'}])
|
||||||
|
const wrapper=render();await flushPromises()
|
||||||
|
const records=wrapper.get('[data-cancellations]')
|
||||||
|
await records.trigger('click')
|
||||||
|
const previous=wrapper.getComponent({name:'AppointmentCancellationRecords'}).vm
|
||||||
|
wrapper.getComponent({name:'AppointmentCalendarPanel'}).vm.$emit('delete',{key:'AP-CANCEL'});await flushPromises()
|
||||||
|
wrapper.getComponent({name:'AppointmentCancellationDialog'}).vm.$emit('cancelled');await flushPromises()
|
||||||
|
expect(wrapper.getComponent({name:'AppointmentCancellationRecords'}).vm).not.toBe(previous)
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCancellationDialog'}).exists()).toBe(false)
|
||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
it('keeps unsaved input when the operator declines to leave', async () => {
|
|
||||||
vi.mocked(ElMessageBox.confirm).mockRejectedValueOnce('cancel')
|
it('keeps the container view mounted while a child has an unresolved command', async () => {
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
const wrapper = render(); await flushPromises()
|
||||||
wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('edit', row); await flushPromises()
|
const tabs = wrapper.get('[aria-label="预约工作视图"]').findAll('button')
|
||||||
await wrapper.get('input').setValue('2026-10-22T09:30')
|
await tabs[1]!.trigger('click'); await flushPromises()
|
||||||
await wrapper.get('[data-close]').trigger('click'); await flushPromises()
|
routing.containerPending = true
|
||||||
expect(ElMessageBox.confirm).toHaveBeenCalled()
|
await tabs[0]!.trigger('click')
|
||||||
expect(wrapper.find('[data-dialog]').exists()).toBe(true)
|
expect(tabs[1]!.attributes('aria-pressed')).toBe('true')
|
||||||
expect((wrapper.get('input').element as HTMLInputElement).value).toBe('2026-10-22T09:30')
|
expect(wrapper.findComponent({ name: 'AppointmentContainerPanel' }).exists()).toBe(true)
|
||||||
|
routing.containerPending = false
|
||||||
|
await tabs[0]!.trigger('click')
|
||||||
|
expect(tabs[0]!.attributes('aria-pressed')).toBe('true')
|
||||||
|
expect(wrapper.findComponent({ name: 'AppointmentContainerPanel' }).exists()).toBe(false)
|
||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
it('loads original sources and real trips without loading work summaries or generated work items', async () => {
|
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
it('opens an unscheduled appointment read-only without allowing a save', async () => {
|
||||||
expect(getWarehouseArrivals).toHaveBeenCalledWith({ from: '2026-09-28', to: '2026-11-02' }, ['1'], expect.any(AbortSignal))
|
routing.canWrite = false
|
||||||
const panel = wrapper.getComponent({ name: 'AppointmentCalendarPanel' })
|
const record = { version: 0, id: '1', appointmentNo: 'AP-READ', originWarehouseId: '100', appointmentStatus: 'PENDING', selectedCount: 1, fbaWarehouseCode: 'ONT8', items: [] }
|
||||||
expect(panel.props('events').map((event: ScheduleEvent) => [event.type, event.date])).toEqual([['arrival', '2026-10-19'], ['warehouse', '2026-10-21']])
|
vi.mocked(listUnscheduledAppointments).mockResolvedValue({ records: [record], total: 1 })
|
||||||
expect(wrapper.text()).not.toMatch(/全局待办|跟进|复核/)
|
vi.mocked(getFbaAppointment).mockResolvedValue(record)
|
||||||
|
const wrapper = render(); await flushPromises()
|
||||||
|
await wrapper.get('[data-unscheduled]').trigger('click')
|
||||||
|
await wrapper.findAll('button').find(b => b.text() === '查看 / 继续')!.trigger('click'); await flushPromises()
|
||||||
|
expect(wrapper.find('[data-save]').exists()).toBe(false)
|
||||||
|
const dialog = wrapper.findAllComponents({ name: 'AppDialog' }).at(-1)!
|
||||||
|
dialog.vm.$emit('confirm'); await flushPromises()
|
||||||
|
expect(updateFbaAppointment).not.toHaveBeenCalled()
|
||||||
|
expect(wrapper.findComponent({ name: 'FbaAppointmentFields' }).props('disabled')).toBe(true)
|
||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
it('keeps available arrivals while reporting a failed warehouse source instead of inventing defaults', async () => {
|
|
||||||
vi.mocked(getWarehouseArrivals).mockRejectedValue(new Error('offline'))
|
it('puts calendar first and opens it by default without reloading when switching back', async () => {
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
const wrapper = render(false); await flushPromises()
|
||||||
expect(wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).props('events').map((event: ScheduleEvent) => event.type)).toEqual(['arrival'])
|
const tabs = wrapper.get('[aria-label="预约工作视图"]').findAll('button')
|
||||||
expect(wrapper.text()).toContain('计划到仓读取失败')
|
expect(tabs.map(button => button.text())).toEqual(['预约日历', '提柜与到仓', '送仓与排车'])
|
||||||
expect(wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).props('incomplete')).toBe(true)
|
expect(tabs[0]!.attributes('aria-pressed')).toBe('true')
|
||||||
wrapper.unmount()
|
expect(wrapper.text()).not.toContain('美国预约总览')
|
||||||
|
expect(listFbaAppointmentCalendar).toHaveBeenCalledTimes(1)
|
||||||
|
expect(listArrivalCalendar).toHaveBeenCalledTimes(1)
|
||||||
|
await tabs[1]!.trigger('click'); await flushPromises()
|
||||||
|
expect(listFbaAppointmentCalendar).toHaveBeenCalledTimes(1)
|
||||||
|
await tabs[0]!.trigger('click'); await flushPromises()
|
||||||
|
expect(listFbaAppointmentCalendar).toHaveBeenCalledTimes(1)
|
||||||
})
|
})
|
||||||
it('does not request unreadable domains and describes the incomplete scope', async () => {
|
it('distinguishes missing country data from truncation instead of suggesting a narrower date range', async () => {
|
||||||
routing.denied.add('platform:overseas-warehouse:dispatch:list'); routing.denied.add('platform:overseas-warehouse:last-mile-order:list')
|
vi.mocked(listPickupCalendar).mockResolvedValueOnce({ records: [], truncated: false, unclassifiedCount: 74, scopeBasis: 'US_DESTINATION_WAREHOUSE', timeBasis: 'SOURCE_LOCAL_UNSPECIFIED' })
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
const wrapper = render(); await flushPromises()
|
||||||
expect(listTripCalendar).not.toHaveBeenCalled(); expect(getWarehouseArrivals).not.toHaveBeenCalled()
|
expect(wrapper.findComponent({ name: 'AppointmentCalendarPanel' }).props('notices').join(' ')).toContain('74 条提柜记录')
|
||||||
expect(wrapper.text()).toContain('缺少排车读取权限')
|
expect(wrapper.text()).not.toContain('缩小日期范围')
|
||||||
expect(wrapper.text()).toContain('缺少尾程订单读取权限')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
})
|
||||||
it('ignores stale calendar responses when the date range changes', async () => {
|
it('shows the original pickup time once without claiming a port time zone and retains partial-source warnings', async () => {
|
||||||
let resolveOld!: (value: Awaited<ReturnType<typeof getCalendarSources>>) => void
|
vi.mocked(listPickupCalendar).mockResolvedValueOnce({records: [{containerBookingId: '123',cabinetNo: 'D0001',containerNo: 'TEST-CONT',destinationPortName: 'Port',destinationWarehouseCode: 'US-W',fleetSupplierName: 'Fleet',pickupAppointmentAt: '2026-10-09T11:00:00',actualPickupAt: null}],truncated: false,unclassifiedCount: 1,scopeBasis: 'US_DESTINATION_WAREHOUSE',timeBasis: 'SOURCE_LOCAL_UNSPECIFIED'})
|
||||||
vi.mocked(getCalendarSources).mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve }))
|
const wrapper=render(); await flushPromises()
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
const panel=wrapper.findComponent({name:'AppointmentCalendarPanel'})
|
||||||
wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('range', { from: '2026-11-01', to: '2026-11-08' }); await flushPromises()
|
expect(panel.props('events')).toEqual([expect.objectContaining({type:'pickup',date:'2026-10-09',time:'11:00',sourcePath:'/container-loading/overseas/123'})])
|
||||||
resolveOld({ containers: [], emptyReturns: [], emptyReturnsReadable: false }); await flushPromises()
|
|
||||||
expect(wrapper.text()).not.toContain('缺少还柜读取权限')
|
|
||||||
expect(wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).props('events')).toHaveLength(0)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('retries an unknown save with the same payload and key, then only reloads reads', async () => {
|
|
||||||
vi.mocked(saveWarehouseArrival).mockRejectedValueOnce(new Error('network interrupted')).mockResolvedValueOnce({})
|
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
|
||||||
wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('edit', row); await flushPromises()
|
|
||||||
await wrapper.get('input[data-temporal-picker]').setValue('2026-10-22T09:30')
|
|
||||||
await wrapper.get('[data-save]').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('提交结果尚未确认')
|
|
||||||
expect(wrapper.get('input').attributes('disabled')).toBeDefined()
|
|
||||||
const guard = vi.mocked(onBeforeRouteLeave).mock.calls.at(-1)![0] as () => Promise<boolean>
|
|
||||||
expect(await guard()).toBe(false)
|
|
||||||
await wrapper.get('[data-save]').trigger('click'); await flushPromises()
|
|
||||||
expect(vi.mocked(saveWarehouseArrival).mock.calls[1]).toEqual(vi.mocked(saveWarehouseArrival).mock.calls[0])
|
|
||||||
expect(saveWarehouseArrival).toHaveBeenCalledWith('1', { estimatedWarehouseArrivalAt: '2026-10-22T09:30:00', expectedVersion: 0 }, expect.any(String))
|
|
||||||
expect(wrapper.find('[data-dialog]').exists()).toBe(false)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('requires an explicit reread after a conflict and retains the entered date', async () => {
|
|
||||||
vi.mocked(saveWarehouseArrival).mockRejectedValueOnce(new ApiResponseError('版本已变化', 'A0409', 409))
|
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
|
||||||
wrapper.getComponent({ name: 'AppointmentCalendarPanel' }).vm.$emit('edit', row); await flushPromises()
|
|
||||||
await wrapper.get('input').setValue('2026-10-22T09:30')
|
|
||||||
await wrapper.get('[data-save]').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.get('[data-save]').attributes('disabled')).toBeDefined()
|
|
||||||
vi.mocked(getWarehouseArrivals).mockResolvedValueOnce([{ ...warehouse, version: 2 }])
|
|
||||||
await wrapper.get('[data-retry]').trigger('click'); await flushPromises()
|
|
||||||
expect((wrapper.get('input').element as HTMLInputElement).value).toBe('2026-10-22T09:30')
|
|
||||||
await wrapper.get('[data-save]').trigger('click'); await flushPromises()
|
|
||||||
expect(saveWarehouseArrival).toHaveBeenLastCalledWith('1', expect.objectContaining({ expectedVersion: 2 }), expect.any(String))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps the selected date and view in the source return link', async () => {
|
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
|
||||||
const panel = wrapper.getComponent({ name: 'AppointmentCalendarPanel' })
|
|
||||||
panel.vm.$emit('select', '2026-10-21', 'week')
|
|
||||||
panel.vm.$emit('open', { ...row, sourcePath: '/container-loading/overseas/1' }); await flushPromises()
|
|
||||||
expect(routing.push).toHaveBeenCalledWith({ path: '/container-loading/overseas/1', query: { appointmentReturn: '/appointment-calendar?date=2026-10-21&mode=week' } })
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('opens the real dispatch detail with calendar context without requiring retired trip-list access', async () => {
|
|
||||||
routing.denied.add('platform:fleet:trip:list')
|
|
||||||
vi.mocked(listTripCalendar).mockResolvedValueOnce({ records: [dispatchEntry({ dispatchNo: 'DS/1', containerNumbers: [], plannedDepartureAt: '2026-10-21T16:00:00Z' })], unresolvedRecords: [] })
|
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
|
||||||
const panel = wrapper.getComponent({ name: 'AppointmentCalendarPanel' })
|
|
||||||
const event = panel.props('events').find((value: ScheduleEvent) => value.type === 'dispatch')
|
|
||||||
expect(listTripCalendar).toHaveBeenCalledOnce()
|
|
||||||
expect(event.sourcePath).toBe('/overseas-warehouse/dispatches/DS%2F1')
|
|
||||||
panel.vm.$emit('select', '2026-10-21', 'week')
|
|
||||||
panel.vm.$emit('open', event); await flushPromises()
|
|
||||||
expect(routing.push).toHaveBeenCalledWith({ path: '/overseas-warehouse/dispatches/DS%2F1', query: { appointmentReturn: '/appointment-calendar?date=2026-10-21&mode=week' } })
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('retains a complete dispatch with its container search fields while naming a different unresolved dispatch and its reason', async () => {
|
|
||||||
const good = dispatchEntry()
|
|
||||||
const unknown = dispatchEntry({ dispatchNo: 'PC-TIMEZONE-MISSING', containerNumbers: ['OTHER7654321'], originTimezone: null, incompleteReasons: ['ORIGIN_TIMEZONE_UNKNOWN'] })
|
|
||||||
vi.mocked(listTripCalendar).mockResolvedValueOnce({ records: [good, good, unknown], unresolvedRecords: [] })
|
|
||||||
const wrapper = renderSchedule(); await flushPromises()
|
|
||||||
const panel = wrapper.getComponent({ name: 'AppointmentCalendarPanel' })
|
|
||||||
const dispatches = (panel.props('events') as ScheduleEvent[]).filter(event => event.type === 'dispatch')
|
|
||||||
expect(dispatches).toHaveLength(1)
|
|
||||||
expect(dispatches[0]).toMatchObject({ key: 'dispatch-PC-CALENDAR-001', date: '2026-10-22', time: '09:00' })
|
|
||||||
expect(dispatches[0]!.fields).toContainEqual({ label: '关联柜号', value: 'TSTU1234567、TSTU7654321' })
|
|
||||||
expect(dispatches[0]!.fields).toContainEqual({ label: '计划出发(起运仓当地)', value: '2026-10-22 09:00' })
|
|
||||||
expect(panel.props('incomplete')).toBe(true)
|
expect(panel.props('incomplete')).toBe(true)
|
||||||
const notice = wrapper.get('.data-notice').text()
|
expect(wrapper.findComponent({ name: 'AppointmentCalendarPanel' }).props('notices').join(' ')).toContain('目的仓国家待核实')
|
||||||
expect(notice).toContain('1 条排车未能定位到日历日期')
|
expect(listPickupCalendar).toHaveBeenCalledTimes(1)
|
||||||
expect(notice).toContain('PC-TIMEZONE-MISSING:起运仓时区待核实')
|
|
||||||
expect(notice).toContain('无法确定当地日期')
|
|
||||||
expect(notice).not.toContain('PC-CALENDAR-001')
|
|
||||||
expect(dispatches.some(event => event.key === 'dispatch-PC-TIMEZONE-MISSING')).toBe(false)
|
|
||||||
expect(listTripCalendar).toHaveBeenCalledTimes(1)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
})
|
||||||
|
it('does not request pickup records without pickup list permission and discloses the omitted source', async () => {
|
||||||
|
routing.canPickup=false
|
||||||
|
const wrapper=render(); await flushPromises()
|
||||||
|
expect(listPickupCalendar).not.toHaveBeenCalled()
|
||||||
|
expect(wrapper.findComponent({ name: 'AppointmentCalendarPanel' }).props('notices').join(' ')).toContain('无提柜查看权限')
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCalendarPanel'}).props('incomplete')).toBe(true)
|
||||||
|
})
|
||||||
|
it('keeps successful arrival data visible when the pickup source fails', async () => {
|
||||||
|
vi.mocked(listPickupCalendar).mockRejectedValueOnce(new Error('pickup unavailable'))
|
||||||
|
vi.mocked(listArrivalCalendar).mockResolvedValueOnce([{containerBookingId:'1',cabinetNo:'D0001',arrivalAt:'2026-10-09T09:00:00',arrivalType:'ESTIMATED'}])
|
||||||
|
const wrapper=render(); await flushPromises()
|
||||||
|
const panel=wrapper.findComponent({name:'AppointmentCalendarPanel'})
|
||||||
|
expect(panel.props('events')).toEqual([expect.objectContaining({type:'arrival',key:'arrival-1'})])
|
||||||
|
expect(panel.props('incomplete')).toBe(true)
|
||||||
|
})
|
||||||
|
it('omits trip requests without trip list permission and keeps other sources usable', async () => {
|
||||||
|
routing.canTrips=false
|
||||||
|
const wrapper=render();await flushPromises()
|
||||||
|
expect(listTripCalendar).not.toHaveBeenCalled();expect(listArrivalCalendar).toHaveBeenCalledTimes(1)
|
||||||
|
expect(wrapper.findComponent({ name: 'AppointmentCalendarPanel' }).props('notices').join(' ')).toContain('无车次查看权限')
|
||||||
|
})
|
||||||
|
it('keeps unresolved trip origins outside daily slots and clearly labels their UTC source time', async () => {
|
||||||
|
vi.mocked(listTripCalendar).mockResolvedValueOnce({records:[],unresolvedRecords:[{sourceType:'TRIP_PLAN',tripNo:'TR-UNKNOWN',status:'PLANNED',originWarehouseId:null,originWarehouseCode:null,originWarehouseName:null,originCountryCode:null,originTimezone:null,originWarehouseStatus:null,plannedDepartureAt:'2026-10-10T12:00:00Z',expectedDriverEndAt:null,departedAt:null,completedAt:null,stops:[],incompleteReasons:['ORIGIN_WAREHOUSE_UNKNOWN']}]})
|
||||||
|
const wrapper=render();await flushPromises()
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCalendarPanel'}).props('events')).toEqual([])
|
||||||
|
expect(wrapper.findAll('.appointment-extra summary').map(node => node.text())).not.toContain('待核实地点的车次(1)')
|
||||||
|
expect(wrapper.text()).not.toContain('原计划时间保留 UTC')
|
||||||
|
await wrapper.findAll('button').find(button => button.text() === '查看待核实车次(1)')!.trigger('click')
|
||||||
|
expect(wrapper.text()).toContain('原计划时间保留 UTC')
|
||||||
|
expect(listTripCalendar).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
it('creates one shared appointment for two customers without sending a fabricated header customer', async () => {
|
||||||
|
const wrapper = render()
|
||||||
|
await flushPromises()
|
||||||
|
expect(listFbaAppointmentCalendar).toHaveBeenCalledTimes(1)
|
||||||
|
expect(listArrivalCalendar).toHaveBeenCalledTimes(1)
|
||||||
|
expect(listInboundOrders).not.toHaveBeenCalled()
|
||||||
|
await wrapper.get('[data-create]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('select[aria-label="预约仓库"]').setValue('ONT8')
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('[data-select]').trigger('click')
|
||||||
|
expect(wrapper.find('input[placeholder="填写仓库提供的预约编号"]').exists()).toBe(false)
|
||||||
|
await wrapper.get('[data-save]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(createFbaAppointment).toHaveBeenCalledTimes(1)
|
||||||
|
expect(createFbaAppointment).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
originWarehouseId: '100', fbaWarehouseCode: 'ONT8', lineIds: ['9007199254740993', '9007199254740994'], idempotencyKey: expect.any(String), details: expect.objectContaining({plannedDate: '2026-10-09', appointmentStatus: 'PENDING', appointmentAt: null, confirmationNo: null}),
|
||||||
|
}))
|
||||||
|
expect(vi.mocked(createFbaAppointment).mock.calls[0]![0]).not.toHaveProperty('customerId')
|
||||||
|
expect(listInboundOrders).toHaveBeenCalledTimes(1)
|
||||||
|
expect(listFbaAppointmentCalendar).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
it('only searches active FBA warehouses and loads cargo automatically after selection', async () => {
|
||||||
|
const wrapper = render()
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('[data-create]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(listPlatformWarehouses).toHaveBeenCalledWith(expect.objectContaining({ warehouseType: 'FBA', status: 'ACTIVE', size: 50 }))
|
||||||
|
expect(wrapper.find('input[placeholder="例如 ONT8"]').exists()).toBe(false)
|
||||||
|
expect(wrapper.text()).not.toContain('查询可预约货物')
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCancellationRecords'}).exists()).toBe(false)
|
||||||
|
await wrapper.get('select[aria-label="预约仓库"]').setValue('ONT8')
|
||||||
|
await flushPromises()
|
||||||
|
expect(listInboundOrders).toHaveBeenLastCalledWith({ page: 1, size: 10, fbaWarehouseCode: 'ONT8' })
|
||||||
|
})
|
||||||
|
it('keeps a pending unknown save retry on the same immutable command', async () => {
|
||||||
|
vi.mocked(createFbaAppointment).mockRejectedValueOnce(new Error('response lost'))
|
||||||
|
const wrapper = render(); await flushPromises()
|
||||||
|
await wrapper.get('[data-create]').trigger('click'); await flushPromises()
|
||||||
|
await wrapper.get('select[aria-label="预约仓库"]').setValue('ONT8'); await flushPromises()
|
||||||
|
await wrapper.get('[data-select]').trigger('click')
|
||||||
|
await wrapper.get('[data-save]').trigger('click'); await flushPromises()
|
||||||
|
const first = vi.mocked(createFbaAppointment).mock.calls[0]![0]
|
||||||
|
await wrapper.get('[data-close]').trigger('click')
|
||||||
|
expect(wrapper.find('[data-save]').exists()).toBe(true)
|
||||||
|
await wrapper.get('[data-create]').trigger('click')
|
||||||
|
expect((wrapper.get('select[aria-label="预约仓库"]').element as HTMLSelectElement).value).toBe('ONT8')
|
||||||
|
const done = vi.fn()
|
||||||
|
wrapper.findAllComponents({ name: 'AppDialog' }).at(-1)!.props('beforeClose')(done)
|
||||||
|
expect(done).not.toHaveBeenCalled()
|
||||||
|
for (const hook of [onBeforeRouteLeave, onBeforeRouteUpdate]) {
|
||||||
|
const guard = vi.mocked(hook).mock.calls.at(-1)![0] as () => boolean
|
||||||
|
expect(guard()).toBe(false)
|
||||||
|
}
|
||||||
|
await wrapper.get('[data-save]').trigger('click'); await flushPromises()
|
||||||
|
expect(vi.mocked(createFbaAppointment).mock.calls[1]![0]).toEqual(first)
|
||||||
|
expect(first.details.appointmentAt).toBeNull()
|
||||||
|
expect(first.details.confirmationNo).toBeNull()
|
||||||
|
expect(first.idempotencyKey).toBeTruthy()
|
||||||
|
})
|
||||||
|
it('keeps undated arrangements outside calendar time slots', async () => {
|
||||||
|
vi.mocked(listUnscheduledAppointments).mockResolvedValueOnce({ records: [{ id:'1', version:0, appointmentNo:'AP-UNSCHEDULED', originWarehouseId:'100', appointmentStatus:'PENDING', selectedCount:2, fbaWarehouseCode:'ONT8', items:[] }], total:1 })
|
||||||
|
const wrapper=render(); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('未定时安排(1)')
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCalendarPanel'}).props('events')).toEqual([])
|
||||||
|
expect(wrapper.findComponent({name:'DataTable'}).exists()).toBe(false)
|
||||||
|
await wrapper.get('[data-unscheduled]').trigger('click')
|
||||||
|
expect(wrapper.findComponent({name:'DataTable'}).props('data')[0]).not.toHaveProperty('appointmentAt')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('changing or clearing the warehouse clears prior cargo selection and blocks saving it', async () => {
|
||||||
|
const wrapper = render()
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('[data-create]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('select[aria-label="预约仓库"]').setValue('ONT8')
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('[data-select]').trigger('click')
|
||||||
|
expect(wrapper.find('input[placeholder="填写仓库提供的预约编号"]').exists()).toBe(false)
|
||||||
|
await wrapper.get('select[aria-label="预约仓库"]').setValue('')
|
||||||
|
await wrapper.get('[data-save]').trigger('click')
|
||||||
|
expect(createFbaAppointment).not.toHaveBeenCalled()
|
||||||
|
expect(listInboundOrders).toHaveBeenCalledTimes(1)
|
||||||
|
expect(wrapper.find('[data-select]').exists()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('discards cargo responses from the previously selected warehouse', async () => {
|
||||||
|
let resolveOld!: (value: Awaited<ReturnType<typeof listInboundOrders>>) => void
|
||||||
|
vi.mocked(listInboundOrders).mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve }))
|
||||||
|
const wrapper = render()
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('[data-create]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('select[aria-label="预约仓库"]').setValue('ONT8')
|
||||||
|
vi.mocked(listInboundOrders).mockResolvedValueOnce({ records: [], total: 0, page: 1, size: 10, pages: 0 })
|
||||||
|
await wrapper.get('select[aria-label="预约仓库"]').setValue('LAX9')
|
||||||
|
await flushPromises()
|
||||||
|
resolveOld({ records: candidates, total: 2, page: 1, size: 10, pages: 1 })
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.findComponent({ name: 'DataTable' }).props('data')).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('searches by keyword and exposes warehouse failures without accepting free text', async () => {
|
||||||
|
const wrapper = render()
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.get('[data-create]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
const select = wrapper.findAllComponents({ name: 'ElSelect' }).find(item => item.props('remoteMethod'))!
|
||||||
|
vi.mocked(listPlatformWarehouses).mockRejectedValueOnce(new Error('仓库暂不可用'))
|
||||||
|
await select.props('remoteMethod')(' LAX ')
|
||||||
|
await flushPromises()
|
||||||
|
expect(listPlatformWarehouses).toHaveBeenLastCalledWith(expect.objectContaining({ keyword: 'LAX', warehouseType: 'FBA', status: 'ACTIVE' }))
|
||||||
|
expect(wrapper.findComponent({ name: 'LoadErrorState' }).props('title')).toBe('仓库加载失败')
|
||||||
|
expect(wrapper.findAll('select[aria-label="预约仓库"] option')).toHaveLength(1)
|
||||||
|
expect(listInboundOrders).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps available arrivals and marks the result incomplete when appointments fail', async () => {
|
||||||
|
vi.mocked(listFbaAppointmentCalendar).mockRejectedValueOnce(new Error('预约暂不可用'))
|
||||||
|
vi.mocked(listArrivalCalendar).mockResolvedValueOnce([{ containerBookingId: '1', cabinetNo: 'D0001', arrivalAt: '2026-10-09T09:00:00', arrivalType: 'ESTIMATED' }])
|
||||||
|
const wrapper = render()
|
||||||
|
await flushPromises()
|
||||||
|
const calendar = wrapper.findComponent({ name: 'AppointmentCalendarPanel' })
|
||||||
|
expect(calendar.props('incomplete')).toBe(true)
|
||||||
|
expect(calendar.props('events')).toHaveLength(1)
|
||||||
|
expect(calendar.props('events')[0].type).toBe('arrival')
|
||||||
|
expect(wrapper.findComponent({ name: 'LoadErrorState' }).props('title')).toBe('送仓预约加载失败')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps delivery appointments when the arrival source fails', async () => {
|
||||||
|
vi.mocked(listArrivalCalendar).mockRejectedValueOnce(new Error('到港暂不可用'))
|
||||||
|
vi.mocked(listFbaAppointmentCalendar).mockResolvedValueOnce([{ version: 0, id: '1', appointmentNo: 'APT-AB', plannedDate: '2026-10-09', appointmentAt: null, originWarehouseId: '100', appointmentStatus: 'PENDING', selectedCount: 2, fbaWarehouseCode: 'ONT8', items: [] }])
|
||||||
|
const wrapper = render()
|
||||||
|
await flushPromises()
|
||||||
|
const calendar = wrapper.findComponent({ name: 'AppointmentCalendarPanel' })
|
||||||
|
expect(calendar.props('incomplete')).toBe(true)
|
||||||
|
expect(calendar.props('events')[0].key).toBe('APT-AB')
|
||||||
|
expect(wrapper.findComponent({ name: 'LoadErrorState' }).props('title')).toBe('船舶到港加载失败')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resolves an external booking deep link through the backend before opening followup', async () => {
|
||||||
|
routing.query = { sourceKey: 'BOOKING:B-1', customerId: 'A', destinationKey: 'FBA:ONT8' }
|
||||||
|
vi.mocked(resolvePlanningSource).mockResolvedValueOnce({ source: { sourceKey: 'BOOKING:B-1', customerId: 'A', orderId: null, inboundCode: null, bookingNo: 'B-1', containerNo: null, originWarehouseId: '100', originWarehouseName: '美国仓', destinationKey: 'FBA:ONT8', destinationWarehouseCode: 'ONT8', packages: null, sourceVersion: 'BOOKING:1', canFollowup: true, blockReasons: [] }, coverage: { status: 'SOURCE_NOT_MATERIALIZED', appointments: [], missingFields: ['REAL_CARGO_MATERIALS'], changeReviewRequired: false } })
|
||||||
|
const wrapper = render(); await flushPromises()
|
||||||
|
expect(resolvePlanningSource).toHaveBeenCalledWith(routing.query)
|
||||||
|
const dialog = wrapper.findComponent({ name: 'AppointmentFollowupDialog' })
|
||||||
|
expect(dialog.props('source').bookingNo).toBe('B-1')
|
||||||
|
expect(dialog.props('source').orderId).toBeNull()
|
||||||
|
expect(dialog.props('coverage').status).toBe('SOURCE_NOT_MATERIALIZED')
|
||||||
|
expect(createFbaAppointment).not.toHaveBeenCalled(); expect(saveFollowup).not.toHaveBeenCalled()
|
||||||
|
expect(dialog.props('canArrange')).toBe(true)
|
||||||
|
dialog.vm.$emit('arrange');await flushPromises()
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentFollowupDialog'}).exists()).toBe(false)
|
||||||
|
expect(wrapper.findComponent({name:'AppointmentCargoPanel'}).props('externalSource')).toMatchObject({sourceKey:'BOOKING:B-1',bookingNo:'B-1',orderId:null})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not trust stale destination query data or open followup after a source error', async () => {
|
||||||
|
routing.query = { sourceKey: 'BOOKING:B-1', customerId: 'A', destinationKey: 'FBA:OLD' }
|
||||||
|
vi.mocked(resolvePlanningSource).mockRejectedValueOnce(new Error('目的地已变化'))
|
||||||
|
const wrapper = render(); await flushPromises()
|
||||||
|
expect(wrapper.findComponent({ name: 'AppointmentFollowupDialog' }).exists()).toBe(false)
|
||||||
|
expect(wrapper.findComponent({ name: 'LoadErrorState' }).props('title')).toBe('预约货源核对失败')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not request deep-link cargo without the underlying source permission', async () => {
|
||||||
|
routing.query = { sourceKey: 'BOOKING:B-1', customerId: 'A', destinationKey: 'FBA:ONT8' }; routing.canSourceRead = false
|
||||||
|
const wrapper = render(); await flushPromises()
|
||||||
|
expect(resolvePlanningSource).not.toHaveBeenCalled()
|
||||||
|
expect(wrapper.findComponent({ name: 'AppointmentFollowupDialog' }).exists()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,209 +1,485 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import InlineHelp from '@/shared/components/InlineHelp.vue'
|
|
||||||
import '@/styles/adminDensity.css'
|
import '@/styles/adminDensity.css'
|
||||||
import { computed, defineAsyncComponent, onActivated, onDeactivated, onBeforeUnmount, onMounted, provide, ref, watch } from 'vue'
|
import { computed, provide, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||||
import { onBeforeRouteLeave, onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router'
|
import { onBeforeRouteLeave, onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router'
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
import { resolvePlanningSource, listUnscheduledAppointments, type ResolvedPlanningSource, type PlanningSource } from './planningApi'
|
||||||
import { isAxiosError } from 'axios'
|
import AppointmentFollowupDialog from './AppointmentFollowupDialog.vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
|
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
||||||
import AdminPage from '@/shared/components/AdminPage.vue'
|
import AdminPage from '@/shared/components/AdminPage.vue'
|
||||||
import AppDialog from '@/shared/components/AppDialog.vue'
|
import AppDialog from '@/shared/components/AppDialog.vue'
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||||
import { ApiResponseError, getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||||
import AppointmentCalendarPanel from './AppointmentCalendarPanel.vue'
|
import {
|
||||||
import { calendarRange, dateKey, type CalendarMode } from './calendar'
|
createFbaAppointment, getFbaAppointment, listFbaAppointmentCalendar, listInboundOrders, updateFbaAppointment,
|
||||||
import { getCalendarSources, getWarehouseArrivals, saveWarehouseArrival, type CalendarSources, type ScheduleRange, type WarehouseArrival, type WarehouseArrivalChange } from './scheduleApi'
|
overseasWarehousePermissions as permission,
|
||||||
import { projectContainerSchedule, type ScheduleEvent } from './schedule'
|
FbaAppointmentFields, createAppointmentForm, appointmentPayload, appointmentFormError,
|
||||||
import { listTripCalendar, projectTripCalendar, tripIssues } from './tripCalendar'
|
type FbaAppointmentDto, type FbaAppointmentDetailsPayload, type InboundOrderSummaryDto,
|
||||||
import { rejectedCommand, type LeaveGuard } from './useWorkDraft'
|
} from '@/modules/overseas-warehouse'
|
||||||
import type { PlanningSourceLookup } from './planningApi'
|
import { listPlatformWarehouses, type PlatformWarehouseSummaryResource } from '@/modules/warehouses'
|
||||||
import type { WorkAction } from './workApi'
|
import AppointmentCalendarPanel, { type CalendarEvent } from './AppointmentCalendarPanel.vue'
|
||||||
import { appointmentExternalTarget } from './workNavigation'
|
import AppointmentInboundCodes from './AppointmentInboundCodes.vue'
|
||||||
|
import AppointmentCancellationDialog from './AppointmentCancellationDialog.vue'
|
||||||
|
import AppointmentCancellationHistory from './AppointmentCancellationHistory.vue'
|
||||||
|
import AppointmentCancellationRecords from './AppointmentCancellationRecords.vue'
|
||||||
|
import AppointmentCargoPanel from './AppointmentCargoPanel.vue'
|
||||||
|
import AppointmentContainerPanel from './AppointmentContainerPanel.vue'
|
||||||
|
import { calendarRange, dateKey } from './calendar'
|
||||||
|
import { listArrivalCalendar, listPickupCalendar, type ArrivalCalendarEntry, type PickupCalendarEntry } from './api'
|
||||||
|
import { listTripCalendar, projectTripCalendar, tripIssues, type TripCalendarEntry } from './tripCalendar'
|
||||||
|
|
||||||
// 原业务页面仍能直接进入其预约表单;日历不再提供工作清单或流程编排入口。
|
const cancellationTarget = ref<FbaAppointmentDto | null>(null)
|
||||||
const WorkDetailPanel = defineAsyncComponent(() => import('./WorkDetailPanel.vue'))
|
const unscheduledOpen = ref(false)
|
||||||
const SourceAppointmentPanel = defineAsyncComponent(() => import('./SourceAppointmentPanel.vue'))
|
const cancellationsOpen = ref(false), cancellationsRevision = ref(0), cancellationHistoryOpen = ref(false), forceReadOnly = ref(false)
|
||||||
const AppointmentCreatePanel = defineAsyncComponent(() => import('./AppointmentCreatePanel.vue'))
|
const appointmentReadOnly = computed(() => forceReadOnly.value || editing.value?.appointmentStatus === 'CANCELLED' || !access.can(permission.inboundOrderAppointment))
|
||||||
const route = useRoute(), router = useRouter(), access = useAccessPreviewStore()
|
const access = useAccessPreviewStore()
|
||||||
const creating = ref(false)
|
const route = useRoute()
|
||||||
const canCreate = computed(() => access.can('platform:overseas-warehouse:inbound-order:fba-appointment') && access.can('platform:overseas-warehouse:last-mile-order:list'))
|
const router = useRouter()
|
||||||
function initialDate() {
|
const linkedSource = ref<ResolvedPlanningSource | null>(null)
|
||||||
const value = typeof route.query.date === 'string' ? route.query.date : ''
|
const selectedSource = ref<PlanningSource | null>(null)
|
||||||
try { calendarRange(value, 'month'); return value } catch { return dateKey(new Date()) }
|
const linkError = ref<ApiErrorDetails | null>(null)
|
||||||
|
const linkLoading = ref(false)
|
||||||
|
let linkRequest = 0
|
||||||
|
const childLeaveGuards = new Set<() => boolean>()
|
||||||
|
provide('appointment-register-leave-guard', (guard: () => boolean) => {
|
||||||
|
childLeaveGuards.add(guard)
|
||||||
|
return () => { childLeaveGuards.delete(guard) }
|
||||||
|
})
|
||||||
|
function switchWorkView(next: 'calendar' | 'cargo' | 'containers') {
|
||||||
|
if (canLeave()) workView.value = next
|
||||||
}
|
}
|
||||||
const selectedDate = ref(initialDate()), mode = ref<CalendarMode>(route.query.mode === 'week' ? 'week' : 'month')
|
const workView = ref<'calendar' | 'cargo' | 'containers'>('calendar')
|
||||||
const range = ref<ScheduleRange>(calendarRange(selectedDate.value, mode.value))
|
const calendarVisited = ref(true)
|
||||||
const sources = ref<CalendarSources | null>(null), warehouses = ref<WarehouseArrival[] | null>(null), trips = ref<ScheduleEvent[]>([])
|
const showTripLayer = ref(false)
|
||||||
const errors = ref<Array<{ title: string; details: ApiErrorDetails }>>([]), notices = ref<string[]>([]), loading = ref(false), active = ref(true)
|
const cargoVisited = ref(false)
|
||||||
const incomplete = computed(() => !!errors.value.length || !!notices.value.length)
|
watch(workView, value => {
|
||||||
const events = computed(() => [...projectContainerSchedule(sources.value || { containers: [], emptyReturns: [], emptyReturnsReadable: true },
|
if (value === 'cargo') cargoVisited.value = true
|
||||||
warehouses.value, range.value, access.can('platform:firstleg:terminal-drayage:list')), ...trips.value])
|
if (value === 'calendar' && !calendarVisited.value) { calendarVisited.value = true; void load(); void loadUnscheduled() }
|
||||||
let generation = 0, controller: AbortController | null = null
|
})
|
||||||
async function load(next = range.value) {
|
const appointments = ref<FbaAppointmentDto[]>([])
|
||||||
range.value = next
|
const arrivals = ref<ArrivalCalendarEntry[]>([])
|
||||||
const request = ++generation; controller?.abort(); controller = new AbortController()
|
const pickups = ref<PickupCalendarEntry[]>([])
|
||||||
const signal = controller.signal
|
const pickupNotice = ref('')
|
||||||
loading.value = true; sources.value = null; warehouses.value = null; trips.value = []; errors.value = []; notices.value = []
|
const tripEvents = ref<CalendarEvent[]>([])
|
||||||
const fail = (title: string, cause: unknown) => { if (request === generation) errors.value.push({ title, details: getApiErrorDetails(cause, title) }) }
|
const unresolvedTrips = ref<TripCalendarEntry[]>([])
|
||||||
await Promise.allSettled([
|
const tripNotice = ref('')
|
||||||
(async () => {
|
const unresolvedDialogOpen = ref(false)
|
||||||
let result: CalendarSources | null = null
|
const unresolvedPage = ref(1), unresolvedSize = ref(10)
|
||||||
try {
|
const unresolvedRows = computed(() => unresolvedTrips.value.slice((unresolvedPage.value - 1) * unresolvedSize.value, unresolvedPage.value * unresolvedSize.value))
|
||||||
result = await getCalendarSources(next, signal)
|
const unresolvedColumns: DataTableColumn[] = [
|
||||||
if (request !== generation) return
|
{ key: 'actions', label: '操作', slotName: 'actions', width: 110, fixed: 'left' },
|
||||||
sources.value = result
|
{ prop: 'tripNo', label: '车次号', minWidth: 210 },
|
||||||
if (!result.emptyReturnsReadable) notices.value.push('缺少还柜读取权限,当前未显示还柜安排。')
|
{ prop: 'originWarehouseName', label: '起运仓', minWidth: 170 },
|
||||||
} catch (cause) { fail('到港与还柜读取失败', cause) }
|
{ prop: 'plannedDepartureAt', label: '原计划出发(UTC)', minWidth: 225 },
|
||||||
if (request !== generation) return
|
{ key: 'issues', label: '待核实资料', slotName: 'issues', minWidth: 230 },
|
||||||
if (!access.can('platform:overseas-warehouse:last-mile-order:list')) {
|
]
|
||||||
notices.value.push('缺少尾程订单读取权限,当前未显示计划到仓。'); return
|
const range = ref(calendarRange(dateKey(new Date()), 'month'))
|
||||||
}
|
const loading = ref(false)
|
||||||
try {
|
const loadError = ref<ApiErrorDetails | null>(null)
|
||||||
const rows = await getWarehouseArrivals(next, [...new Set(result?.containers.map(row => row.containerBookingId) || [])], signal)
|
const sourceErrors = ref<Array<{ title: string; details: ApiErrorDetails }>>([])
|
||||||
if (request === generation) warehouses.value = rows
|
const errorTitle = ref('预约日历加载失败')
|
||||||
} catch (cause) { fail('计划到仓读取失败', cause) }
|
const dialogError = ref<ApiErrorDetails | null>(null)
|
||||||
})(),
|
const dialogOpen = ref(false)
|
||||||
(async () => {
|
const saving = ref(false)
|
||||||
if (!access.can('platform:overseas-warehouse:dispatch:list')) { notices.value.push('缺少排车读取权限,当前未显示排车安排。'); return }
|
const detailLoading = ref(false)
|
||||||
try {
|
const detailReady = ref(false)
|
||||||
const result = projectTripCalendar(await listTripCalendar(next, signal), next)
|
const editing = ref<FbaAppointmentDto | null>(null)
|
||||||
if (request !== generation) return
|
const warehouse = ref('')
|
||||||
trips.value = result.events
|
const warehouseOptions = ref<PlatformWarehouseSummaryResource[]>([])
|
||||||
if (result.unresolved.length) {
|
const warehouseLoading = ref(false)
|
||||||
const details = result.unresolved.slice(0, 3).map(row => `${row.dispatchNo?.trim() || '排车单号缺失'}:${tripIssues(row) || '资料待核实'}`).join(';')
|
const warehouseError = ref<ApiErrorDetails | null>(null)
|
||||||
notices.value.push(`${result.unresolved.length} 条排车未能定位到日历日期(${details}${result.unresolved.length > 3 ? ';其余请到排车列表核对' : ''})。`)
|
const warehouseKeyword = ref('')
|
||||||
}
|
const warehouseTotal = ref(0)
|
||||||
} catch (cause) { fail('排车读取失败', cause) }
|
let warehouseRequest = 0
|
||||||
})(),
|
const candidates = ref<InboundOrderSummaryDto[]>([])
|
||||||
])
|
const selected = ref<InboundOrderSummaryDto[]>([])
|
||||||
if (request === generation) loading.value = false
|
const candidateLoading = ref(false)
|
||||||
|
const candidateError = ref<ApiErrorDetails | null>(null)
|
||||||
|
const candidatePage = ref(1)
|
||||||
|
const candidateSize = ref(10)
|
||||||
|
const candidateTotal = ref(0)
|
||||||
|
const searchedWarehouse = ref('')
|
||||||
|
const selectionEpoch = ref(0)
|
||||||
|
let calendarController: AbortController | undefined
|
||||||
|
let calendarRequest = 0
|
||||||
|
let candidateRequest = 0
|
||||||
|
let detailRequest = 0
|
||||||
|
const form = reactive(createAppointmentForm())
|
||||||
|
const pendingSave = ref<{ appointmentNo: string | null; version: number; originWarehouseId: string; fbaWarehouseCode: string; lineIds: string[]; details: FbaAppointmentDetailsPayload; idempotencyKey: string } | null>(null)
|
||||||
|
const unscheduled = ref<FbaAppointmentDto[]>([]), unscheduledTotal = ref(0), unscheduledPage = ref(1), unscheduledSize = ref(10)
|
||||||
|
const unscheduledError = ref<ApiErrorDetails | null>(null)
|
||||||
|
const unscheduledColumns: DataTableColumn[] = [{key:'actions',label:'操作',slotName:'actions',width:100,fixed:'left'},{prop:'appointmentNo',label:'系统预约单号',minWidth:200},{prop:'fbaWarehouseCode',label:'目的仓',width:100},{prop:'selectedCount',label:'票数',width:80}]
|
||||||
|
let unscheduledRequest = 0
|
||||||
|
async function loadUnscheduled() {
|
||||||
|
const current = ++unscheduledRequest; unscheduledError.value = null
|
||||||
|
try { const result = await listUnscheduledAppointments(unscheduledPage.value, unscheduledSize.value); if(current === unscheduledRequest) {unscheduled.value = result.records; unscheduledTotal.value = result.total} }
|
||||||
|
catch(cause) {if(current === unscheduledRequest) unscheduledError.value = getApiErrorDetails(cause, '未定时安排加载失败')}
|
||||||
}
|
}
|
||||||
function select(date: string, nextMode: CalendarMode) { selectedDate.value = date; mode.value = nextMode }
|
const statusLabels: Record<string, string> = { PENDING: '安排待确认', SUCCESS: '对方已确认', FAILED: '未约成', CANCELLED: '已取消' }
|
||||||
async function openSource(event: ScheduleEvent) {
|
const columns: DataTableColumn[] = [
|
||||||
if (!event.sourcePath || !await canLeave()) return
|
{ key: 'selection', type: 'selection', reserveSelection: true, width: 46, selectable: (row: InboundOrderSummaryDto) => row.fbaWarehouseCode === searchedWarehouse.value && (!row.appointmentStatus || ['FAILED', 'CANCELLED'].includes(row.appointmentStatus)) },
|
||||||
const context = { date: selectedDate.value, mode: mode.value }
|
{ prop: 'inboundCode', label: '入仓码', minWidth: 220, singleLine: false, showOverflowTooltip: false },
|
||||||
await router.replace({ query: context })
|
{ prop: 'customerName', label: '客户', slotName: 'customer', minWidth: 180, singleLine: false, showOverflowTooltip: false },
|
||||||
await router.push(appointmentExternalTarget(event.sourcePath, context))
|
{ prop: 'fbaWarehouseCode', label: '目的仓', width: 110 },
|
||||||
}
|
{ prop: 'overseasWarehouseName', label: '海外仓', minWidth: 150, singleLine: false, showOverflowTooltip: false },
|
||||||
const editor = ref<ScheduleEvent | null>(null), plannedAt = ref(''), originalAt = ref(''), saving = ref(false)
|
{ prop: 'packageCount', label: '箱数', width: 80 },
|
||||||
const saveError = ref<ApiErrorDetails | null>(null), unknownResult = ref(false), conflict = ref(false)
|
{ prop: 'palletCount', label: '托数', width: 80 },
|
||||||
let pending: { id: string; body: WarehouseArrivalChange; key: string } | null = null
|
{ prop: 'appointmentNo', label: '已有预约号', minWidth: 160, singleLine: false, showOverflowTooltip: false },
|
||||||
function edit(event: ScheduleEvent) {
|
]
|
||||||
if (!event.canEdit || !event.warehouse) return
|
const events = computed<CalendarEvent[]>(() => [...arrivals.value.map(arrival => ({
|
||||||
editor.value = event; plannedAt.value = event.warehouse.plannedAt?.slice(0, 16) || ''; originalAt.value = plannedAt.value
|
key: `arrival-${arrival.containerBookingId}`, type: 'arrival' as const,
|
||||||
pending = null; saveError.value = null; unknownResult.value = false; conflict.value = false
|
date: arrival.arrivalAt.slice(0, 10), time: arrival.arrivalAt.slice(11, 16),
|
||||||
}
|
title: `${arrival.voyageNo || arrival.cabinetNo} ${arrival.arrivalType === 'ACTUAL' ? '实际到港' : '预计到港'}`,
|
||||||
async function save() {
|
fields: [
|
||||||
const row = editor.value?.warehouse
|
{ label: '船名 / 航次', value: [arrival.vesselName, arrival.voyageNo].filter(Boolean).join(' / ') },
|
||||||
if (!row || saving.value || conflict.value || !plannedAt.value) return
|
{ label: '目的港', value: arrival.destinationPortName },
|
||||||
pending ||= { id: row.sourceContainerBookingId, body: { estimatedWarehouseArrivalAt: `${plannedAt.value}:00`, expectedVersion: row.version },
|
{ label: '已装货柜号', value: arrival.containerNo },
|
||||||
key: `calendar-arrival-${crypto.randomUUID()}` }
|
{ label: '柜次号', value: arrival.cabinetNo },
|
||||||
saving.value = true; saveError.value = null
|
{ label: '货物去向', value: arrival.destinationWarehouseCode },
|
||||||
|
],
|
||||||
|
})), ...pickups.value.map(pickup => ({
|
||||||
|
key: `pickup-${pickup.containerBookingId}`, type: 'pickup' as const,
|
||||||
|
date: pickup.pickupAppointmentAt.slice(0, 10), time: pickup.pickupAppointmentAt.slice(11, 16),
|
||||||
|
title: `${pickup.containerNo || pickup.cabinetNo || '未关联柜号'} 预约提柜`,
|
||||||
|
sourcePath: `/container-loading/overseas/${encodeURIComponent(pickup.containerBookingId)}`,
|
||||||
|
subtitle: '美国目的仓相关提柜安排',
|
||||||
|
fields: [
|
||||||
|
{ label: '柜次号', value: pickup.cabinetNo }, { label: '目的港', value: pickup.destinationPortName },
|
||||||
|
{ label: '目的仓', value: pickup.destinationWarehouseCode }, { label: '车队', value: pickup.fleetSupplierName },
|
||||||
|
{ label: '实际提柜', value: pickup.actualPickupAt || '尚未记录' },
|
||||||
|
{ label: '时间口径', value: '原提柜业务时间,港口时区待核实' },
|
||||||
|
],
|
||||||
|
})), ...appointments.value.map(appointment => ({
|
||||||
|
key: appointment.appointmentNo, type: 'delivery' as const, date: (appointment.appointmentAt || appointment.plannedAt || appointment.plannedDate || '').slice(0, 10),
|
||||||
|
endAt: (appointment.appointmentAt ? appointment.appointmentEndAt : appointment.plannedEndAt) || undefined,
|
||||||
|
time: (appointment.appointmentAt || appointment.plannedAt || '').slice(11, 16) + ((appointment.appointmentAt ? appointment.appointmentEndAt : appointment.plannedEndAt) ? `–${(appointment.appointmentAt ? appointment.appointmentEndAt : appointment.plannedEndAt)!.slice(11, 16)}` : ''), title: `${appointment.fbaWarehouseCode} ${appointment.appointmentStatus === 'SUCCESS' ? '已确认送仓' : '计划送仓'}`,
|
||||||
|
fields: [
|
||||||
|
{ label: '预约仓库', value: appointment.fbaWarehouseCode },
|
||||||
|
{ label: '系统单号', value: appointment.appointmentNo },
|
||||||
|
{ label: '外部约号', value: appointment.confirmationNo },
|
||||||
|
{ label: '地点时区', value: appointment.timezone || '待核实' },
|
||||||
|
{ label: '完整时段', value: `${appointment.appointmentAt || appointment.plannedAt || appointment.plannedDate || '待定'}${(appointment.appointmentAt ? appointment.appointmentEndAt : appointment.plannedEndAt) ? ` — ${appointment.appointmentAt ? appointment.appointmentEndAt : appointment.plannedEndAt}` : ''}` },
|
||||||
|
{ label: '预约状态', value: statusLabels[appointment.appointmentStatus] || '—' },
|
||||||
|
{ label: '货物信息', value: `${appointment.selectedCount} 票 / ${new Set(appointment.items.map(item => item.customerId)).size} 个客户` },
|
||||||
|
{ label: '预约备注', value: appointment.appointmentRemark },
|
||||||
|
].filter(field => field.value != null && field.value !== ''),
|
||||||
|
inboundCodes: appointment.items.map(item => item.inboundCode),
|
||||||
|
canEdit: access.can(permission.inboundOrderAppointment),
|
||||||
|
canView: access.can('platform:appointment:list'),
|
||||||
|
canDelete: access.can('platform:appointment:delete'),
|
||||||
|
})), ...tripEvents.value])
|
||||||
|
|
||||||
|
async function load(nextRange = range.value) {
|
||||||
|
unresolvedDialogOpen.value = false
|
||||||
|
range.value = nextRange
|
||||||
|
const request = ++calendarRequest
|
||||||
|
calendarController?.abort()
|
||||||
|
calendarController = new AbortController()
|
||||||
|
loading.value = true
|
||||||
|
loadError.value = null
|
||||||
|
sourceErrors.value = []
|
||||||
|
errorTitle.value = '预约日历加载失败'
|
||||||
|
appointments.value = []
|
||||||
|
arrivals.value = []
|
||||||
|
pickups.value = []
|
||||||
|
tripEvents.value = []; unresolvedTrips.value = []; unresolvedPage.value = 1
|
||||||
|
const canReadPickup = access.can('platform:firstleg:terminal-drayage:list')
|
||||||
|
const canReadTrips = access.can('platform:fleet:trip:list')
|
||||||
|
pickupNotice.value = canReadPickup ? '' : '无提柜查看权限,当前日历不包含提柜预约。'
|
||||||
|
tripNotice.value = canReadTrips ? '' : '无车次查看权限,当前日历不包含用车计划。'
|
||||||
try {
|
try {
|
||||||
await saveWarehouseArrival(pending.id, pending.body, pending.key)
|
const [result, arrivalResult, pickupResult, tripResult] = await Promise.allSettled([
|
||||||
pending = null; unknownResult.value = false; editor.value = null
|
listFbaAppointmentCalendar(nextRange, calendarController.signal),
|
||||||
ElMessage.success('计划到仓已保存')
|
listArrivalCalendar(nextRange, calendarController.signal),
|
||||||
await load()
|
canReadPickup ? listPickupCalendar(nextRange, calendarController.signal) : Promise.resolve(null),
|
||||||
} catch (cause) {
|
canReadTrips ? listTripCalendar(nextRange, calendarController.signal) : Promise.resolve(null),
|
||||||
saveError.value = getApiErrorDetails(cause, '计划到仓保存失败')
|
])
|
||||||
unknownResult.value = !rejectedCommand(cause)
|
if (request !== calendarRequest) return
|
||||||
const status = cause instanceof ApiResponseError ? cause.status : isAxiosError(cause) ? cause.response?.status : undefined
|
if (result.status === 'fulfilled') appointments.value = result.value
|
||||||
conflict.value = status === 409 || /409$/.test(saveError.value.code || '')
|
else sourceErrors.value.push({ title: '送仓预约加载失败', details: getApiErrorDetails(result.reason, '送仓预约加载失败') })
|
||||||
if (!unknownResult.value) pending = null
|
if (arrivalResult.status === 'fulfilled') arrivals.value = arrivalResult.value
|
||||||
} finally { saving.value = false }
|
else sourceErrors.value.push({ title: '船舶到港加载失败', details: getApiErrorDetails(arrivalResult.reason, '船舶到港加载失败') })
|
||||||
|
if (pickupResult.status === 'fulfilled' && pickupResult.value) {
|
||||||
|
pickups.value = pickupResult.value.records
|
||||||
|
pickupNotice.value = [pickupResult.value.truncated ? '提柜安排超出读取上限,请缩小日期范围。' : '', Number(pickupResult.value.unclassifiedCount) > 0 ? `有 ${Number(pickupResult.value.unclassifiedCount)} 条提柜记录的目的仓国家待核实,请完善仓库资料后重新核对;这些记录未计入当前范围。` : ''].filter(Boolean).join(' ')
|
||||||
|
} else if (pickupResult.status === 'rejected') sourceErrors.value.push({ title: '提柜预约加载失败', details: getApiErrorDetails(pickupResult.reason, '提柜预约加载失败') })
|
||||||
|
if (tripResult.status === 'fulfilled' && tripResult.value) {
|
||||||
|
const projection = projectTripCalendar(tripResult.value, nextRange)
|
||||||
|
tripEvents.value = projection.events; unresolvedTrips.value = projection.unresolved
|
||||||
|
if (projection.unresolved.length) tripNotice.value = '部分车次无法确定起运地点或当地日期,已单列待核实,未计入每日安排。'
|
||||||
|
} else if (tripResult.status === 'rejected') sourceErrors.value.push({ title: '用车计划加载失败', details: getApiErrorDetails(tripResult.reason, '用车计划加载失败') })
|
||||||
|
} catch (error) {
|
||||||
|
if (request === calendarRequest) loadError.value = getApiErrorDetails(error, '预约日历加载失败')
|
||||||
|
} finally { if (request === calendarRequest) loading.value = false }
|
||||||
}
|
}
|
||||||
async function rereadEditor() {
|
|
||||||
const row = editor.value?.warehouse
|
function openSource(event: CalendarEvent) {
|
||||||
if (!row) return
|
if (event.sourcePath) void router.push(event.sourcePath)
|
||||||
saving.value = true
|
|
||||||
try {
|
|
||||||
const rows = await getWarehouseArrivals(range.value, [row.sourceContainerBookingId])
|
|
||||||
const latest = rows.find(value => value.sourceContainerBookingId === row.sourceContainerBookingId)
|
|
||||||
if (!latest?.canEdit) { saveError.value = { message: '该柜已不能调整计划到仓,请关闭并查看最新货柜记录。' }; return }
|
|
||||||
editor.value = { ...editor.value!, warehouse: latest }; conflict.value = false; saveError.value = null
|
|
||||||
} catch (cause) { saveError.value = getApiErrorDetails(cause, '最新计划读取失败') }
|
|
||||||
finally { saving.value = false }
|
|
||||||
}
|
}
|
||||||
const guards = new Set<LeaveGuard>()
|
|
||||||
provide('appointment-work-leave-guard', (guard: LeaveGuard) => { guards.add(guard); return () => guards.delete(guard) })
|
function canLeave() {
|
||||||
async function canLeave() {
|
if (saving.value || pendingSave.value) { ElMessage.warning('请先核实本次保存结果,再关闭或切换'); return false }
|
||||||
if (saving.value || unknownResult.value) return false
|
return [...childLeaveGuards].every(guard => guard())
|
||||||
for (const guard of guards) if (!await guard()) return false
|
|
||||||
if (editor.value && plannedAt.value !== originalAt.value) {
|
|
||||||
try { await ElMessageBox.confirm('计划到仓尚未保存,确定放弃本次修改?', '未保存修改', { type: 'warning', customClass: 'admin-density-confirm admin-workbench is-dialog' }) }
|
|
||||||
catch { return false }
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
async function closeEditor(done: () => void) { if (await canLeave()) { done(); editor.value = null } }
|
function beforeCloseAppointment(done: () => void) { if (canLeave()) done() }
|
||||||
async function openCreate() { if (canCreate.value && await canLeave()) creating.value = true }
|
function closeAppointment() { if (canLeave()) dialogOpen.value = false }
|
||||||
async function closeCreate(done: () => void) { if (await canLeave()) { done(); creating.value = false } }
|
|
||||||
onBeforeRouteLeave(canLeave)
|
onBeforeRouteLeave(canLeave)
|
||||||
onBeforeRouteUpdate(canLeave)
|
onBeforeRouteUpdate(canLeave)
|
||||||
|
function openCreate(date: string) {
|
||||||
|
if (!access.can(permission.inboundOrderAppointment) || !canLeave()) return
|
||||||
|
forceReadOnly.value = false; cancellationHistoryOpen.value = false
|
||||||
|
++candidateRequest
|
||||||
|
++detailRequest
|
||||||
|
detailLoading.value = false
|
||||||
|
candidateLoading.value = false
|
||||||
|
candidatePage.value = 1
|
||||||
|
editing.value = null
|
||||||
|
warehouse.value = ''
|
||||||
|
searchedWarehouse.value = ''
|
||||||
|
candidates.value = []
|
||||||
|
selected.value = []
|
||||||
|
selectionEpoch.value++
|
||||||
|
candidateTotal.value = 0
|
||||||
|
candidateError.value = null
|
||||||
|
dialogError.value = null
|
||||||
|
Object.assign(form, createAppointmentForm(), { plannedDate: date }); pendingSave.value = null
|
||||||
|
dialogOpen.value = true
|
||||||
|
detailReady.value = true
|
||||||
|
void searchWarehouses('')
|
||||||
|
}
|
||||||
|
|
||||||
// 仅承接原业务仍在使用的精确来源/事项深链,不恢复旧全局待办、分页和筛选协议。
|
async function openEdit(event: Pick<CalendarEvent, 'key'>, readOnly = false) {
|
||||||
const workKey = ref(''), origins = ref<string[]>([]), sourceLink = ref<PlanningSourceLookup | null>(null), initialAction = ref<WorkAction | null>(null)
|
if (!canLeave()) return
|
||||||
watch(() => [route.query.workItem, route.query.sourceKey, route.query.orderId, route.query.customerId, route.query.destinationKey], () => {
|
forceReadOnly.value = readOnly; cancellationHistoryOpen.value = false
|
||||||
workKey.value = typeof route.query.workItem === 'string' ? route.query.workItem : ''
|
const request = ++detailRequest
|
||||||
const customerId = typeof route.query.customerId === 'string' ? route.query.customerId : ''
|
dialogError.value = null
|
||||||
const destinationKey = typeof route.query.destinationKey === 'string' ? route.query.destinationKey : undefined
|
editing.value = [...appointments.value, ...unscheduled.value].find(item => item.appointmentNo === event.key) || null
|
||||||
sourceLink.value = customerId && typeof route.query.sourceKey === 'string' ? { customerId, sourceKey: route.query.sourceKey, destinationKey }
|
pendingSave.value = null
|
||||||
: customerId && typeof route.query.orderId === 'string' ? { customerId, orderId: route.query.orderId, destinationKey } : null
|
dialogOpen.value = true
|
||||||
origins.value = []
|
detailLoading.value = true
|
||||||
initialAction.value = null
|
detailReady.value = false
|
||||||
}, { immediate: true })
|
try {
|
||||||
async function openWork(key: string, action?: WorkAction) {
|
const detail = await getFbaAppointment(event.key)
|
||||||
if (await canLeave()) { if (workKey.value) origins.value.push(workKey.value); workKey.value = key; initialAction.value = action || null }
|
if (request !== detailRequest || !dialogOpen.value) return
|
||||||
|
editing.value = detail
|
||||||
|
detailReady.value = true
|
||||||
|
warehouse.value = detail.fbaWarehouseCode
|
||||||
|
Object.assign(form, createAppointmentForm(detail))
|
||||||
|
} catch (error) {
|
||||||
|
if (request === detailRequest) dialogError.value = getApiErrorDetails(error, '预约详情加载失败')
|
||||||
|
} finally { if (request === detailRequest) detailLoading.value = false }
|
||||||
}
|
}
|
||||||
async function backWork() { if (await canLeave()) { workKey.value = origins.value.pop() || ''; initialAction.value = null } }
|
|
||||||
async function closeBusiness(done: () => void) {
|
async function searchWarehouses(keyword: string) {
|
||||||
if (!await canLeave()) return
|
warehouseKeyword.value = keyword
|
||||||
done(); workKey.value = ''; sourceLink.value = null; origins.value = []
|
const request = ++warehouseRequest
|
||||||
await router.replace({ query: { date: selectedDate.value, mode: mode.value } })
|
warehouseLoading.value = true
|
||||||
|
warehouseError.value = null
|
||||||
|
warehouseOptions.value = []
|
||||||
|
warehouseTotal.value = 0
|
||||||
|
try {
|
||||||
|
const result = await listPlatformWarehouses({ page: 1, size: 50, keyword: keyword.trim() || undefined, warehouseType: 'FBA', status: 'ACTIVE' })
|
||||||
|
if (request !== warehouseRequest || !dialogOpen.value) return
|
||||||
|
warehouseOptions.value = result.records.filter(item => item.warehouseType === 'FBA' && item.status === 'ACTIVE')
|
||||||
|
warehouseTotal.value = result.total
|
||||||
|
} catch (error) {
|
||||||
|
if (request === warehouseRequest) warehouseError.value = getApiErrorDetails(error, '仓库搜索失败,请重试')
|
||||||
|
} finally { if (request === warehouseRequest) warehouseLoading.value = false }
|
||||||
}
|
}
|
||||||
async function external(path: string) {
|
|
||||||
if (!await canLeave()) return
|
function changeWarehouse(value: string) {
|
||||||
await router.push(appointmentExternalTarget(path, { date: selectedDate.value, mode: mode.value, workItem: workKey.value || undefined }))
|
++candidateRequest
|
||||||
|
candidateLoading.value = false
|
||||||
|
candidates.value = []
|
||||||
|
selected.value = []
|
||||||
|
candidateTotal.value = 0
|
||||||
|
candidateError.value = null
|
||||||
|
candidatePage.value = 1
|
||||||
|
selectionEpoch.value++
|
||||||
|
searchedWarehouse.value = value
|
||||||
|
if (value) void loadCandidates()
|
||||||
}
|
}
|
||||||
onMounted(() => { void load() })
|
|
||||||
onActivated(() => { const returning = !active.value; active.value = true; if (returning) void load() })
|
async function loadCandidates() {
|
||||||
onDeactivated(() => { active.value = false; ++generation; controller?.abort() })
|
if (!searchedWarehouse.value) return
|
||||||
onBeforeUnmount(() => { ++generation; controller?.abort() })
|
candidateLoading.value = true
|
||||||
|
candidateError.value = null
|
||||||
|
const request = ++candidateRequest
|
||||||
|
try {
|
||||||
|
const result = await listInboundOrders({ page: candidatePage.value, size: candidateSize.value, fbaWarehouseCode: searchedWarehouse.value })
|
||||||
|
if (request !== candidateRequest || !dialogOpen.value) return
|
||||||
|
candidates.value = result.records
|
||||||
|
candidateTotal.value = result.total
|
||||||
|
} catch (error) {
|
||||||
|
if (request === candidateRequest) {
|
||||||
|
candidates.value = []
|
||||||
|
candidateError.value = getApiErrorDetails(error, '可预约货物加载失败')
|
||||||
|
}
|
||||||
|
} finally { if (request === candidateRequest) candidateLoading.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (appointmentReadOnly.value || saving.value || detailLoading.value || !detailReady.value) return
|
||||||
|
const validation = appointmentFormError(form)
|
||||||
|
if (!pendingSave.value && validation) { ElMessage.warning(validation); return }
|
||||||
|
if (!editing.value) {
|
||||||
|
if (!warehouse.value || warehouse.value !== searchedWarehouse.value || candidateLoading.value || candidateError.value) { ElMessage.warning('请先选择仓库并等待货物加载完成'); return }
|
||||||
|
if (selected.value.some(item => item.fbaWarehouseCode !== warehouse.value)) { ElMessage.warning('请重新选择当前仓库的货物'); return }
|
||||||
|
if (!selected.value.length) { ElMessage.warning('请选择需要预约的货物'); return }
|
||||||
|
if (selected.value.some(item => !item.overseasWarehouseId) || new Set(selected.value.map(item => item.overseasWarehouseId)).size !== 1) { ElMessage.warning('请选择同一接仓点的货物'); return }
|
||||||
|
if (new Set(selected.value.map(item => item.fbaWarehouseCode)).size !== 1) {
|
||||||
|
ElMessage.warning('同一预约的货物必须送往同一目的仓'); return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
saving.value = true
|
||||||
|
dialogError.value = null
|
||||||
|
try {
|
||||||
|
pendingSave.value ||= {appointmentNo: editing.value?.appointmentNo || null, version: editing.value?.version || 0, originWarehouseId: String(selected.value[0]?.overseasWarehouseId || ''), fbaWarehouseCode: searchedWarehouse.value, lineIds: selected.value.map(item => item.lineId), details: appointmentPayload(form), idempotencyKey: crypto.randomUUID()}
|
||||||
|
const payload = pendingSave.value
|
||||||
|
if (payload.appointmentNo) await updateFbaAppointment(payload.appointmentNo, { details: payload.details, version: payload.version, idempotencyKey: payload.idempotencyKey })
|
||||||
|
else await createFbaAppointment({ originWarehouseId: payload.originWarehouseId, fbaWarehouseCode: payload.fbaWarehouseCode, details: payload.details, idempotencyKey: payload.idempotencyKey, lineIds: payload.lineIds })
|
||||||
|
pendingSave.value = null
|
||||||
|
dialogOpen.value = false
|
||||||
|
ElMessage.success('预约已保存')
|
||||||
|
await Promise.all([load(), loadUnscheduled()])
|
||||||
|
} catch (error) { dialogError.value = getApiErrorDetails(error, '预约保存失败,请核对后重试'); if (['400','403','404','409','A0400','A0403','A0404','A0409'].includes(dialogError.value.code || '')) pendingSave.value = null }
|
||||||
|
finally { saving.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectCandidates(rows: object[]) {
|
||||||
|
selected.value = rows as InboundOrderSummaryDto[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove(event: CalendarEvent) {
|
||||||
|
if (!access.can('platform:appointment:delete') || loading.value || !canLeave()) return
|
||||||
|
cancellationTarget.value = appointments.value.find(item => item.appointmentNo === event.key) || null
|
||||||
|
}
|
||||||
|
function cancelEditing() {
|
||||||
|
if (!editing.value || editing.value.appointmentStatus === 'CANCELLED' || !access.can('platform:appointment:delete') || !canLeave()) return
|
||||||
|
cancellationTarget.value = editing.value
|
||||||
|
dialogOpen.value = false
|
||||||
|
}
|
||||||
|
async function cancelled() {
|
||||||
|
cancellationTarget.value = null; ++cancellationsRevision.value
|
||||||
|
ElMessage.success('预约已取消,可在取消记录中查看原因与原记录')
|
||||||
|
await Promise.all([load(),loadUnscheduled()])
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
watch(dialogOpen, open => {
|
||||||
|
if (!open) { ++candidateRequest; ++detailRequest; ++warehouseRequest; candidateLoading.value = false; warehouseLoading.value = false; detailLoading.value = false; detailReady.value = false }
|
||||||
|
})
|
||||||
|
|
||||||
|
async function resolveLink() {
|
||||||
|
const request = ++linkRequest
|
||||||
|
linkedSource.value = null; linkError.value = null; linkLoading.value = false
|
||||||
|
const { sourceKey, customerId, destinationKey } = route.query
|
||||||
|
if (!sourceKey && !customerId && !destinationKey) return
|
||||||
|
if (typeof sourceKey !== 'string' || typeof customerId !== 'string' || typeof destinationKey !== 'string') {
|
||||||
|
linkError.value = { message: '货物链接不完整,请返回原登记重新打开' }; return
|
||||||
|
}
|
||||||
|
if (!access.can(permission.lastMileOrderList)) { linkError.value = { message: '当前账号没有货源读取权限,请联系预约负责人处理' }; return }
|
||||||
|
linkLoading.value = true
|
||||||
|
try {
|
||||||
|
const result = await resolvePlanningSource({ sourceKey, customerId, destinationKey })
|
||||||
|
if (request === linkRequest) linkedSource.value = result
|
||||||
|
} catch (cause) { if (request === linkRequest) linkError.value = getApiErrorDetails(cause, '预约货源核对失败') }
|
||||||
|
finally { if (request === linkRequest) linkLoading.value = false }
|
||||||
|
}
|
||||||
|
function arrangeLinkedSource() {
|
||||||
|
if (!linkedSource.value || !access.can(permission.inboundOrderAppointment) || !linkedSource.value.source.canFollowup || linkedSource.value.coverage.appointments.length) return
|
||||||
|
selectedSource.value = linkedSource.value.source
|
||||||
|
linkedSource.value = null
|
||||||
|
workView.value = 'cargo'
|
||||||
|
}
|
||||||
|
watch(() => [route.query.sourceKey, route.query.customerId, route.query.destinationKey], resolveLink, { immediate: true })
|
||||||
|
|
||||||
|
onMounted(() => { void load(); void loadUnscheduled() })
|
||||||
|
onBeforeUnmount(() => { ++unscheduledRequest; ++calendarRequest; ++candidateRequest; ++detailRequest; ++warehouseRequest; ++linkRequest; calendarController?.abort() })
|
||||||
</script>
|
</script>
|
||||||
<template>
|
|
||||||
<AdminPage class="admin-density appointment-schedule admin-workbench" spacing="compact">
|
|
||||||
<LoadErrorState v-for="error in errors" :key="error.title" :title="error.title" :message="error.details.message" :loading="loading" @retry="load()"><template #details><ApiErrorMeta :details="error.details" /></template></LoadErrorState>
|
|
||||||
<p v-for="notice in notices" :key="notice" role="status" class="data-notice">{{ notice }}</p>
|
|
||||||
<AppointmentCalendarPanel :events="events" :loading="loading" :incomplete="incomplete" :initial-date="selectedDate" :initial-mode="mode" :can-create="canCreate" @create="openCreate" @range="load" @select="select" @open="openSource" @edit="edit" />
|
|
||||||
<AppDialog v-if="active && creating" :model-value="true" title="新增FBA送仓预约" class="admin-density-dialog admin-density business-dialog admin-workbench is-dialog" width="1080px" :show-footer="false" :before-close="closeCreate" :close-on-click-modal="true" append-to-body fullscreenable>
|
|
||||||
<AppointmentCreatePanel :can-write="canCreate" :can-leave="canLeave" @created="load()" />
|
|
||||||
</AppDialog>
|
|
||||||
<AppDialog v-if="active" :model-value="!!editor" title="调整计划到仓" class="admin-density-dialog admin-workbench is-dialog" width="520px" fullscreenable :confirm-loading="saving" :confirm-disabled="!plannedAt || conflict" :before-close="closeEditor" :confirm-text="unknownResult ? '重试确认保存结果' : '保存'" @confirm="save">
|
|
||||||
<div v-if="editor" class="density-dialog-sections">
|
|
||||||
<section class="density-dialog-section" data-tone="source" aria-label="到仓业务信息">
|
|
||||||
<table class="density-table"><tbody><tr><th scope="row">业务</th><td>{{ editor.title }}</td></tr></tbody></table>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="density-dialog-section" data-tone="work" aria-label="调整到仓时间">
|
<template>
|
||||||
<el-form class="density-form" label-position="left" label-width="150px" :disabled="saving || unknownResult">
|
<AdminPage class="admin-density" spacing="compact">
|
||||||
<table class="density-table density-table--editable"><tbody><tr><td><el-form-item label="计划到仓时间" required><template #label>计划到仓时间<InlineHelp title="到仓时间说明"><p>自动计划为到港日期加2个自然日;人工保存后优先使用人工时间。填写接仓地点当地时间。</p></InlineHelp></template><el-date-picker v-model="plannedAt" type="datetime" :disabled="saving || unknownResult" required aria-label="计划到仓时间" placeholder="接仓地点当地时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DDTHH:mm" clearable /></el-form-item></td></tr></tbody></table>
|
<p v-if="linkLoading">正在核对预约货源…</p>
|
||||||
</el-form>
|
<LoadErrorState v-if="linkError" title="预约货源核对失败" :message="linkError.message" :loading="linkLoading" @retry="resolveLink" />
|
||||||
</section>
|
<AppointmentFollowupDialog v-if="linkedSource" :source="linkedSource.source" :coverage="linkedSource.coverage" :can-write="access.can('platform:appointment:followup')" :can-arrange="access.can(permission.inboundOrderAppointment)" @arrange="arrangeLinkedSource" @close="linkedSource = null" />
|
||||||
<p v-if="unknownResult" role="status">上次提交结果尚未确认,请使用原请求重试,避免重复修改。</p>
|
<div class="appointment-heading">
|
||||||
<LoadErrorState v-if="saveError" title="计划到仓未保存" :message="saveError.message" :loading="saving" @retry="conflict ? rereadEditor() : save()"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState>
|
<div class="density-status-tabs" role="group" aria-label="预约工作视图">
|
||||||
<p v-if="conflict" role="status">重试将重新读取当前资格和版本并保留输入,核对后再次点击保存。</p>
|
<button type="button" :class="{ 'is-active': workView === 'calendar' }" :aria-pressed="workView === 'calendar'" @click="switchWorkView('calendar')">预约日历</button>
|
||||||
</div>
|
<button v-if="access.can(permission.lastMileOrderList)" type="button" :class="{ 'is-active': workView === 'containers' }" :aria-pressed="workView === 'containers'" @click="switchWorkView('containers')">提柜与到仓</button>
|
||||||
|
<button v-if="access.can(permission.lastMileOrderList)" type="button" :class="{ 'is-active': workView === 'cargo' }" :aria-pressed="workView === 'cargo'" @click="switchWorkView('cargo')">送仓与排车</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="cargoVisited" v-show="workView === 'cargo'"><AppointmentCargoPanel :external-source="selectedSource" @source-accepted="selectedSource = null" @created="load(); loadUnscheduled()" /></div>
|
||||||
|
<AppointmentContainerPanel v-if="workView === 'containers'" />
|
||||||
|
<div v-if="calendarVisited" v-show="workView === 'calendar'">
|
||||||
|
<LoadErrorState v-if="loadError" :title="errorTitle" :message="loadError.message" :loading="loading" @retry="load()"><template #details><ApiErrorMeta :details="loadError" /></template></LoadErrorState>
|
||||||
|
<LoadErrorState v-for="error in sourceErrors" :key="error.title" :title="error.title" :message="error.details.message" :loading="loading" @retry="load()"><template #details><ApiErrorMeta :details="error.details" /></template></LoadErrorState>
|
||||||
|
<AppointmentCalendarPanel :notices="[pickupNotice, showTripLayer ? tripNotice : ''].filter(Boolean)" :events="events" :loading="loading" :incomplete="sourceErrors.length > 0 || !!pickupNotice || (showTripLayer && !!tripNotice)" :can-create="access.can(permission.inboundOrderAppointment)" @layers="showTripLayer = $event.trips" @range="load" @create="openCreate" @view="openEdit($event, true)" @edit="openEdit" @delete="remove" @open="openSource">
|
||||||
|
<template #toolbar-actions>
|
||||||
|
<el-button aria-haspopup="dialog" data-unscheduled @click="unscheduledOpen = true">未定时安排({{ unscheduledError ? '加载失败' : unscheduledTotal }})</el-button>
|
||||||
|
<el-button aria-haspopup="dialog" data-cancellations @click="cancellationsOpen = true">取消记录</el-button>
|
||||||
|
</template>
|
||||||
|
<template #notice-actions><el-button v-if="showTripLayer && unresolvedTrips.length" link type="primary" @click="unresolvedDialogOpen = true">查看待核实车次({{ unresolvedTrips.length }})</el-button></template>
|
||||||
|
</AppointmentCalendarPanel>
|
||||||
|
</div>
|
||||||
|
<AppDialog v-if="unscheduledOpen" v-model="unscheduledOpen" title="未定时安排" width="min(1000px, calc(100vw - 48px))" :show-confirm="false" cancel-text="关闭" class="admin-density-dialog">
|
||||||
|
<LoadErrorState v-if="unscheduledError" title="未定时安排加载失败" :message="unscheduledError.message" @retry="loadUnscheduled" />
|
||||||
|
<DataTable v-model:page="unscheduledPage" v-model:page-size="unscheduledSize" :data="unscheduled" :columns="unscheduledColumns" :total="unscheduledTotal" :results-visible="!unscheduledError" row-key="appointmentNo" empty-text="暂无未定时安排" @update:page="loadUnscheduled" @update:page-size="unscheduledPage = 1; loadUnscheduled()">
|
||||||
|
<template #actions="{ row }"><el-button @click="openEdit({key: row.appointmentNo})">查看 / 继续</el-button></template>
|
||||||
|
</DataTable>
|
||||||
</AppDialog>
|
</AppDialog>
|
||||||
<AppDialog v-if="active && (workKey || sourceLink)" :model-value="true" title="原业务预约办理" class="admin-density-dialog admin-density business-dialog admin-workbench is-dialog" width="min(1120px, calc(100vw - 48px))" fullscreenable append-to-body :show-footer="false" :before-close="closeBusiness" :close-on-click-modal="true">
|
<AppDialog v-if="cancellationsOpen" v-model="cancellationsOpen" title="取消记录" width="min(1160px, calc(100vw - 48px))" :show-confirm="false" cancel-text="关闭" class="admin-density-dialog">
|
||||||
<el-button v-if="origins.length" link @click="backWork">返回原事项</el-button>
|
<AppointmentCancellationRecords :key="cancellationsRevision" @view="openEdit({key: $event}, true)" />
|
||||||
<WorkDetailPanel v-if="workKey" :key="workKey" :item-key="workKey" :initial-action="initialAction" :can-leave="canLeave" @open="openWork" @external="external" @saved="load()" @updated="load()" @container="id => external(`/container-loading/overseas/${encodeURIComponent(id)}`)" />
|
</AppDialog>
|
||||||
<SourceAppointmentPanel v-else-if="sourceLink" :key="JSON.stringify(sourceLink)" :source="sourceLink" :can-leave="canLeave" @updated="load()" />
|
<AppDialog v-if="unresolvedDialogOpen" v-model="unresolvedDialogOpen" :title="`待核实车次(${unresolvedTrips.length})`" width="min(1000px, calc(100vw - 48px))" :show-confirm="false" class="admin-density-dialog">
|
||||||
|
<p>这些车次缺少地点或时区,暂未计入日历。原计划时间保留 UTC。</p>
|
||||||
|
<DataTable v-model:page="unresolvedPage" v-model:page-size="unresolvedSize" :data="unresolvedRows" :columns="unresolvedColumns" :total="unresolvedTrips.length" row-key="tripNo" @update:page-size="unresolvedPage = 1">
|
||||||
|
<template #actions="{ row }"><el-button class="density-action" @click="router.push(`/overseas-master-data/trips/${encodeURIComponent(row.tripNo)}`)">查看来源</el-button></template>
|
||||||
|
<template #issues="{ row }">{{ tripIssues(row as TripCalendarEntry) }}</template>
|
||||||
|
</DataTable>
|
||||||
|
</AppDialog>
|
||||||
|
<AppointmentCancellationDialog v-if="cancellationTarget" :appointment-no="cancellationTarget.appointmentNo" :version="cancellationTarget.version" :selected-count="cancellationTarget.selectedCount" @close="cancellationTarget = null" @cancelled="cancelled" />
|
||||||
|
<AppDialog :model-value="dialogOpen" @update:model-value="closeAppointment" :before-close="beforeCloseAppointment" :show-confirm="!appointmentReadOnly" class="admin-density-dialog" :title="appointmentReadOnly ? '查看预约' : editing ? '编辑预约' : '新增预约'" width="min(1080px, calc(100vw - 48px))" :confirm-text="pendingSave ? '重试本次保存' : '保存'" :confirm-loading="saving" :confirm-disabled="detailLoading || !detailReady || (!editing && (!warehouse || !selected.length || candidateLoading || !!candidateError))" @confirm="save">
|
||||||
|
<LoadErrorState v-if="dialogError" title="预约操作失败" :message="dialogError.message" :show-retry="false"><template #details><ApiErrorMeta :details="dialogError" /></template></LoadErrorState>
|
||||||
|
<div v-loading="detailLoading">
|
||||||
|
<el-form label-position="top" class="calendar-form density-form">
|
||||||
|
<el-form-item label="预约仓库" required>
|
||||||
|
<el-input v-if="editing" :model-value="warehouse" readonly />
|
||||||
|
<el-select v-else v-model="warehouse" aria-label="预约仓库" filterable remote clearable :remote-method="searchWarehouses" :loading="warehouseLoading" placeholder="搜索仓库编码或名称" @change="changeWarehouse">
|
||||||
|
<el-option v-for="item in warehouseOptions" :key="String(item.id)" :value="item.warehouseCode" :label="item.warehouseName === item.warehouseCode ? item.warehouseCode : `${item.warehouseCode} · ${item.warehouseName}`" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<LoadErrorState v-if="!editing && warehouseError" title="仓库加载失败" :message="warehouseError.message" @retry="searchWarehouses(warehouseKeyword)" />
|
||||||
|
<p v-if="!editing && warehouseTotal > warehouseOptions.length && !warehouseError" class="appointment-hint">输入更完整的仓库编码或名称,缩小搜索范围。</p>
|
||||||
|
<FbaAppointmentFields :model="form" :appointment-no="editing?.appointmentNo" :timezone="editing?.timezone || warehouseOptions.find(item => item.warehouseCode === warehouse)?.timezone" :disabled="appointmentReadOnly || saving || !!pendingSave" />
|
||||||
|
<el-button v-if="editing && editing.appointmentStatus !== 'CANCELLED' && access.can('platform:appointment:delete')" data-cancel-editing type="danger" plain :disabled="saving || !!pendingSave || !detailReady" @click="cancelEditing">取消预约</el-button>
|
||||||
|
<template v-if="!editing && warehouse">
|
||||||
|
<DataTable :key="selectionEpoch" v-model:page="candidatePage" v-model:page-size="candidateSize" :data="candidates" :columns="columns" :total="candidateTotal" :loading="candidateLoading" row-key="lineId" :results-visible="!candidateError" @selection-change="selectCandidates" @update:page="loadCandidates()" @update:page-size="candidatePage = 1; loadCandidates()">
|
||||||
|
<template #customer="{ row }">{{ row.customerName?.trim() || '客户名称缺失' }}</template>
|
||||||
|
<template #notices><LoadErrorState v-if="candidateError" title="货物加载失败" :message="candidateError.message" @retry="loadCandidates()" /></template>
|
||||||
|
<template #pagination-left>已选 {{ selected.length }} 票,可跨客户选择同一目的仓货物</template>
|
||||||
|
</DataTable>
|
||||||
|
</template>
|
||||||
|
<p v-else-if="!editing" class="appointment-hint">先选择预约仓库,即可勾选同仓货物,支持多个客户一起预约。</p>
|
||||||
|
<div v-else class="appointment-cargo">
|
||||||
|
<span>{{ editing.selectedCount }} 票货物</span>
|
||||||
|
<AppointmentInboundCodes :key="editing.appointmentNo" :codes="editing.items.map(item => item.inboundCode)" />
|
||||||
|
<details :key="`cancellations-${editing.appointmentNo}`" @toggle="cancellationHistoryOpen = ($event.target as HTMLDetailsElement).open"><summary>取消历史</summary><AppointmentCancellationHistory v-if="cancellationHistoryOpen" :key="editing.appointmentNo" :appointment-no="editing.appointmentNo" /></details>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</AppDialog>
|
</AppDialog>
|
||||||
</AdminPage>
|
</AdminPage>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.data-notice { margin: 0; font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }
|
.appointment-heading { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-5); }
|
||||||
:global(.business-dialog.el-dialog:not(.is-fullscreen)) { max-height: 88dvh; }
|
.appointment-heading .density-status-tabs { flex: 1; margin: 0; }
|
||||||
|
.calendar-form { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0 var(--admin-space-6); }
|
||||||
|
.calendar-form :deep(.el-select), .calendar-form :deep(.el-date-editor) { width: 100%; }
|
||||||
|
.appointment-cargo { padding: 12px 0; line-height: 1.7; overflow-wrap: anywhere; font-size: 13px; }
|
||||||
|
.appointment-hint { color: var(--el-text-color-secondary); font-size: var(--admin-font-body); margin: var(--admin-space-5) 0; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ async function save() {
|
|||||||
<p>取消后释放货物占用,保留原备注、时间及取消历史;不会回退库存或取消车次。</p>
|
<p>取消后释放货物占用,保留原备注、时间及取消历史;不会回退库存或取消车次。</p>
|
||||||
<LoadErrorState v-if="error" title="取消未完成" :message="error.message" :show-retry="false" />
|
<LoadErrorState v-if="error" title="取消未完成" :message="error.message" :show-retry="false" />
|
||||||
<el-form label-position="top" :disabled="saving || !!pending">
|
<el-form label-position="top" :disabled="saving || !!pending">
|
||||||
<el-form-item label="取消原因" required><el-input v-model="reason" type="textarea" maxlength="1000" show-word-limit /></el-form-item>
|
<el-form-item label="取消原因" required><el-input v-model="reason" type="textarea" maxlength="1000" show-word-limit placeholder="请填写实际取消原因" /></el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
</AppDialog>
|
</AppDialog>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ onBeforeUnmount(() => { ++request; ++contextRequest; controller?.abort() })
|
|||||||
<LoadErrorState v-if="error" compact title="货柜列表暂时无法加载" :message="error.code === 'A0404' ? '列表服务暂不可用,请稍后重试。' : error.message" @retry="load()"><template #details><details><summary>诊断详情</summary><ApiErrorMeta :details="error" /></details></template></LoadErrorState>
|
<LoadErrorState v-if="error" compact title="货柜列表暂时无法加载" :message="error.code === 'A0404' ? '列表服务暂不可用,请稍后重试。' : error.message" @retry="load()"><template #details><details><summary>诊断详情</summary><ApiErrorMeta :details="error" /></details></template></LoadErrorState>
|
||||||
<LoadErrorState v-if="contextError" compact title="操作未完成" :message="contextError.message" :show-retry="false"><template #details><details><summary>诊断详情</summary><ApiErrorMeta :details="contextError" /></details></template></LoadErrorState>
|
<LoadErrorState v-if="contextError" compact title="操作未完成" :message="contextError.message" :show-retry="false"><template #details><details><summary>诊断详情</summary><ApiErrorMeta :details="contextError" /></details></template></LoadErrorState>
|
||||||
<details v-if="impactError" class="container-help"><summary>船期跟进暂不可用,货柜列表仍可查看</summary><ApiErrorMeta :details="impactError" /></details>
|
<details v-if="impactError" class="container-help"><summary>船期跟进暂不可用,货柜列表仍可查看</summary><ApiErrorMeta :details="impactError" /></details>
|
||||||
|
<details v-if="!error" class="container-help"><summary>说明</summary><p>同柜共用提柜跟进,接仓按仓库分别跟进。预计到港仅供参考。</p></details>
|
||||||
</template>
|
</template>
|
||||||
<template #actions="{ row }"><el-button class="density-action" size="small" :disabled="opening" @click="follow(row as PlanningContainer)">提柜跟进</el-button><el-button v-if="row.impact" link type="primary" @click="impactId = row.containerBookingId">{{ row.impact.status === 'OPEN' ? '处理船期变化' : '核对记录' }}</el-button></template>
|
<template #actions="{ row }"><el-button class="density-action" size="small" :disabled="opening" @click="follow(row as PlanningContainer)">提柜跟进</el-button><el-button v-if="row.impact" link type="primary" @click="impactId = row.containerBookingId">{{ row.impact.status === 'OPEN' ? '处理船期变化' : '核对记录' }}</el-button></template>
|
||||||
<template #packages="{ row }">{{ row.packages ?? '待核实' }}</template>
|
<template #packages="{ row }">{{ row.packages ?? '待核实' }}</template>
|
||||||
|
|||||||
@@ -1,133 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import AppointmentCreatePanel from './AppointmentCreatePanel.vue'
|
|
||||||
import { createSourceAppointment, listPlanningCargo, listPlanningDestinations, previewPlanningBatch, resolvePlanningSource, type PlanningCargo, type PlanningBatchPreview } from './planningApi'
|
|
||||||
import type { QueryField } from '@/shared/components/QueryToolbar.vue'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
|
|
||||||
vi.mock('./planningApi', async original => ({ ...await original<typeof import('./planningApi')>(), listPlanningCargo: vi.fn(), listPlanningDestinations: vi.fn(), resolvePlanningSource: vi.fn(), previewPlanningBatch: vi.fn(), createSourceAppointment: vi.fn() }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => true }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { success: vi.fn(), warning: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
|
||||||
const cargo: PlanningCargo = { sourceKey: 'ORDER:9007199254740999', orderId: '9007199254740999', customerId: '9007199254740998', customerName: '测试客户', inboundCode: 'IN-TEST', containerBookingId: 'container-1', containerNo: 'TEST-CONT', originWarehouseId: 'origin-1', originWarehouseCode: 'US-W', originWarehouseName: '美国仓', destinationWarehouseCode: 'ONT8', packages: 20, receivedPackages: 0, shippedPackages: 0, sourcePalletCount: null, volumeCbm: null, estimatedArrivalAt: null, estimatedWarehouseAt: null, orderVersion: 1, standardNode: 'DEPARTED', shippingVersion: null, shippingObservedAt: null, shippingProvider: null, hasInboundPlan: false, hasActiveAppointment: false, detained: false, mixedDestinations: false }
|
|
||||||
const source = { sourceKey: cargo.sourceKey, customerId: cargo.customerId, orderId: cargo.orderId, inboundCode: cargo.inboundCode, bookingNo: null, containerNo: cargo.containerNo, originWarehouseId: cargo.originWarehouseId, originWarehouseName: cargo.originWarehouseName, destinationKey: 'FBA:LAX9', destinationWarehouseCode: 'LAX9', packages: 20, sourceVersion: 'v1', canFollowup: true, blockReasons: [] }
|
|
||||||
const preview: PlanningBatchPreview = { group: { originWarehouseId: cargo.originWarehouseId, destinationKey: source.destinationKey, packages: 20, sourceCount: 1, customerCount: 1, readinessIncomplete: true, readyFrom: null, readyTo: null, unknownQuantitySources: 0 }, originWarehouseName: '美国仓', destinationWarehouseCode: 'LAX9', destinationTimezone: 'America/Los_Angeles', sources: [source], missingFields: [] }
|
|
||||||
const guards = new Set<LeaveGuard>()
|
|
||||||
function render(canWrite = true) {
|
|
||||||
return mount(AppointmentCreatePanel, { props: { canWrite, canLeave: async () => { for (const guard of guards) if (!await guard()) return false; return true } }, global: {
|
|
||||||
provide: { 'appointment-work-leave-guard': (guard: LeaveGuard) => { guards.add(guard); return () => guards.delete(guard) } },
|
|
||||||
stubs: {
|
|
||||||
DataTable: { name: 'DataTable', props: ['data', 'total', 'resultsVisible'], emits: ['update:page'], template: '<div><slot name="filters" /><slot name="toolbar-actions" /><slot name="notices" /><div v-for="row in data" :key="row.sourceKey"><span>{{ row.inboundCode }}</span><slot name="select" :row="row" /><slot name="eligibility" :row="row" /></div><button data-page @click="$emit(\'update:page\', 2)">下一页</button></div>' },
|
|
||||||
QueryToolbar: { name: 'QueryToolbar', props: ['modelValue', 'fields'], emits: ['search', 'update:modelValue'], template: '<button data-query @click="$emit(\'search\')">查询</button>' },
|
|
||||||
ElCheckbox: { props: ['modelValue', 'disabled'], emits: ['change'], template: '<input type="checkbox" :checked="modelValue" :disabled="disabled" @change="$emit(\'change\', $event.target.checked)">' },
|
|
||||||
ElButton: { props: ['disabled', 'loading'], template: '<button :disabled="disabled || loading"><slot /></button>' },
|
|
||||||
FbaAppointmentFields: { name: 'FbaAppointmentFields', props: ['model', 'disabled'], template: '<input data-date type="date" v-model="model.plannedDate" :disabled="disabled">' },
|
|
||||||
LoadErrorState: { props: ['message'], emits: ['retry'], template: '<p role="alert">{{ message }}<button data-retry @click="$emit(\'retry\')">重试</button><slot name="details" /></p>' }, ApiErrorMeta: true,
|
|
||||||
},
|
|
||||||
} })
|
|
||||||
}
|
|
||||||
async function selectAndPrepare(wrapper: ReturnType<typeof render>) {
|
|
||||||
await wrapper.get('input[type="checkbox"]').setValue(true)
|
|
||||||
await wrapper.findAll('button').find(button => button.text().startsWith('下一步'))!.trigger('click')
|
|
||||||
await flushPromises()
|
|
||||||
}
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks(); guards.clear()
|
|
||||||
vi.mocked(listPlanningCargo).mockResolvedValue({ records: [cargo], total: 21, page: 1, size: 20, pages: 2 })
|
|
||||||
vi.mocked(resolvePlanningSource).mockResolvedValue({ source, coverage: { status: 'NONE', missingFields: [], changeReviewRequired: false, appointments: [] } })
|
|
||||||
vi.mocked(previewPlanningBatch).mockResolvedValue(preview)
|
|
||||||
vi.mocked(createSourceAppointment).mockResolvedValue(batchContext().appointment)
|
|
||||||
vi.mocked(listPlanningDestinations).mockResolvedValue(['ABE4','ONT8'])
|
|
||||||
})
|
|
||||||
it('loads searchable destination options lazily and keeps the submitted filter across pages until reset', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const toolbar = wrapper.getComponent({name:'QueryToolbar'})
|
|
||||||
const destination = () => (toolbar.props('fields') as QueryField[]).find(field=>field.key==='destination')!
|
|
||||||
expect(destination().props?.filterable).toBe(true)
|
|
||||||
expect(listPlanningDestinations).not.toHaveBeenCalled()
|
|
||||||
const open = destination().props!.onVisibleChange as (visible:boolean)=>void
|
|
||||||
open(true); await flushPromises()
|
|
||||||
expect(destination().options).toEqual([{label:'ABE4',value:'ABE4'},{label:'ONT8',value:'ONT8'}])
|
|
||||||
open(true); await flushPromises(); expect(listPlanningDestinations).toHaveBeenCalledTimes(1)
|
|
||||||
toolbar.vm.$emit('update:modelValue',{keyword:'IN-TEST',destination:'ABE4'})
|
|
||||||
await wrapper.get('[data-query]').trigger('click'); await flushPromises()
|
|
||||||
expect(listPlanningCargo).toHaveBeenLastCalledWith({page:1,size:20,keyword:'IN-TEST',destination:'ABE4'},expect.any(AbortSignal))
|
|
||||||
await wrapper.get('[data-page]').trigger('click'); await flushPromises()
|
|
||||||
expect(listPlanningCargo).toHaveBeenLastCalledWith({page:2,size:20,keyword:'IN-TEST',destination:'ABE4'},expect.any(AbortSignal))
|
|
||||||
toolbar.vm.$emit('update:modelValue',{keyword:'',destination:undefined})
|
|
||||||
await wrapper.get('[data-query]').trigger('click'); await flushPromises()
|
|
||||||
expect(listPlanningCargo).toHaveBeenLastCalledWith({page:1,size:20,keyword:undefined},expect.any(AbortSignal))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('reports a destination directory failure and allows retry without hiding loaded cargo', async () => {
|
|
||||||
vi.mocked(listPlanningDestinations).mockRejectedValueOnce(new Error('offline'))
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const field = (wrapper.getComponent({name:'QueryToolbar'}).props('fields') as QueryField[]).find(field=>field.key==='destination')!
|
|
||||||
;(field.props!.onVisibleChange as (visible:boolean)=>void)(true); await flushPromises()
|
|
||||||
expect(wrapper.find('[role="alert"]').exists()).toBe(true)
|
|
||||||
expect(wrapper.getComponent({name:'DataTable'}).props('resultsVisible')).toBe(true)
|
|
||||||
await wrapper.get('[data-retry]').trigger('click'); await flushPromises()
|
|
||||||
expect(listPlanningDestinations).toHaveBeenCalledTimes(2)
|
|
||||||
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not read or create per-row details until the operator selects cargo and proceeds', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(listPlanningCargo).toHaveBeenCalledWith({ page: 1, size: 20, keyword: undefined }, expect.any(AbortSignal))
|
|
||||||
expect(resolvePlanningSource).not.toHaveBeenCalled(); expect(previewPlanningBatch).not.toHaveBeenCalled(); expect(createSourceAppointment).not.toHaveBeenCalled()
|
|
||||||
await selectAndPrepare(wrapper)
|
|
||||||
expect(resolvePlanningSource).toHaveBeenCalledWith({ sourceKey: cargo.sourceKey, customerId: cargo.customerId })
|
|
||||||
expect(previewPlanningBatch).toHaveBeenCalledWith([{ sourceKey: source.sourceKey, customerId: source.customerId, destinationKey: 'FBA:LAX9' }])
|
|
||||||
expect(wrapper.text()).not.toContain(cargo.orderId)
|
|
||||||
wrapper.unmount(); expect(guards.size).toBe(0)
|
|
||||||
})
|
|
||||||
it('submits the real form, shows the saved appointment, and prevents another submit of the same completed form', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); await selectAndPrepare(wrapper)
|
|
||||||
await wrapper.get('[data-date]').setValue('2026-10-25')
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '保存预约安排')!.trigger('click'); await flushPromises()
|
|
||||||
expect(createSourceAppointment).toHaveBeenCalledWith(expect.objectContaining({ sources: [{ sourceKey: source.sourceKey, customerId: source.customerId, destinationKey: 'FBA:LAX9' }], details: expect.objectContaining({ plannedDate: '2026-10-25', plannedAt: null }), idempotencyKey: expect.any(String) }))
|
|
||||||
expect(wrapper.emitted('created')).toEqual([[batchContext().appointment]])
|
|
||||||
expect(wrapper.get('[role="status"]').text()).toContain(batchContext().appointment.appointmentNo)
|
|
||||||
expect(wrapper.findAll('button').some(button => button.text() === '保存预约安排')).toBe(false)
|
|
||||||
expect(wrapper.find('[data-date]').exists()).toBe(false)
|
|
||||||
expect(wrapper.get('[aria-label="预约保存回执"]').text()).toContain('等待对方确认')
|
|
||||||
expect(wrapper.get('[aria-label="预约保存回执"]').findAll('input, textarea, select')).toHaveLength(0)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('preserves the original request and blocks returning or closing after an unknown creation result', async () => {
|
|
||||||
vi.mocked(createSourceAppointment).mockRejectedValueOnce(new Error('connection lost'))
|
|
||||||
const wrapper = render(); await flushPromises(); await selectAndPrepare(wrapper)
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '保存预约安排')!.trigger('click'); await flushPromises()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '返回选择货物')!.trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.findComponent({ name: 'DataTable' }).exists()).toBe(false)
|
|
||||||
expect((await Promise.all([...guards].map(guard => guard()))).includes(false)).toBe(true)
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '重试本次创建')!.trigger('click'); await flushPromises()
|
|
||||||
expect(vi.mocked(createSourceAppointment).mock.calls[1]).toEqual(vi.mocked(createSourceAppointment).mock.calls[0])
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('disables blocked cargo and keeps selected cargo across pages', async () => {
|
|
||||||
vi.mocked(listPlanningCargo).mockResolvedValueOnce({ records: [cargo, { ...cargo, sourceKey: 'ORDER:blocked', detained: true }], total: 21, page: 1, size: 20, pages: 2 })
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.findAll('input[type="checkbox"]')[1]!.attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.findAll('input[type="checkbox"]')[0]!.setValue(true)
|
|
||||||
await wrapper.get('[data-page]').trigger('click'); await flushPromises()
|
|
||||||
expect(listPlanningCargo).toHaveBeenLastCalledWith({ page: 2, size: 20, keyword: undefined }, expect.any(AbortSignal))
|
|
||||||
expect(wrapper.findAll('button').some(button => button.text() === '下一步:填写预约(1)')).toBe(true)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('reports source failures and does not offer a write path without permission', async () => {
|
|
||||||
const readonly = render(false); await flushPromises()
|
|
||||||
expect(listPlanningCargo).not.toHaveBeenCalled(); expect(createSourceAppointment).not.toHaveBeenCalled(); readonly.unmount()
|
|
||||||
vi.mocked(listPlanningCargo).mockRejectedValueOnce(new Error('unavailable'))
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.findComponent({ name: 'DataTable' }).props('resultsVisible')).toBe(false)
|
|
||||||
expect(wrapper.find('[role="alert"]').exists()).toBe(true)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('ignores a source resolution that arrives after the dialog is closed', async () => {
|
|
||||||
let complete!: (value: Awaited<ReturnType<typeof resolvePlanningSource>>) => void
|
|
||||||
vi.mocked(resolvePlanningSource).mockImplementationOnce(() => new Promise(resolve => { complete = resolve }))
|
|
||||||
const wrapper = render(); await flushPromises(); await selectAndPrepare(wrapper)
|
|
||||||
wrapper.unmount(); complete({ source, coverage: { status: 'NONE', missingFields: [], changeReviewRequired: false, appointments: [] } }); await flushPromises()
|
|
||||||
expect(previewPlanningBatch).not.toHaveBeenCalled(); expect(createSourceAppointment).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import InlineHelp from '@/shared/components/InlineHelp.vue'
|
|
||||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
|
||||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
|
||||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import LineClampText from '@/shared/components/LineClampText.vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import { createAppointmentForm, type FbaAppointmentDto } from '@/modules/overseas-warehouse'
|
|
||||||
import { listPlanningCargo, listPlanningDestinations, resolvePlanningSource, type PlanningCargo } from './planningApi'
|
|
||||||
import { useWorkDraft, type LeaveGuard } from './useWorkDraft'
|
|
||||||
import type { SourceReference } from './workApi'
|
|
||||||
import WorkCreateAppointmentForm from './WorkCreateAppointmentForm.vue'
|
|
||||||
|
|
||||||
const props = defineProps<{ canWrite: boolean; canLeave: LeaveGuard }>()
|
|
||||||
const emit = defineEmits<{ created: [appointment: FbaAppointmentDto] }>()
|
|
||||||
const query = ref<QueryModel>({ keyword: '', destination: '' }), keyword = ref(''), destination = ref(''), page = ref(1), total = ref(0)
|
|
||||||
const destinations = ref<string[]>([]), destinationsLoading = ref(false), destinationsLoaded = ref(false), destinationError = ref<ApiErrorDetails | null>(null)
|
|
||||||
let destinationsRequest = 0, destinationsController: AbortController | null = null
|
|
||||||
const fields = computed<QueryField[]>(() => [
|
|
||||||
{ key: 'keyword', type: 'input', label: '货物', placeholder: '入仓码、柜号、客户名称', width: 300 },
|
|
||||||
{ key: 'destination', type: 'select', label: '目的FBA仓', placeholder: '搜索或选择目的FBA仓', width: 220,
|
|
||||||
options: destinations.value.map(code => ({ label: code, value: code })),
|
|
||||||
props: { filterable: true, loading: destinationsLoading.value, onVisibleChange: (visible: boolean) => {
|
|
||||||
if (visible && !destinationsLoaded.value) void loadDestinations()
|
|
||||||
} } },
|
|
||||||
])
|
|
||||||
const rows = ref<PlanningCargo[]>([]), selected = ref<Record<string, PlanningCargo>>({})
|
|
||||||
const selectedRows = computed(() => Object.values(selected.value))
|
|
||||||
const loading = ref(false), resolving = ref(false), error = ref<ApiErrorDetails | null>(null), selectionError = ref<ApiErrorDetails | null>(null)
|
|
||||||
const references = ref<SourceReference[] | null>(null), created = ref<FbaAppointmentDto | null>(null)
|
|
||||||
const createdForm = computed(() => createAppointmentForm(created.value || undefined))
|
|
||||||
useWorkDraft(computed(() => !references.value && !created.value && selectedRows.value.length > 0), computed(() => false))
|
|
||||||
let generation = 0, selectionGeneration = 0, controller: AbortController | null = null
|
|
||||||
const columns: DataTableColumn[] = [
|
|
||||||
{ key: 'select', label: '选择', width: 60, slotName: 'select' },
|
|
||||||
{ prop: 'inboundCode', label: '入仓码', minWidth: 180 },
|
|
||||||
{ prop: 'customerName', label: '客户', minWidth: 140, slotName: 'customer' },
|
|
||||||
{ prop: 'containerNo', label: '柜号', minWidth: 145 },
|
|
||||||
{ prop: 'originWarehouseName', label: '起运仓', minWidth: 140, slotName: 'origin' },
|
|
||||||
{ prop: 'destinationWarehouseCode', label: '目的FBA仓', width: 110 },
|
|
||||||
{ prop: 'packages', label: '箱数', width: 80 },
|
|
||||||
{ key: 'eligibility', label: '预约资格', minWidth: 130, slotName: 'eligibility' },
|
|
||||||
]
|
|
||||||
function key(row: PlanningCargo) { return JSON.stringify([row.customerId, row.sourceKey]) }
|
|
||||||
function reason(row: PlanningCargo) {
|
|
||||||
if (row.detained) return '货物暂扣中'
|
|
||||||
if (row.mixedDestinations) return '多个目的地,需先核对'
|
|
||||||
if (row.hasActiveAppointment) return '已有有效预约'
|
|
||||||
const anchor = selectedRows.value[0]
|
|
||||||
if (anchor && (anchor.originWarehouseId !== row.originWarehouseId || anchor.destinationWarehouseCode !== row.destinationWarehouseCode)) return '请选择同起运仓、同目的仓'
|
|
||||||
if (selectedRows.value.length >= 100 && !selected.value[key(row)]) return '每次最多选择100票'
|
|
||||||
return ''
|
|
||||||
}
|
|
||||||
function toggle(row: PlanningCargo, checked: boolean | string | number) {
|
|
||||||
if (!props.canWrite || resolving.value) return
|
|
||||||
if (!checked) delete selected.value[key(row)]
|
|
||||||
else if (!reason(row)) selected.value[key(row)] = row
|
|
||||||
selectionError.value = null
|
|
||||||
}
|
|
||||||
async function load(nextPage = page.value) {
|
|
||||||
if (!props.canWrite) return
|
|
||||||
page.value = nextPage
|
|
||||||
const current = ++generation; controller?.abort(); controller = new AbortController()
|
|
||||||
loading.value = true; error.value = null
|
|
||||||
try {
|
|
||||||
const result = await listPlanningCargo({ page: nextPage, size: 20, keyword: keyword.value || undefined,
|
|
||||||
...(destination.value ? { destination: destination.value } : {}) }, controller.signal)
|
|
||||||
if (current === generation) { rows.value = result.records; total.value = result.total }
|
|
||||||
} catch (cause) {
|
|
||||||
if (current === generation) { rows.value = []; total.value = 0; error.value = getApiErrorDetails(cause, '可预约货物读取失败') }
|
|
||||||
} finally { if (current === generation) loading.value = false }
|
|
||||||
}
|
|
||||||
function search() {
|
|
||||||
keyword.value = String(query.value.keyword || '').trim()
|
|
||||||
destination.value = String(query.value.destination || '').trim()
|
|
||||||
void load(1)
|
|
||||||
}
|
|
||||||
async function loadDestinations() {
|
|
||||||
if (!props.canWrite || destinationsLoading.value) return
|
|
||||||
const current = ++destinationsRequest
|
|
||||||
destinationsController?.abort(); destinationsController = new AbortController()
|
|
||||||
destinationsLoading.value = true; destinationError.value = null
|
|
||||||
try {
|
|
||||||
const result = await listPlanningDestinations(destinationsController.signal)
|
|
||||||
if (current === destinationsRequest) { destinations.value = result; destinationsLoaded.value = true }
|
|
||||||
} catch (cause) {
|
|
||||||
if (current === destinationsRequest) destinationError.value = getApiErrorDetails(cause, '目的FBA仓选项读取失败')
|
|
||||||
} finally { if (current === destinationsRequest) destinationsLoading.value = false }
|
|
||||||
}
|
|
||||||
async function prepare() {
|
|
||||||
if (!props.canWrite || !selectedRows.value.length || loading.value || resolving.value || error.value) return
|
|
||||||
const current = ++selectionGeneration, snapshot = [...selectedRows.value]
|
|
||||||
resolving.value = true; selectionError.value = null
|
|
||||||
try {
|
|
||||||
const sources: SourceReference[] = []
|
|
||||||
// 仅对明确选中的货物读取最新来源,不按展示行逐票请求,也不猜目的地键。
|
|
||||||
for (const row of snapshot) {
|
|
||||||
if (current !== selectionGeneration) return
|
|
||||||
const { source } = await resolvePlanningSource({ sourceKey: row.sourceKey, customerId: row.customerId })
|
|
||||||
if (current !== selectionGeneration) return
|
|
||||||
if (!source.canFollowup) { selectionError.value = { message: source.blockReasons.join(';') || '所选货物当前不能新增预约,请重新核对。' }; return }
|
|
||||||
sources.push({ sourceKey: source.sourceKey, customerId: source.customerId, destinationKey: source.destinationKey })
|
|
||||||
}
|
|
||||||
if (current === selectionGeneration) references.value = sources
|
|
||||||
} catch (cause) { if (current === selectionGeneration) selectionError.value = getApiErrorDetails(cause, '所选货物核对失败') }
|
|
||||||
finally { if (current === selectionGeneration) resolving.value = false }
|
|
||||||
}
|
|
||||||
async function back() { if (await props.canLeave()) references.value = null }
|
|
||||||
function saved(appointment: FbaAppointmentDto) {
|
|
||||||
created.value = appointment; references.value = null; selected.value = {}
|
|
||||||
emit('created', appointment)
|
|
||||||
}
|
|
||||||
async function again() {
|
|
||||||
if (!await props.canLeave()) return
|
|
||||||
created.value = null; references.value = null; selected.value = {}; selectionError.value = null
|
|
||||||
await load()
|
|
||||||
}
|
|
||||||
onMounted(() => { void load() })
|
|
||||||
onBeforeUnmount(() => { ++generation; ++selectionGeneration; ++destinationsRequest; controller?.abort(); destinationsController?.abort() })
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section class="density-dialog-sections" aria-label="新增FBA送仓预约">
|
|
||||||
<template v-if="created">
|
|
||||||
<section class="density-dialog-section" data-tone="summary" aria-label="预约保存回执">
|
|
||||||
<h3 class="density-dialog-section__title" role="status">预约已保存:{{ created.appointmentNo || '预约编号未返回' }}</h3>
|
|
||||||
<table class="density-table"><tbody>
|
|
||||||
<tr><th scope="row">系统单号</th><td>{{ created.appointmentNo || '—' }}</td><th scope="row">目的仓时区</th><td>{{ created.timezone || '待核实' }}</td></tr>
|
|
||||||
<tr><th scope="row">计划送仓日期</th><td>{{ createdForm.plannedDate || '—' }}</td><th scope="row">本次登记</th><td>{{ ({ PENDING: '等待对方确认', SUCCESS: '已取得对方正式确认', FAILED: '未约成', CANCELLED: '已取消' })[createdForm.appointmentStatus] }}</td></tr>
|
|
||||||
<tr><th scope="row">计划开始时段</th><td>{{ createdForm.plannedAt || '—' }}</td><th scope="row">计划结束时段</th><td>{{ createdForm.plannedEndAt || '—' }}</td></tr>
|
|
||||||
<tr><th scope="row">外部约号</th><td colspan="3">{{ createdForm.confirmationNo || '—' }}</td></tr>
|
|
||||||
<tr><th scope="row">对方确认开始时间</th><td>{{ createdForm.appointmentAt || '—' }}</td><th scope="row">对方确认结束时间</th><td>{{ createdForm.appointmentEndAt || '—' }}</td></tr>
|
|
||||||
<tr><th scope="row">确认开始时差</th><td>{{ createdForm.startOffset || '—' }}</td><th scope="row">确认结束时差</th><td>{{ createdForm.endOffset || '—' }}</td></tr>
|
|
||||||
<tr><th scope="row">{{ createdForm.appointmentStatus === 'FAILED' ? '原因' : '备注' }}</th><td colspan="3">{{ createdForm.appointmentRemark || '—' }}</td></tr>
|
|
||||||
</tbody></table>
|
|
||||||
<p class="density-dialog-note">预约已保存,请继续在原业务安排车辆。</p>
|
|
||||||
</section>
|
|
||||||
<div v-if="canWrite" class="density-actions density-actions--footer"><el-button @click="again">继续新增预约</el-button></div>
|
|
||||||
</template>
|
|
||||||
<template v-else-if="references">
|
|
||||||
<div class="density-actions"><el-button @click="back">返回选择货物</el-button></div>
|
|
||||||
<WorkCreateAppointmentForm :sources="references" :can-write="canWrite" @saved="saved" />
|
|
||||||
</template>
|
|
||||||
<template v-else>
|
|
||||||
<section class="density-dialog-section" data-tone="source" aria-label="选择预约货物">
|
|
||||||
<div class="workbench-table"><DataTable :data="rows" :columns="columns" :page="page" :page-size="20" :page-sizes="[20]" :total="total" :loading="loading" :results-visible="!error" :row-key="key" max-height="" empty-text="暂无可预约货物" @update:page="load($event)">
|
|
||||||
<template #filters><QueryToolbar v-model="query" ariaLabel="新增预约货物查询" :fields="fields" :loading="loading || resolving" @search="search" /></template>
|
|
||||||
<template #toolbar-actions><InlineHelp title="选货说明"><p>选择需要送往FBA的已有货物;同一起运仓、同一目的仓可合并多个客户的货物。跨页选择会保留。</p></InlineHelp><el-button :disabled="!selectedRows.length || resolving" @click="selected = {}; selectionError = null">清空选择</el-button><el-button type="primary" :disabled="!canWrite || !selectedRows.length || loading || !!error" :loading="resolving" @click="prepare">下一步:填写预约({{ selectedRows.length }})</el-button></template>
|
|
||||||
<template #pagination-left>已选 {{ selectedRows.length }}/100 票</template>
|
|
||||||
<template #notices><LoadErrorState v-if="destinationError" title="目的FBA仓选项读取失败" :message="destinationError.message" :loading="destinationsLoading" @retry="loadDestinations"><template #details><ApiErrorMeta :details="destinationError" /></template></LoadErrorState><LoadErrorState v-if="error" title="可预约货物读取失败" :message="error.message" :loading="loading" @retry="load()"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState><LoadErrorState v-if="selectionError" title="所选货物核对失败" :message="selectionError.message" :show-retry="false"><template #details><ApiErrorMeta :details="selectionError" /></template></LoadErrorState></template>
|
|
||||||
<template #select="{ row }"><el-checkbox :model-value="!!selected[key(row as PlanningCargo)]" :aria-label="`选择 ${row.inboundCode || row.containerNo || '未提供业务编号的货物'}`" :disabled="!canWrite || resolving || (!selected[key(row as PlanningCargo)] && !!reason(row as PlanningCargo))" @change="toggle(row as PlanningCargo, $event)" /></template>
|
|
||||||
<template #eligibility="{ row }">{{ reason(row as PlanningCargo) || '可选择' }}</template>
|
|
||||||
<template #customer="{ row }"><LineClampText :content="row.customerName" /></template>
|
|
||||||
<template #origin="{ row }"><LineClampText :content="row.originWarehouseName" /></template>
|
|
||||||
</DataTable></div>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -105,10 +105,10 @@ onBeforeUnmount(() => { ++generation })
|
|||||||
<ul v-if="coverage?.missingFields.length" aria-label="预约待核实事项"><li v-for="item in coverage.missingFields" :key="item">{{ coverageNeeds[item] || '存在待核实事项,请返回来源详情核对。' }}</li></ul>
|
<ul v-if="coverage?.missingFields.length" aria-label="预约待核实事项"><li v-for="item in coverage.missingFields" :key="item">{{ coverageNeeds[item] || '存在待核实事项,请返回来源详情核对。' }}</li></ul>
|
||||||
<el-form v-if="canWrite && canFollowup" label-position="top" class="followup-form density-form" :disabled="saving || !!pending">
|
<el-form v-if="canWrite && canFollowup" label-position="top" class="followup-form density-form" :disabled="saving || !!pending">
|
||||||
<el-form-item label="跟进事项"><el-select v-model="form.stage"><el-option v-for="(label,value) in allowedStages" :key="value" :value="value" :label="label" /></el-select></el-form-item>
|
<el-form-item label="跟进事项"><el-select v-model="form.stage"><el-option v-for="(label,value) in allowedStages" :key="value" :value="value" :label="label" /></el-select></el-form-item>
|
||||||
<el-form-item label="联系对象"><el-input v-model="form.contactedParty" maxlength="200" /></el-form-item>
|
<el-form-item label="联系对象"><el-input v-model="form.contactedParty" maxlength="200" placeholder="本次联系的车队、码头或仓库" /></el-form-item>
|
||||||
<el-form-item label="下次跟进日期"><el-date-picker v-model="form.followupDate" type="date" value-format="YYYY-MM-DD" placeholder="业务地点当地日期" /></el-form-item>
|
<el-form-item label="下次跟进日期"><el-date-picker v-model="form.followupDate" type="date" value-format="YYYY-MM-DD" placeholder="业务地点当地日期" /></el-form-item>
|
||||||
<el-form-item label="联系结果" required class="wide"><el-input v-model="form.result" type="textarea" maxlength="1000" placeholder="记录对方反馈,不会自动确认预约" /></el-form-item>
|
<el-form-item label="联系结果" required class="wide"><el-input v-model="form.result" type="textarea" maxlength="1000" placeholder="记录对方反馈,不会自动确认预约" /></el-form-item>
|
||||||
<el-form-item label="下一步安排" class="wide"><el-input v-model="form.nextAction" maxlength="500" /></el-form-item>
|
<el-form-item label="下一步安排" class="wide"><el-input v-model="form.nextAction" maxlength="500" placeholder="填写待补资料或下次联系事项" /></el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
<DataTable v-model:page="page" v-model:page-size="size" :data="rows" :columns="columns" :total="total" :loading="loading" :results-visible="!error" :row-key="rowKey" @update:page="load" @update:page-size="page = 1; load()">
|
<DataTable v-model:page="page" v-model:page-size="size" :data="rows" :columns="columns" :total="total" :loading="loading" :results-visible="!error" :row-key="rowKey" @update:page="load" @update:page-size="page = 1; load()">
|
||||||
<template #stage="{ row }">{{ stages[row.stage as FollowupStage] }}</template>
|
<template #stage="{ row }">{{ stages[row.stage as FollowupStage] }}</template>
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ onMounted(load)
|
|||||||
</template>
|
</template>
|
||||||
<el-form v-if="canWrite && detail.impact.status === 'OPEN'" label-position="top" :disabled="saving || !!pending">
|
<el-form v-if="canWrite && detail.impact.status === 'OPEN'" label-position="top" :disabled="saving || !!pending">
|
||||||
<el-form-item label="实际处理结果"><el-input v-model="form.result" type="textarea" maxlength="1000" placeholder="记录已联系、核对或改约的实际结果;此处不会自动改约" /></el-form-item>
|
<el-form-item label="实际处理结果"><el-input v-model="form.result" type="textarea" maxlength="1000" placeholder="记录已联系、核对或改约的实际结果;此处不会自动改约" /></el-form-item>
|
||||||
<el-form-item label="下一步"><el-input v-model="form.nextAction" maxlength="500" /></el-form-item>
|
<el-form-item label="下一步"><el-input v-model="form.nextAction" maxlength="500" placeholder="填写后续处理事项" /></el-form-item>
|
||||||
<el-form-item label="下次跟进日期"><el-date-picker v-model="form.followupDate" value-format="YYYY-MM-DD" /></el-form-item>
|
<el-form-item label="下次跟进日期"><el-date-picker v-model="form.followupDate" value-format="YYYY-MM-DD" /></el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
<div v-if="canWrite && detail.impact.status === 'OPEN'">
|
<div v-if="canWrite && detail.impact.status === 'OPEN'">
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { defineComponent, h, KeepAlive, ref } from 'vue'
|
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
||||||
import AppointmentCalendarView from './AppointmentCalendarView.vue'
|
|
||||||
import { getCalendarSources, getWarehouseArrivals } from './scheduleApi'
|
|
||||||
import { listTripCalendar } from './tripCalendar'
|
|
||||||
vi.mock('vue-router', () => ({ useRoute: () => ({ query: {} }), useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), onBeforeRouteLeave: vi.fn(), onBeforeRouteUpdate: vi.fn() }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => true }) }))
|
|
||||||
vi.mock('./scheduleApi', () => ({ getCalendarSources: vi.fn(), getWarehouseArrivals: vi.fn(), saveWarehouseArrival: vi.fn() }))
|
|
||||||
vi.mock('./tripCalendar', async original => ({ ...await original<typeof import('./tripCalendar')>(), listTripCalendar: vi.fn() }))
|
|
||||||
describe('calendar cache lifecycle', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks()
|
|
||||||
vi.mocked(getCalendarSources).mockResolvedValue({ containers: [], emptyReturns: [], emptyReturnsReadable: true })
|
|
||||||
vi.mocked(getWarehouseArrivals).mockResolvedValue([])
|
|
||||||
vi.mocked(listTripCalendar).mockResolvedValue({ records: [], unresolvedRecords: [] })
|
|
||||||
})
|
|
||||||
it('aborts reads when cached and reloads on return without creating background work polling', async () => {
|
|
||||||
const active = ref(true)
|
|
||||||
const host = defineComponent({ setup: () => () => h(KeepAlive, null, { default: () => active.value ? h(AppointmentCalendarView) : h('div') }) })
|
|
||||||
const wrapper = mount(host, { global: { stubs: { AdminPage: { template: '<main><slot /></main>' }, AppointmentCalendarPanel: { template: '<section />' }, AppDialog: true } } })
|
|
||||||
await flushPromises()
|
|
||||||
expect(getCalendarSources).toHaveBeenCalledTimes(1)
|
|
||||||
const signal = vi.mocked(getCalendarSources).mock.calls[0]![1]!
|
|
||||||
active.value = false; await flushPromises()
|
|
||||||
expect(signal.aborted).toBe(true)
|
|
||||||
active.value = true; await flushPromises()
|
|
||||||
expect(getCalendarSources).toHaveBeenCalledTimes(2)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import CargoVerificationForm from './CargoVerificationForm.vue'
|
|
||||||
import { getCargoVerification, saveCargoVerification, type CargoVerificationContext } from './cargoVerificationApi'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
const permissions = vi.hoisted(() => ({ canWrite: true }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: (permission: string) => !permission.endsWith('fba-appointment') || permissions.canWrite }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
|
||||||
vi.mock('./cargoVerificationApi', () => ({ getCargoVerification: vi.fn(), saveCargoVerification: vi.fn() }))
|
|
||||||
const source = { sourceKey: 'ORDER:9007199254740993', customerId: 'customer-1', destinationKey: 'FBA:ONT8' }
|
|
||||||
const context: CargoVerificationContext = {
|
|
||||||
source: { ...source, orderId: '9007199254740993', inboundCode: 'IN-TEST-001', bookingNo: null, containerNo: 'TEST-CN-001', originWarehouseId: 'warehouse-1', originWarehouseName: '测试仓', destinationWarehouseCode: 'ONT8', packages: null, sourceVersion: null, canFollowup: true, blockReasons: [] },
|
|
||||||
verification: null, allocatedPackages: 0, unknownAllocationCount: 0, effectivePackages: null, availablePackages: null, sourceChanged: false, allowedActions: ['VERIFY_CARGO'], blockReasons: [],
|
|
||||||
}
|
|
||||||
function render() { return mount(CargoVerificationForm, { props: { source }, global: { stubs: { ElButton: { props: ['nativeType'], template: '<button :type="nativeType"><slot /></button>' }, LoadErrorState: { props: ['message'], template: '<div role="alert">{{ message }}</div>' }, ApiErrorMeta: true } } }) }
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks(); permissions.canWrite = true; vi.mocked(getCargoVerification).mockResolvedValue(context)
|
|
||||||
vi.mocked(saveCargoVerification).mockResolvedValue({ version: 1, sourceVersion: null, destinationKey: source.destinationKey, sourcePackages: null, packageCount: 20, shipmentReferences: ['FBA-TEST'], remark: null, operatorName: '测试调度', verifiedAt: '2026-10-15T03:00:00Z' })
|
|
||||||
})
|
|
||||||
it('saves independent cargo verification before any appointment exists, preserving unknown source values', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('待核实'); expect(wrapper.text()).not.toContain('9007199254740993')
|
|
||||||
await wrapper.get('input[type=number]').setValue('20'); await wrapper.get('textarea[aria-label="本票货件号"]').setValue('FBA-TEST\nFBA-TEST')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(saveCargoVerification).toHaveBeenCalledWith(source, expect.objectContaining({ expectedSourceVersion: null, expectedVersion: 0, packageCount: 20, shipmentReferences: ['FBA-TEST'] }))
|
|
||||||
expect(vi.mocked(saveCargoVerification).mock.calls[0]![1]).not.toHaveProperty('appointmentStatus')
|
|
||||||
expect(wrapper.emitted('saved')).toHaveLength(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('uses the same key and payload after an unknown save outcome', async () => {
|
|
||||||
vi.mocked(saveCargoVerification).mockRejectedValueOnce(new Error('network lost'))
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.get('input[type=number]').setValue('20'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const first = vi.mocked(saveCargoVerification).mock.calls[0]![1]
|
|
||||||
expect(wrapper.get('fieldset').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(saveCargoVerification).toHaveBeenNthCalledWith(2, source, first); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('refreshes source conflicts without deleting the entered quantity or shipment numbers', async () => {
|
|
||||||
vi.mocked(saveCargoVerification).mockRejectedValueOnce(new ApiResponseError('原来源已变化', 'A0409', 409))
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.get('input[type=number]').setValue('20'); await wrapper.get('textarea[aria-label="本票货件号"]').setValue('FBA-KEEP')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(getCargoVerification).toHaveBeenCalledTimes(2)
|
|
||||||
expect((wrapper.get('input[type=number]').element as HTMLInputElement).value).toBe('20')
|
|
||||||
expect((wrapper.get('textarea[aria-label="本票货件号"]').element as HTMLTextAreaElement).value).toBe('FBA-KEEP'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('blocks invalid allocation bounds and denies writes for list-only users', async () => {
|
|
||||||
vi.mocked(getCargoVerification).mockResolvedValue({ ...context, source: { ...context.source, packages: 50 }, allocatedPackages: 30, availablePackages: 20 })
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.get('input[type=number]').setValue('20'); await wrapper.get('form').trigger('submit')
|
|
||||||
expect(saveCargoVerification).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
permissions.canWrite = false; const denied = render(); await flushPromises()
|
|
||||||
await denied.get('form').trigger('submit'); expect(saveCargoVerification).not.toHaveBeenCalled(); denied.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import './appointmentNativeForms.css'
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import InlineHelp from '@/shared/components/InlineHelp.vue'
|
|
||||||
import { computed, onMounted, reactive, ref } from 'vue'
|
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import { getCargoVerification, saveCargoVerification, type CargoVerificationContext, type CargoVerificationSource, type SaveCargoVerification } from './cargoVerificationApi'
|
|
||||||
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
|
|
||||||
const props = defineProps<{ source: CargoVerificationSource }>()
|
|
||||||
const emit = defineEmits<{ saved: [] }>()
|
|
||||||
const access = useAccessPreviewStore()
|
|
||||||
const context = ref<CargoVerificationContext | null>(null), loading = ref(false), saving = ref(false)
|
|
||||||
const error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null), pending = ref<SaveCargoVerification | null>(null)
|
|
||||||
const form = reactive({ packages: '', references: '', remark: '' }), baseline = ref(JSON.stringify(form))
|
|
||||||
const dirty = computed(() => JSON.stringify(form) !== baseline.value)
|
|
||||||
useWorkDraft(dirty, computed(() => saving.value || !!pending.value))
|
|
||||||
const canWrite = computed(() => access.can('platform:overseas-warehouse:inbound-order:fba-appointment') && context.value?.allowedActions.includes('VERIFY_CARGO'))
|
|
||||||
async function load(preserve = false) {
|
|
||||||
loading.value = true; error.value = null
|
|
||||||
if (!access.can('platform:appointment:list') || !access.can('platform:overseas-warehouse:last-mile-order:list')) { error.value = { message: '当前账号没有该货源的读取权限,请联系预约负责人处理。' }; loading.value = false; return }
|
|
||||||
try {
|
|
||||||
context.value = await getCargoVerification(props.source)
|
|
||||||
if (!preserve) {
|
|
||||||
const record = context.value.verification
|
|
||||||
Object.assign(form, { packages: record?.packageCount == null ? '' : String(record.packageCount), references: record?.shipmentReferences.join('\n') || '', remark: record?.remark || '' })
|
|
||||||
baseline.value = JSON.stringify(form)
|
|
||||||
}
|
|
||||||
} catch (cause) { error.value = getApiErrorDetails(cause, '核实资料读取失败') }
|
|
||||||
finally { loading.value = false }
|
|
||||||
}
|
|
||||||
async function save() {
|
|
||||||
if (!context.value || !canWrite.value || loading.value || error.value || saving.value) return
|
|
||||||
if (!pending.value) {
|
|
||||||
const count = String(form.packages).trim() ? Number(form.packages) : null
|
|
||||||
if (count !== null && (!Number.isSafeInteger(count) || count < 1)) { ElMessage.warning('核实箱数须为正整数,暂未核实可留空'); return }
|
|
||||||
if (count !== null && (count < context.value.allocatedPackages || (context.value.source.packages != null && count > context.value.source.packages))) { ElMessage.warning('核实箱数不能低于已分配量,也不能超过已知原箱数'); return }
|
|
||||||
const references = [...new Set(form.references.split(/\r?\n/).map(value => value.trim()).filter(Boolean))]
|
|
||||||
if (references.length > 100 || references.some(value => value.length > 128)) { ElMessage.warning('最多填写100条货件号,每条不超过128字'); return }
|
|
||||||
pending.value = { destinationKey: context.value.source.destinationKey, expectedSourceVersion: context.value.source.sourceVersion, expectedVersion: Number(context.value.verification?.version || 0), packageCount: count, shipmentReferences: references, remark: form.remark.trim() || null, idempotencyKey: crypto.randomUUID() }
|
|
||||||
}
|
|
||||||
saving.value = true; saveError.value = null
|
|
||||||
try {
|
|
||||||
await saveCargoVerification(props.source, pending.value)
|
|
||||||
pending.value = null; baseline.value = JSON.stringify(form)
|
|
||||||
ElMessage.success('核实资料已保存,原订单与预约状态保持不变'); emit('saved'); await load()
|
|
||||||
} catch (cause) {
|
|
||||||
saveError.value = getApiErrorDetails(cause, '保存结果待确认,请重试本次保存')
|
|
||||||
if (rejectedCommand(cause)) { pending.value = null; await load(true) }
|
|
||||||
} finally { saving.value = false }
|
|
||||||
}
|
|
||||||
onMounted(() => load())
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section aria-label="货物核实资料">
|
|
||||||
<h3>核实货物资料<InlineHelp title="核实资料说明"><p>未约成也可保存;只用于预约核实,保留原订单资料。</p></InlineHelp></h3>
|
|
||||||
<LoadErrorState v-if="error" title="核实资料读取失败" :message="error.message" :loading="loading" @retry="load(true)"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<p v-if="loading">正在读取货物资料…</p>
|
|
||||||
<template v-if="context">
|
|
||||||
<dl class="cargo-facts"><dt>原票</dt><dd>{{ context.source.inboundCode || context.source.bookingNo || '—' }}</dd><dt>目的仓</dt><dd>{{ context.source.destinationWarehouseCode || '—' }}</dd><dt>原箱数</dt><dd>{{ context.source.packages ?? '待核实' }}</dd><dt>已分配</dt><dd>{{ context.allocatedPackages }} 箱<span v-if="context.unknownAllocationCount">;另有 {{ context.unknownAllocationCount }} 项数量未知</span></dd><dt>可分配</dt><dd>{{ context.availablePackages ?? '待核实' }}</dd></dl>
|
|
||||||
<p v-if="context.sourceChanged" role="alert">原货源已变化,请核对当前原票和已分配量后重新保存。</p><p v-for="reason in context.blockReasons" :key="reason" role="status">{{ reason }}</p>
|
|
||||||
<form class="density-form work-form appointment-native-form" @submit.prevent="save"><fieldset :disabled="!canWrite || loading || !!error || saving || !!pending">
|
|
||||||
<label>核实箱数(可暂不填)<input v-model="form.packages" type="number" min="1" step="1" aria-label="核实箱数" class="workbench-input"></label>
|
|
||||||
<label>本票货件号 / 追踪号(每行一个)<textarea v-model="form.references" rows="4" aria-label="本票货件号" class="workbench-input" /></label>
|
|
||||||
<label>核实说明<textarea v-model="form.remark" maxlength="1000" rows="2" class="workbench-input" /></label>
|
|
||||||
</fieldset><p v-if="!canWrite">当前仅可查看核实资料;需核实权限及有效货源资格才能保存。</p>
|
|
||||||
<LoadErrorState v-if="saveError" title="核实资料未保存" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState>
|
|
||||||
<div class="density-actions density-actions--footer appointment-form-actions"><el-button type="primary" native-type="submit" :loading="saving" :disabled="!canWrite || loading || !!error">{{ pending ? '重试本次保存' : '保存核实资料' }}</el-button></div></form>
|
|
||||||
</template>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
<style scoped>
|
|
||||||
.cargo-facts { display: grid; grid-template-columns: 80px 1fr; gap: var(--admin-space-3); }.cargo-facts dd { margin: 0; overflow-wrap: anywhere; }.cargo-facts dt { color: var(--el-text-color-secondary); }
|
|
||||||
</style>
|
|
||||||
@@ -1,285 +1,45 @@
|
|||||||
# 预约工作日历逐操作矩阵
|
# 预约管理交互矩阵
|
||||||
|
|
||||||
## 2026-10-21 排车候选分页
|
原型:用户提供 `C:/Users/BY-OY/Desktop/新版.html` 的 `page-appointment-calendar`、`modal-appointment-edit`、`renderAppointmentCalendar`、`renderAppointmentDay`、`openAppointmentModal`、`deleteAppointment`,以及本对话三张截图。
|
||||||
|
|
||||||
| 页面/组件 | 操作与承载依据 | 本次调整 | 验收 |
|
用户确认:同一目的仓允许多个客户货物统一预约、统一送仓,不能按客户拆预约。客户隔离保留在货物明细。
|
||||||
|---|---|---|---|
|
|
||||||
| WorkDispatchForm | 保留既有预约事项深链内的表单、批次范围与整车草稿流程;现行排车契约第17项候选分页 | 表下分页仅请求当前页;说明总数为关联计划候选数,表格仅显示本批货物;跨页保留选择和原批次版本,完整组/来源版本变化阻止建单 | 定向自动检查单独记录;1920×1080、100%待人工截图确认 |
|
|
||||||
|
|
||||||
## 2026-10-20 日期时间组件统一(当前确认)
|
| 页面/操作 | 原型承载与布局 | 实现约束 |
|
||||||
|
|
||||||
依据:用户截图 `codex-clipboard-ed442cca-1bd2-43d3-87e8-6671e5bcc508.png`,以及随后明确要求排查并优化同类原生日期输入。保留现有业务入口与承载方式,使用 Element Plus 日期/时间控件及已有公共表单样式。
|
|
||||||
|
|
||||||
| 页面/组件 | 操作与承载 | 本次调整 | 验收 |
|
|
||||||
|---|---|---|---|
|
|
||||||
| AppointmentCalendarView | 调整计划到仓,原520px居中弹框及全屏能力 | 1处日期时间选择器;分钟精度沿用原请求格式;标签宽度150px,说明图标与标签并排,控件沿用公共满宽样式 | 真实浏览器检查通过:日期面板、选值、空值禁用、全屏保值、未保存保护及放弃返回;未提交业务保存 |
|
|
||||||
| WorkReceivingPanel | 原业务深链中的客户计划、后送与跟进,原表单 | 5处日期/日期时间输入;日期与秒精度的当地时间分别保存;调整开始/结束时段后仍清除原时差依据 | 自动检查通过;待人工截图确认 |
|
|
||||||
| WorkCommandForm | 跟进、收货要求,原表单 | 3处日期、2处时间输入;跨日结束日期显式保留;不推断次日、不转换地点时区 | 自动检查通过;待人工截图确认 |
|
|
||||||
| AppointmentBatchForm | 原分批/合并表单 | 2处可空目标日期,保留跨批分配、版本、幂等与原写权限 | 自动检查通过;待人工截图确认 |
|
|
||||||
|
|
||||||
共4组件13处。日期使用 `el-date-picker`,时间使用 `el-time-picker`;保留原权限、处理中及未知结果锁定、清空与未保存保护。新增控件显式接收原禁用条件,宽度复用 `density-form`,不新增全局日期控件外观规则。
|
|
||||||
|
|
||||||
自动验证:受影响7个测试文件88项通过;类型检查与生产构建通过。全量回归执行464个文件4203项,4201项通过,两项旧公共样式断言(标签宽度、追加样式类)更新后,该样式文件65项全部复验通过。后台业务模板原生日期/时间控件残留检查通过。本轮未部署TEST,未进行真实HTTP或人工页面截图验收。
|
|
||||||
|
|
||||||
补充浏览器验收:用户明确要求打开页面后,使用已发布TEST页面,页面报告1920×1080、DPR1、visual scale1。TSTU5446539的默认计划、Element日期面板、快捷选值、全屏保值、清空禁用、未保存保护与放弃返回通过;原计划仍2026-10-01,未点击保存。MSCU7264017现已有入库计划,按冻结时间显示且无调整入口。本轮仅覆盖日历与调整到仓弹框,其余三表单仍待逐页操作;输入09:30的最终确认未单独完成,不计通过。证据见 `.logs/appointment-element-release-20261020/ui/result.json` 及同目录截图。
|
|
||||||
|
|
||||||
## 2026-10-20 蓝白工作台续批(写权已协调)
|
|
||||||
|
|
||||||
本次续批修改文件(相对本模块):
|
|
||||||
|
|
||||||
- `AppointmentBatchForm.vue`
|
|
||||||
- `AppointmentCalendarPanel.vue`
|
|
||||||
- `AppointmentCalendarView.vue`
|
|
||||||
- `AppointmentCreatePanel.vue`
|
|
||||||
- `ReceivingScope.vue`
|
|
||||||
- `SourceAppointmentPanel.vue`
|
|
||||||
- `TripAppointmentPanel.vue`
|
|
||||||
- `WorkDetailPanel.vue`
|
|
||||||
- `WorkReceivingPanel.vue`
|
|
||||||
|
|
||||||
总控已核实预约交付及排车只读预审状态,本轮授权续接展示;逐文件按当前内容快照核对后写入。依据蓝白样板与本矩阵既有逐操作承载。
|
|
||||||
|
|
||||||
| 实际入口 | 操作/承载与冻结结论 | 验收 |
|
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 预约日历主页面及原业务深链的实际表单、工作详情;保留四类、月周日期与原弹框承载 | 只接入主题、公共列表/面板和局部旧外观清理;尺寸、字段、事件、权限、请求及业务计算保留 | 续批定向回归通过;待人工1920×1080、100%截图确认 |
|
| 补充计划时段 | 用户2026-10-12新增预约截图:开始、结束时段输入框各占整行过长 | 共用 FbaAppointmentFields 的补充区域沿用三列网格,计划开始、结束时段同排各占一列,与主字段对齐;夏令时说明整行、两个时差输入同排。日历新增/编辑、合批安排、入仓单预约同步生效;字段语义及保存不变,待人工截图确认 |
|
||||||
|
| 预约补充记录入口 | 用户2026-10-12截图1:原顶部未定时安排、取消记录两行默认折叠文字要求优化 | 用户2026-10-12后续确认覆盖页内展开方案:入口并入日历工具栏,与数据提示同组;未定时安排1000px、取消记录1160px居中弹框,保留独立分页及错误重试,取消记录仅打开时加载。新增预约紧邻日历标题,月/周及日期操作连续排列 |
|
||||||
|
| 送仓与排车货源页签 | 用户2026-10-12截图2、3:参考尾程订单下划线页签 | 头程货物、外接货物通过同一局部页签组件复用 density-status-tabs,两种模式均放入表格 filters 的 integrated-query-group 内并紧邻搜索;点击及方向键/Home/End切换,保留跨货源选择;新增、编辑、取消预约沿用原承载方式。待人工1920×1080、100%截图确认 |
|
||||||
续批验证:81个文件671项定向回归首轮669项通过,出车图表两项旧颜色期望按公共主题更新后,所属1文件5项复验通过;50个修改Vue模板与局部样式编译通过。写前、写后快照核对未发现外部漂移;所有事件/表单绑定、非图表业务脚本保留,图表仅接入配色/字体/tooltip主题。未改API、日期计算、driver、权限、状态与路由。类型检查、全量测试和构建由总控统一执行;截图均待人工确认。
|
| 预约列表 | 左侧月/周日历,右侧选中日期详情 | 保留双栏日历;到港蓝色、送仓绿色,区分预计/实际到港 |
|
||||||
|
| 新增预约 | 居中表单,按用户简化要求使用1080px三列 | 仓库远程搜索并自动加载货物;主区保留计划日期、登记阶段及可选备注。系统单号自动生成,不要求外部约号和预计装车时间;计划时段收至补充信息。选择“已取得对方正式确认”才展开外部号和确认时段,并显示地点时区 |
|
||||||
当前无正式入口引用的11个旧面板保留原样:AppointmentCancellationDialog、AppointmentCancellationHistory、AppointmentCancellationRecords、AppointmentCargoPanel、AppointmentCargoTabs、AppointmentContainerPanel、AppointmentExternalCandidates、AppointmentFollowupDialog、AppointmentImpactDialog、AppointmentInboundCodes、WorkCalendarPanel。不是新增或恢复入口;TripAppointmentPanel仍由正式车次详情引用,已纳入本次续批。
|
| 编辑预约 | 复用居中表单 | 与入仓单共用记录;版本校验;真实货物归属不允许手填更改 |
|
||||||
|
| 到港详情 | 当天安排右侧只读 | 使用货柜/船节点事实,无逐行详情请求,无模拟到港数据 |
|
||||||
## 2026-10-20 排车入口收敛
|
| 取消预约 | 二次确认 | 显式提示全部货物释放占用、历史保留;沿用独立权限,已关联有效排车时先处理运输安排,不能自动回退库存 |
|
||||||
|
| 月/周切换 | 顶部切换与前后按钮 | 周模式按7天移动,修正原型仍按月移动的问题 |
|
||||||
用户指出预约日历仍跳旧车次详情。排车标签改用服务端关联真实整车主单返回的排车单号,打开 `/overseas-warehouse/dispatches/:dispatchNo` 独立排车详情;返回按钮显示“返回预约日历”并保留原日期与月/周视图。无合法日历返回参数时继续走原列表或拼车登记返回逻辑,外部返回地址拒绝。读取权限与排车列表一致,不要求旧车次列表权限;独立旧车次、取消排车主单不进入活动日历,不按TR号猜DS号。原四类、地点日期和实际发车归属规则保持。自动检查与发布/真实HTTP分别记录,1920×1080、100%人工操作截图待确认。
|
| 多条安排 | 日历标签、右侧明细 | 月/周日格均最多显示3条,超出显示“还有N条”,悬停显示当天总数;日格固定高度,右侧全部展示并独立滚动 |
|
||||||
|
| 多入仓码 | 用户2026-10-09补充截图:单预约20票导致两列详情被长字符串撑高 | 右侧卡片与编辑弹框共用独立整行入仓码列表;去空去重后显示总数,默认3条,长码悬停可读全文;超过3条可展开/收起,展开后216px内独立滚动并可键盘聚焦,不拼成长段文字 |
|
||||||
自动验证:相关3文件42项、Admin全量453文件4086项、类型检查与生产构建通过;后端最终常规Maven流程完成生产/测试源码编译,`FleetTripCalendarServiceTest`及真实H2查询的`FleetTripCalendarMapperTest`共9项通过,覆盖真实排车号与内部车次号不同、独立旧车次/取消主单/取货排除、跨日期和查询上限。Gateway路由合同5项通过。均经共享`local-check.ps1`执行;早先其他自有业务在途编译错误及失效生成物尝试不作为通过证据,以最终常规Maven回归为准。接口路径复用、无网关配置或数据库结构变更,匹配发布单元为Admin与Lastleg。
|
| 在途货物及外接来源跟进 | 美国预约统一方案的提前联系需求 | 日历与已开船FBA列表切换;跟进在居中1080px弹框中承载,3列表单、联系结果及下一步整行,历史分页;BOOKING深链先由服务端核对,再展示原登记及真实预约缺项 |
|
||||||
|
| 整柜提柜与接仓 | 美国预约统一方案的整柜共享事项 | 独立工作视图按柜汇总,操作列左置;接仓点在行内分组,点击后共用1080px跟进弹框。整柜只选拖车/码头事项,接仓只记录对应仓库,单票只记录FBA联系;数量未知或范围不完整明确显示,不按客户复制整柜联系。首次只请求一页整柜数据,详情按点击读取;待1920×1080页面验收 |
|
||||||
## 2026-10-19 四类日历恢复(当前结论)
|
| 在途跨客户合批安排 | 美国预约统一方案的同起运仓、同目的仓合批 | 操作列后选择同起运仓及同目的仓,跨页累计最多100票;批量核对后在1080px弹框填写与入仓入口共用的安排表单。未知箱数保留待核实;暂扣、多目的地和已有预约不可选入。保存必须重新核对,未知结果保留同一命令供重试 |
|
||||||
|
| 外接货进入合批 | 同仓跨客户共用预约,不因未入仓而只允许跟进 | 后端核实BOOKING深链后,“加入预约合批”进入现有合批工作区,再显式加入选择;可与同起运仓/目的仓头程货混选,保留原BOOKING键与未知箱数。跨仓不清空已有选择,已有关联预约不再开放新增入口;切换日历/合批工作视图保留本页选择,外接选择默认折叠、展开216px内滚动 |
|
||||||
依据:用户本轮确认四类与日期规则,以及截图 `C:/Users/BY-OY/AppData/Local/Temp/codex-clipboard-840bcc07-6b54-4afa-9dc7-666d09ff04f2.png`。当前结论覆盖下文旧工作台首页/明细承载描述;原业务写入规则仍按正式业务契约。
|
| 完整外接候选 | 统一方案第九节两类货源均可筹划、合批及核对覆盖 | 在同一合批工作区切换头程/外接来源列表,外接按服务端分页、关键词筛选,展示原登记、客户、车次、接仓点、目的仓、可空箱数及预约覆盖。加入选择复用原100票合批选择与保存弹框;查看跟进沿用原弹框,不新增预约数据副本。切换来源保留选择,未打开外接列表不请求;待1920×1080验收 |
|
||||||
|
| 未定时安排 | 总览不得伪造时段 | 日历上方独立折叠分页列表;日期未定不补零点或09点,继续编辑仍操作原系统单号;仅有计划日期时日历显示日期,不生成确认时段 |
|
||||||
| 页面 | 操作 | 当前确认承载与布局 | 实现结论 |
|
| 提柜日历 | 美国业务预约统一总览 | 读取原码头提柜预约,一柜一条,点击查看来源进入清关提柜详情;按美国目的仓确认业务范围,不等于确认港口国家。保留原业务日期,明确港口时区待核实,不套用目的仓时区;未知目的仓及截断显示统计不完整。无提柜权限不请求该来源并提示范围缺失 |
|
||||||
|---|---|---|---|
|
| 用车计划日历 | 统一总览的真实车次只读来源 | 一车一条,计划与实际出发分开,司机预计结束不当送货完成。查询一次带跨时区余量的UTC窗口,按起运仓地点时区筛回42个当地日;缺国家/时区的记录独立分页待核实,不放入每日格。路线最多3站摘要,完整路线进入原车次;不请求逐车详情,不在预约页创建车次或重算余位 |
|
||||||
| 预约列表 | 月/周、四类选择、当前范围搜索 | 左日历右当天安排;日期格简洁标签,最多三条 | 恢复 `AppointmentCalendarPanel`,不再打开全局工作明细弹框;待人工截图确认 |
|
| 来源失败 | 统一方案的部分结果规则 | 日历保留成功来源并提示不完整;深链解析失败不打开假来源;跟进版本加载失败禁止保存,未知提交结果保留原请求供重试 |
|
||||||
| 预约列表 | 月视图周数 | 用户截图 `codex-clipboard-372a5dc5-0c82-4298-93db-089b6c97c8ca.png`;周一至周日,只覆盖当月所需完整周 | 4/5/6周自适应;2026年10月五周,保留末周11月1日,不追加11月2—8日整周;待人工截图确认 |
|
| 船期变化影响与处理 | 统一方案第十节场景16,旧/新预测、下游影响、负责人及结果闭环 | 并入提柜与到仓的货柜列表,不设第四工作视图;行内处理船期变化,本页待办计数明确标识范围;显式本页批量核对,不逐柜轮询。1200px居中详情展示直接货物/预约、关联车次与同车待复核承诺;各明细220px内滚动,历史服务端分页。认领及结果表单复用现有控件;未知提交保留原命令并禁止关闭,已确认预约不因核对动作改变。待1920×1080真实验收 |
|
||||||
| 预约列表 | 查看当天、未定日期 | 固定右侧区域,完整业务字段与滚动明细 | 类型仅到港、排车、还柜、计划到仓;待人工截图确认 |
|
|
||||||
| 预约列表 | 新增预约 | 用户本轮要求恢复顶部按钮,随后确认先支持FBA;1080px居中弹框,先选择已有货物,再登记预约时间 | 复用真实来源预览及预约保存流程,原权限/幂等/未保存保护;保存成功显示预约编号和只读内容;普通客户仓不在本次范围;待人工截图确认 |
|
结束时间未明确时允许为空。系统单号、外部确认号、计划时段及确认时段保持不同语义。日历范围最多42天,每次范围变化查询预约、到港及有权限的提柜、车次来源各一次;未定时列表独立分页,选中日期不发送请求。候选选仓后自动分页读取,跨页选择保留;换仓清空旧选择并丢弃旧请求,清空仓库不查货。时区由目的仓主档核实,夏令时重叠明确时差,不凭浏览器时区猜测。仓库请求失败可重试;只展示前50个匹配仓,超出提示缩小关键词。
|
||||||
| 新增FBA送仓预约 | 按目的仓查询 | 用户截图 `codex-clipboard-44b338fe-af49-45e2-abf2-3bc0bd27224a.png`;在原查询栏增加可搜索、可清空的目的FBA仓下拉框 | 选项使用同货物查询权限的权威美国FBA目录;提交查询后从第一页按目的仓过滤,翻页沿用条件;待人工截图确认 |
|
|
||||||
| 预约列表 | 审核、删除 | 不恢复通用入口 | 在原业务处理,不在日历改业务状态 |
|
本轮视觉验收:待人工1920×1080截图确认。
|
||||||
| 计划到仓 | 调整 | 原居中弹框保留,小型时间表单 | 整柜原命令、原权限/版本/幂等与计划冻结门禁;待人工截图确认 |
|
|
||||||
| 到港、排车、还柜 | 查看与办理 | 跳原货柜/车次正式详情页 | 保留日期/月周返回上下文,无独立工作流程导航 |
|
视觉验收目标为1920×1080、100%缩放。该矩阵描述设计和代码边界,不代替测试环境浏览器验收证据。
|
||||||
| 原业务深链 | 精确来源/事项办理 | 仍使用既有居中原业务表单 | 只承接其他模块实际使用的精确入口,不恢复全局工作待办;待人工截图确认 |
|
|
||||||
|
按用户确认收敛:主视图仅提柜与到仓、送仓与排车、预约日历,默认有权限的列表视图;日历首次进入才加载。到港参考、用车计划默认隐藏,可独立开关,不计入预约数量;缺国家资料与查询超限分开提示。送仓与排车目前仍以选货合批为主,目的仓货量汇总及7/14/30天窗口尚未完成,不因标题调整宣称完成。
|
||||||
2026-10-19 目的FBA仓筛选补修:原查询栏增加可搜索、可清空的下拉框,首次展开读取完整权威美国FBA目录;复用原货物读取权限,不新增仓库管理权限。查询回第一页,翻页沿用目的仓条件,重置清除条件;选项失败独立提示并可重试,不隐藏已加载货物或伪装为空结果。预约模块37文件/276项及生产构建(含类型检查)通过,Gateway路由合同5项通过。后端生产源码编译通过,本次两个测试文件单独javac编译并经Surefire执行13项通过;常规Maven流程仍被派送模块三份测试中的5项编译错误阻挡,不能据定向结果宣称后端完整门禁通过。Admin全量405文件/3388项通过、1项输入提示合同失败,原因是其他在途运输单表单的7个输入框缺少placeholder;单独复查相同失败,未修改其他模块。日志为`.logs/appointment-destination-{test,build,full-test,placeholder-check}.log`,后端为同名前缀的`route`、`backend`、`javac`及`targeted-backend`日志。本补修未提交或部署,人工1920×1080/100%视觉待确认。
|
|
||||||
|
用户截图密度修正:业务标题复用density-detail-title并与三视图同行,不独占大标题区;船期操作并入查询栏,不单独占空白工具栏。常驻业务解释改为默认折叠“说明”;错误保留重试,诊断信息默认折叠。基础货柜与船期状态独立读取,后者失败不阻断货柜列表、不展示假的零待办。
|
||||||
2026-10-19 新增FBA预约入口补修:顶部按钮要求原FBA预约写权限及尾程订单列表权限,点击后才读取候选;支持同起运仓、同目的仓的跨客户货物选择,核对最新真实来源后复用原创建表单。未知结果保留原请求并阻止关闭/返回,成功后移除创建表单、显示真实预约编号和只读内容,刷新原日历;不生成虚拟车次或第五类日历。本次已明确普通客户仓暂不加入。
|
|
||||||
|
用户最新截图确认:移除“美国预约总览”文字,仅保留三视图导航;日历图例和图层开关归入有内边距的辅助栏,长范围提示默认折叠,月格112px仍容纳3条摘要及剩余数;右侧固定360px,系统单号/完整时段/备注跨整行。该项以当前用户要求覆盖原标题建议,待1920×1080实际页面确认。
|
||||||
验证:新增入口直接5文件/59项通过;`pnpm build`含类型检查通过,仅既有AnalyticsChart大分块提示。工作区首次全量为405文件/3385项通过、1项排车详情布局合同失败,后续该项单独6项复查通过;再次全量出现9文件/11项失败(以5秒超时为主),在不修改超时阈值和其他业务代码的情况下,以2个工作进程复查整个预约模块、密度及上述全部失败文件,47文件/385项全过。不将这些分次结果记录为单次全量绿灯。证据为`.logs/appointment-create-{focused-final,build,full-test,full-test-final,layout-recheck,bounded-recheck}.log`。额外临时候选核对未作为通过证据;工作区其他业务在途修改保留。本次未提交、发布或新增真实业务记录,人工1920×1080/100%视觉待确认。
|
|
||||||
|
用户最新确认覆盖默认列表建议:预约日历排第一并默认打开,之后为提柜与到仓、送仓与排车;范围资料提示移入日历工具栏“数据提示”,点击展开浮层,不在日历上方占行。真实接口错误仍保留错误与重试入口。
|
||||||
2026-10-19 月视图周数补修:按月实际周数生成日期格,并同步查询开区间;覆盖2026年10月五周、跨年五周、完整二月四周与确需六周的八月。Admin全量405文件/3375项、类型检查及生产构建通过,`git diff --check`通过;仅既有AnalyticsChart大分块提示。本补修尚未提交或发布,人工视觉待确认;证据为`.logs/appointment-calendar-month-weeks-{test,build}.log`。
|
|
||||||
|
用户确认待核实车次不占日历顶部:入口并入“数据提示”,显式点击后打开1000px居中分页明细;保留原UTC、缺项及查看来源操作,未打开不渲染明细,不增加查询;日期范围变化关闭旧明细。
|
||||||
2026-10-19 发布候选检查:Admin全量405文件/3372项通过,定向输入提示、弹框密度及取货组件4文件/35项通过;`pnpm build`(含类型检查)通过,仅既有AnalyticsChart大分块提示。新增日历后端直接测试及受影响SQL、API、权限合同通过,Gateway路由/部署拓扑/回滚合同与Mapper注册合同通过。
|
|
||||||
|
|
||||||
发布检查中发现的既有问题已在本候选最小修正:调拨新增箱数和取货输入提示、取货弹框密度、尾程贴标文件页签结构与对应断言;取货测试Bean及API数量断言;国内空库SQL中误放的五张海外取货表归回海外空库基线,并同步现行车次用途字段和基线表数。这些仅修改源码基线,不对运行环境执行SQL。
|
|
||||||
|
|
||||||
本次发布单元为Admin、Firstleg、Lastleg;新增两个只读日历接口复用现有Gateway通配路由,日历功能不新增数据库结构。环境发布与真实HTTP结果只维护在`docs/测试环境单机部署与配置契约.md`。人工视觉待用户在1920×1080、100%缩放下截图确认。
|
|
||||||
|
|
||||||
2026-10-16 本次 UI 检查:用户重新要求检查后,运行 Admin 全量测试,397 文件 / 3292 项通过;发现并修正 QueryToolbar 必填 `ariaLabel` 属性的模板写法。补充真实 KeepAlive + Teleport 离开/恢复及点击提醒弹层回归后,最新定向检查 3 文件 / 66 项通过,最终 `pnpm typecheck`、`pnpm build` 和 `git diff --check` 通过。构建仍有既有 AnalyticsChart 约 588 kB 分块提示。此记录更新下文历史“未运行验证”的结论;本地自动检查不代表测试环境或人工视觉验收。所属客户显示缺项仍待后端合同补齐,INP 采集报错的脚本来源未确认,本次未部署。日志为 `.logs/appointment-ui-current-{test,focused,typecheck,build}.log`。
|
|
||||||
|
|
||||||
本轮依据:`C:/Users/BY-OY/.codex/visualizations/2026/10/14/01a13a8d-e968-7962-906b-1a514792d921/appointment-calendar-guided.html`(V13,SHA-256 `61902e410be755aa9cbf9fcfaa9d393bfa49dd8d592cd8773af5396e78c29836`)及 `docs/海外仓业务/预约工作日历V13变更说明.md`、开发协作契约。保留既有日历和居中弹框优化,不改变原业务实际执行入口。
|
|
||||||
|
|
||||||
本次密度调整依据:用户提供的主页面截图 `codex-clipboard-93984795-68cb-4082-96b3-c83189d8a357.png`、展开明细截图 `codex-clipboard-a98edd3b-82af-4f1b-989e-7d0f028e0965.png`,以及用户确认的压缩留白、日期定位、控件统一、零值弱化和统计范围说明。
|
|
||||||
|
|
||||||
2026-10-16 操作列样式核对:用户截图 `codex-clipboard-9d54345c-c9c1-4991-82ba-b319948f781b.png` 明确要求与外层表格统一。
|
|
||||||
|
|
||||||
| 页面 | 操作 | 截图依据与布局 | 当前实现 | 本轮结论 |
|
|
||||||
|---|---|---|---|---|
|
|
||||||
| 预约工作明细表格 | 查看详情或服务端提供的下一步操作 | 操作列内蓝色普通文字,无边框、底色或装饰图标 | `RowActions` 默认描边样式 | 使用公共 `text-actions` 模式,保留当前文案、权限、点击承载和长文案换行;待人工截图确认 |
|
|
||||||
|
|
||||||
2026-10-16 当前承载调整:用户反馈“点击外面关闭不了,也看不清”。日期/类型/全局明细、事项详情、原侧边编辑表单和到港参考统一改用带遮罩的居中 `AppDialog`,常规宽度 1120px、高度 88dvh,支持全屏;标题与分页固定、仅正文滚动。遮罩、Esc 和关闭按钮统一经过未保存/提交结果待确认保护。此结论优先于下表早期侧边承载描述;原业务独立页面跳转、确认流程和统计口径保持原样。改后待人工截图确认。
|
|
||||||
|
|
||||||
V13 日历布局:按已确认定高要求,月日格固定 146px,周日格固定 270px;只展示五类服务端计数和独立到港参考,不追加逐事项卡片、不依明细条数扩高。替代下表早期“随内容自然增高”的结论;不裁掉五类入口,仍需人工核对 1920×1080、100% 下完整内容。
|
|
||||||
|
|
||||||
## V13 前端本轮最终收口(2026-10-16)
|
|
||||||
|
|
||||||
已完成 cargo-refresh 按客户最新资料预览/明确采用、60+40 原排车单共车续办,以及原车当前/历史稳定批次引用。当前合同与具体范围以下述对应章节为准,早期分批检查数字仅为过程记录。
|
|
||||||
|
|
||||||
- 最新完整受影响组合:41 文件、357 项通过(18.64 秒),覆盖全部 appointment-calendar、Fleet trips API/页面/安排/交接、排车预排/详情/列表及密度合同。
|
|
||||||
- 全量前端 `pnpm test`:397 文件、3290 项通过(137.44 秒),无失败;存在既有 Vue const reactive v-model 编译提示,本批未扩展修改无关模块。
|
|
||||||
- 最终 `pnpm typecheck` 通过;`pnpm build`(另含 vue-tsc)通过,Vite 16.24 秒,仅既有 AnalyticsChart 588.19 kB 分块警告。`git diff --check` 通过。
|
|
||||||
- 本地日志:`.logs/appointment-v13-final-combined.log`、`appointment-v13-final-full-test.log`、`appointment-v13-final-typecheck.log`、`appointment-v13-final-build.log`;冻结文件与 SHA-256 清单为 `.logs/appointment-v13-frontend-freeze.json`。日志为本地证据,不提交。
|
|
||||||
- 本轮前端冻结;没有提交、推送、部署、SQL 或真实 HTTP。人工 1920×1080、100% 截图与真实 60+40 装载、客户移出后重进、后送 40/20、cargo-refresh 持久事实仍待总控组织验收。后端客户间 FAILED/PENDING 排车资格隔离由总控收口,不改变本轮前端合同。
|
|
||||||
|
|
||||||
## V13 第一批实现与接口依赖
|
|
||||||
|
|
||||||
### 本批收货覆盖合同接入
|
|
||||||
|
|
||||||
已按生产者 `FbaReceivingContracts.java`、`FbaReceivingController.java`、`FbaReceivingService.java` 和 `appointment-receiving-v1.yaml` 接入 `receivingApi.ts`,浏览器前缀为 `/platform/v1/last-leg/appointment-receiving`(公共 HTTP 层统一提供 `/api`)。真实入口如下:
|
|
||||||
|
|
||||||
- GET `/batches/{batchKey}` 和 `/agreements/{agreementKey}`:读取批次、当前覆盖、待确认变化、车辆范围版本及重约 eligible/excluded。
|
|
||||||
- POST `/changes` 和 `/changes/{changeKey}/resolve`:逐来源先送 0..当前量,持久 WAITING;明确回复 CONFIRM 或撤回 WITHDRAW。保留原批次/来源/核实/transport 版本,未知结果重试原幂等命令。
|
|
||||||
- POST `/bookings`:一份共同 booking 或每成员独立 booking,沿用当前批次,不新建货物;取消组携带原 agreementKey/version,只提交 eligible 成员。
|
|
||||||
- POST `/agreements/{agreementKey}/reschedule`、`/cancel`:展示整份当前范围,提交真实范围版本;取消需要 delete 权限及二次确认,普通编辑和客户移出分别遵循 Controller 的独立权限组合。
|
|
||||||
|
|
||||||
接入文件:`WorkReceivingPanel.vue`、只读 `ReceivingScope.vue`;入口为 `WorkAppointmentForm.vue` 的“客户调整 / 共同预约范围”,由 `WorkDetailPanel.vue` 在原居中弹框内装配并保留结果。Member.customerName、Source.inboundCode 已消费,无名无号显示“—”,不以内部标识回退。原批次快照未提供客户名时只能从已返回的覆盖成员匹配或显示“—”,不猜客户名称。
|
|
||||||
|
|
||||||
结果只报告服务端实际 steps;本地原子事务失败不包装成部分成功。待确认结果明确原安排未变;保存成功但刷新失败只重试 GET。范围变化后保留输入并重新确认;重约成员集合变化时禁止把原输入套给新成员,显式重新填写。已返回的真实车次可跳原详情核对,后送步骤按 ALLOCATE_CARGO.targetKey 匹配成功批次,不取任意第一批;无业务号不拼车辆链接。未知箱数不替换为 0 或加入可预约范围。
|
|
||||||
|
|
||||||
本批前端直接验证:`receivingApi.test.ts`、`WorkReceivingPanel.test.ts`、`WorkDetailPanel.test.ts`、`WorkAppointmentForm.test.ts` 共 4 文件、36 项通过,`pnpm typecheck` 通过。未重复全模块测试或全量构建。生产者已通知新源码编译通过,但本批后端回归和真实环境验收尚无通过结论;不能据前端模拟 HTTP 的定向测试宣称端到端通过。
|
|
||||||
|
|
||||||
后续闭合情况见下节:子批真实事项解析、原车按需客户卡片、原来源过滤及单批真实托盘预选均已接入;重约按最新 executionScope/executionVersion 判断客户资格;普通调整和整份操作继续使用 transportVersion。以下早期依赖表用于逐场景定位,新合同的实际实现与剩余缺口以本节及下节为准。
|
|
||||||
|
|
||||||
已消费的合同为 `workApi.ts`、`batchApi.ts`、`planningApi.ts` 及原预约/排车 API。本批不新增接口或推导数量。已接核心冻结的 `FbaAppointmentBatchContext.currentBatches`:服务端解析全部替代分支、按稳定批次去重,前端只显示与 originalSourceRefs 的 customerId/sourceKey/destinationKey 完全匹配的当前明细,合并后的其他来源不算入原范围。未知箱数不显示 0,零量不生成去向卡片,空结果不回退历史替代链接。`replacementBatchKeys` 只用于识别历史快照,不能据此推导当前 20/40 箱去向。取消保留分配后的续办通过原预约更新接口提交版本和幂等键,不整票重建或重新分配。当前前端 `splitBatch` 与表单一次拆两批;服务端普通 repartition 的 DTO/OpenAPI 已支持 1 至 20 个非空目标批次,普通多批能力不构成接口依赖。本轮 100/60、40/20 保持两批交互。先送 0、已确认且有车的客户移出、共约范围变更仍需专用命令,不能以普通分批代替;尚未冻结的共享范围命令继续等待生产者。
|
|
||||||
|
|
||||||
| V13 场景 | 当前前端与直接检查 | 依赖/剩余验收 |
|
|
||||||
|---|---|---|
|
|
||||||
| 事项列表统一表格 | 用户截图 `codex-clipboard-1bde1991-b226-4956-8530-6de44074f818.png` 明确要求统一表格或卡片,不能混排 | 所有日期/类型/全局待办列表统一使用 DataTable 与 RowActions,替代早期多行卡片排版。操作固定最左;事项、类型、状态、作业时间、时区、流程、地点、负责人、下次跟进、提醒分列,时间保留实际/确认/目标口径。列表弹框加宽,表头与分页由共享表格承载;保留每页 8 项、筛选和返回上下文。当前调整覆盖旧卡片与独立分页结论;未运行验证或部署,待人工截图确认 |
|
|
||||||
| 01 整客户 160 移出续办 | `WorkDetailPanel.test.ts` 保存后读取主要下一步;`WorkExistingDispatchForm.test.ts` 沿用真实排车单继续安排本批车辆 | 单客户移出命令、当前数量/车辆版本、原车 120 保留结果及后续目标;真实发车签收待集成 |
|
|
||||||
| 02 100 先送、60 后送 | `AppointmentBatchForm.test.ts` 保留普通分批与来源版本;`WorkDetailPanel.test.ts` 区分未定作业日和跟进日 | 已确认预约/装载关系的部分移出与调整回复语义,不能以普通分批代替 |
|
|
||||||
| 03 后送 60 加另一客户 40 共车 | 本批与另一客户按实际托盘各建排车单;结果页“与同仓其他排车单共车”沿业务号核对两单后复用 TripPreparationDialog/Fleet prepare,可加入已有计划车次;WorkDispatchForm、WorkSharedTripForm、TripPreparationDialog、trips API 测试覆盖传递与导航 | 实物须能对应本次数量,不能对应时先走原库存拆托;共车后的路线、容量、审核及发车须真实 HTTP 验收,非任意箱级拆托开发缺口 |
|
|
||||||
| 04 后送 40 新批、20 待排 | `AppointmentBatchForm.test.ts` 消费 `currentBatches` 的 40/20 全部分支;逐客户/来源/目的仓过滤,排除合并的其他货物;未知量不当 0 | 已接客户变化确认及真实批次续办;已接当前/历史排车全量批次引用,实际装载链待集成;实物拆托是原库存前置 |
|
|
||||||
| 05 全部再分配后的旧入口 | `AppointmentBatchForm.test.ts` 只显示当前终点,不显示中间替代批次;零量无卡片,空结果不回退旧链接,原快照明确仅供追溯 | 服务端负责图遍历及稳定键去重;真实多次再分配与跨页返回待集成 |
|
|
||||||
| 06 待回复先保存再续办 | `WorkAppointmentForm` 保留计划/确认分开;`WorkDetailPanel` 保存后留在当前项 | 单客户调整草稿、仓库回复范围、待确认变化、原车阻断条件 DTO/命令 |
|
|
||||||
| 07 共约旧约号冲突 | 原预约错误继续保留表单;不按文本约号判断共约 | 生产者共约身份、当前覆盖成员、唯一性冲突合同;真实冲突验收待集成 |
|
|
||||||
| 08 整份改期、无变化保存 | `WorkAppointmentForm.test.ts` 无变化及空白字符归一化后不重复提交;跨日/偏移原样保留 | 整份范围、成员版本、车辆影响与无变化后端幂等;不能仅凭前端禁用证明不重复复核 |
|
|
||||||
| 09 整份取消后共同重约 | `WorkAppointmentForm.test.ts` 已接取消保留分配后的原批更新续办,可先保存日期未定/PENDING;保留历史、版本及幂等键,不再创建整票;取消不能重复提交,只读权限不能续办 | 整组共同/分别重约已接 receiving Book,消费 eligible/excluded;新关联及原车实际资格待后端/集成验收 |
|
|
||||||
| 10 分别重约与排除已另约成员 | 不复制现有逐票新建接口实现假整组成功 | 当前组资格、排除原因、分别重约结果、冲突/部分失败续办及所有时段核对 |
|
|
||||||
| 11 保留量为 0、原车无货 | 当前前端普通拆分保留两批均非空的交互约束,不绕过服务端业务资格 | “取消本次安排/全部移出”专用语义、无货原车权威处理结果;不能用空批次代替 |
|
|
||||||
| 12 未定日期、换月、图层、分页 | `AppointmentCalendarView.test.ts` 全局范围不带日历条件,保存后留在当前详情、返回保持原分页;既有前置返回/外部路由上下文继续检查;`WorkDetailPanel.test.ts` 跟进日不作作业日 | 新去向与新范围的上下文等待对应稳定标识;人工截图与真实再进入待验 |
|
|
||||||
| 13 部分失败、超时、并发 | `WorkDispatchForm.test.ts` 重试原草稿、不重锁已提交实物;`WorkDetailPanel.test.ts` 保存成功但下一步读取失败仅重试 GET、旧操作禁用;`WorkAppointmentForm.test.ts` 原批重约结果未知同键重试,明确冲突保留输入、读取新版本后显式再提交 | 多步骤逐项结果/可重试动作及范围版本合同;现有草稿恢复不代表跨域 V13 全部已完成 |
|
|
||||||
| 14 权限、失败、时区、DST | 既有 work/form/presentation/API 直接测试保留;来源失败显示明确错误 | 新增合同对应权限/版本/持久幂等与真实时区场景待生产者和集成验证 |
|
|
||||||
| 15 五类计数、真实车次与执行门槛 | `WorkCalendarPanel.test.ts` 五类聚合固定数量入口,服务端 2 批送仓/1 车原样展示;日格定高,不在浏览器重算车辆数;原实际执行入口保留 | 去重由后端保证;直送卸货、还空、共车发车资格及接手结果继续真实验收 |
|
|
||||||
|
|
||||||
当前定向检查(含首批与 currentBatches/原批重约新增 6 项):`pnpm test src/modules/appointment-calendar src/styles/adminDensity.test.ts`,29 文件、210 项通过;`pnpm typecheck` 通过。完整测试/构建窗口按开发协作契约交总控安排,本批未执行。以上是本地实现与检查,不表示部署或 15 项全链已验收;居中弹框及新增去向/续办内容仍待人工截图确认。
|
|
||||||
|
|
||||||
|
|
||||||
### 60+40 两步共车入口
|
|
||||||
|
|
||||||
`WorkSharedTripForm.vue` 仅按明确排车业务号读取两单,复用原 Fleet 安排弹框。真实 60/40 数量从两单读取,不自行生成装载结论;已关联、异仓、重复、错误业务号均不进入安排。子弹框打开时保护父工作面板,成功导航服务端返回的车次。增量联通检查覆盖 WorkDispatchForm、WorkSharedTripForm、既有 TripPreparationDialog 与 trips API;完整本轮验证见下一节。
|
|
||||||
|
|
||||||
### 最新货物资料显式采用
|
|
||||||
|
|
||||||
已消费 RefreshCargo/REFRESH_CARGO:WorkReceivingPanel 按客户提供“核对并采用本客户最新货物资料”,只按该客户原来源读取既有 cargo-verification(预约及尾程列表读权限),展示原票、本批箱数、最新核实/有效/已分配量及货件号。读取不会保存核实资料或自动采用。源/核实版本、身份、目的地、起运仓、未知分配、已分配超量及来源阻断均检查;任何一票失败不提交部分范围。
|
|
||||||
|
|
||||||
明确确认后 POST `/appointment-receiving/cargo-refresh` 只携带该客户成员及显示的 batchVersion、executionVersion、各来源最新版本;不提交箱数或正式确认。已确认、待变化、已完成客户禁用。冲突后重读并清除确认,未知结果保持原请求键,成功刷新事项并可继续本客户计划/正式预约,不跳回会影响其他客户的旧整批 PUT。
|
|
||||||
|
|
||||||
本轮共车与资料采用最初组合为 8 文件、81 项通过;已被下述当前/历史引用收口后的完整组合覆盖。未执行 HTTP、部署或人工截图。
|
|
||||||
|
|
||||||
### 客户级普通计划补齐(V13 06 / 09 / 10)
|
|
||||||
|
|
||||||
- 已消费实际 `Context.plans`、`CustomerPlan` 和 `Plan`,通过 POST `/appointment-receiving/plans` 提交明确 batchKey/customerId/batchVersion、executionVersion 与幂等键。`WorkReceivingPanel` 客户卡片和本批重约范围提供“保存目标 / 未约成”;不走旧整批 PUT,不改变甲的确认或借分批保存日期。
|
|
||||||
- 只允许 PENDING/FAILED,FAILED 必须有原因;普通计划无外部约号和正式确认时间。资格同时要求 PLAN_RECEIVING、当前执行资格、无活动确认和无待变化记录。时区来自该客户计划(未有计划时来自批次目的仓);非空目标缺时区阻止提交。计划窗口支持跨日及 startOffset/endOffset,DST 歧义或不存在时间由权威接口校验;只填日期或全空目标不带偏移。
|
|
||||||
- 回显优先当前 batch/customer 的 plans,明确空日期保持空;无独立客户计划时,仅无任何有效独立覆盖且 header 为 PENDING/FAILED 才带入旧计划和原因,剔除正式确认。混合覆盖不借甲日期,CANCELLED 不回填旧目标。混合状态测试为同一稳定批次中甲已有独立确认、乙与丁未确认;覆盖乙保存日期、未约成、清空日期、丁从空白开始、只读/已完成/待变化禁用、版本冲突保留输入、未知结果同键重试、UNCHANGED、跨日/DST 和未知时区。保存后刷新当前工作事项,保留 receiving 面板及真实结果,原“记录回复与跟进”入口保留。
|
|
||||||
- 整组取消后支持按客户勾选子集,共同或分别确认只提交所选成员。通过实际只读 POST `/appointment-receiving/execution-scope` 查询所选 batch/customer 的执行资格,使用返回版本,不复用全组或猜测 token;保留展示时的 batchVersion/groupVersion。选择变化清除范围确认,读失败禁止提交,可单独重读;过期异步响应不覆盖新选择。新增同批仅甲独立确认、跨批仅乙子集、分别表单与客户匹配、查询失败及迟到响应回归。
|
|
||||||
- 直接测试:`WorkReceivingPanel.test.ts`、`receivingApi.test.ts`、`WorkDetailPanel.test.ts`、`TripAppointmentPanel.test.ts` 共 4 文件、56 项通过;`pnpm typecheck` 和最终 `pnpm build`(含 vue-tsc)通过,构建 4.78 秒;仅既有 AnalyticsChart 约 588 kB 分块警告。`git diff --check` 通过。本批前端冻结。未执行真实 HTTP、部署或人工截图验收;服务端甲确认不变、客户计划工作域投影及日历归属仍由总控集成核对。
|
|
||||||
|
|
||||||
### 本批续办、原车入口和历史来源收敛
|
|
||||||
|
|
||||||
- `batchApi.ts` 必需字段 `originalSourceRefs` 已与生产者 SourceRef/OpenAPI 同步;`AppointmentBatchForm` 与 `TripAppointmentPanel` 均按完整客户/来源/目的地过滤当前全部去向。原批仍保留货物但另有后送批时也显示当前去向。全客户移出后不再依赖原批当前 items,且不拿历史来源授权可分配数量;新增全移出、40/20、合并其他来源隔离回归。
|
|
||||||
- `workApi.ts`、`WorkBatchContinuation.vue` 接真实客户级解析;保存原/后送预约后继续当前子批事项,原事项留作返回上下文,多客户不默认取第一项。
|
|
||||||
- `TripDetailView.vue` 按需装配公开 `TripAppointmentPanel`:本车当前 appointmentBatches 与 previousDispatches 稳定引用→批次/currentBatches/receiving 范围;客户卡片列当前所有匹配去向,直接进入对应客户调整或当前批次续办。新弹框复用未保存/未知结果保护,刷新车次和路由离开也经过保护,业务提交后刷新本车事实。
|
|
||||||
- `WorkDispatchForm.vue` 从单客户单批入口仅预选当前合格实物,候选跨批/客户、重复实物、未知箱数均不误选;提交仍复制服务端 allocations。可直接进入本批逐来源分批,60→40/20 测试只提交该 60 的原批和来源版本,不把原总量 160 再分配。多客户、超车型容量不自动全选;真实整托无法覆盖的部分箱量不伪造实物。
|
|
||||||
- `WorkReceivingPanel.test.ts` 新增跨批 A 已另约、仅 B/D eligible 的重约回归:提交 B/D 的真实 batchKeys 与 GroupContext.executionScope.version(Book.executionVersion),不带回 A,也不使用原 A/B/D 范围版本或运输版本。待确认 WITHDRAW 仍可提交,不以普通货物可变性条件禁用撤回。
|
|
||||||
|
|
||||||
- 最新接收合同已消费:ChangeIntent.ownerId 由本人、当前事项及关联事项负责人候选选择,父事项传入候选,不新增用户目录或用自由姓名充当账号;Pending.followup 展示服务端 ownerName/nextFollowupDate。普通正式预约按 Context.executionScope 排除 completed 或 canRebook=false 的客户,整组按服务端 eligibleMembers;Book 只提交对应 executionVersion,运输展示或无关客户的运输阻断不再一刀切禁止重约。货物调整、确认/撤回和整份改期/取消仍使用 transportVersion。新增负责人候选/真实姓名、已完成 A 不挡未完成 B、缺失执行资格不擅自放行等回归。
|
|
||||||
|
|
||||||
当前合同接入、实物前置与真实验收边界:
|
|
||||||
|
|
||||||
1. 原车当前/历史引用已按冻结 DTO 接入:`DispatchResponse.appointmentBatches`、`TripBinding.appointmentBatches` 与 `Detail.previousDispatches` 均为必需数组,`batchNo` 允许 null,不依赖可空 `fbaAppointmentNo` 或内部排车 ID。`TripAppointmentPanel` 按批次/客户聚合并对排车业务号、来源和当前终点去重,精确匹配客户/来源/目的地,只展示 `currentBatches` 当前量。历史卡片只提供追溯和权威解析后的当前工作入口,不使用历史数量授权调整或排车。`appointmentHistoryUnavailableReason` 单独提示,缺乏证据的引用不开入口,当前车次仍可读。已补空原约号、多批引用、历史客户移出后重进、40/20 全去向、其他客户/来源隔离、重复记录、缺失历史提示和错误身份回归。真实持久历史及装载链待集成验收。
|
|
||||||
2. 60+40 按真实两步流程收口:各客户按本批分配及实际托盘生成排车单,WorkDispatchForm 结果页进入 WorkSharedTripForm,按另一张业务号重读两单,核对当前状态、未绑定及真实起运仓一致后交给既有 TripPreparationDialog;Fleet prepare 复用多个 dispatchNos,可新建或加入原计划车次。未新增共车命令、未扫描全局待办、未按名称推仓。数量不能映射完整实物时必须先走原库存拆托,这属于实物前置,不列为待开发任意拆托;仍待真实 60+40 HTTP 和装载链验收。
|
|
||||||
3. receiving 仍以当前源码接入,待核心与工作事项后端回归及真实场景。UI 本地通过不证明服务端初始化、同步及最终执行门槛已经部署验收。
|
|
||||||
|
|
||||||
验证:最新完整定向命令 `pnpm test src/modules/appointment-calendar src/modules/overseas-master-data/pages/TripsBehavior.test.ts src/styles/adminDensity.test.ts` 34 文件、260 项通过;`pnpm typecheck` 通过。`pnpm build`(含 vue-tsc)通过,Vite 构建 3.92 秒;既有 AnalyticsChart 约 588 kB 分块警告保留,无构建失败。`git diff --check` 通过;未提交、发布或部署,真实页面待人工截图确认。
|
|
||||||
|
|
||||||
### 下一批精确接入点与合同门槛
|
|
||||||
|
|
||||||
下表路径除特别标注外相对 `src/modules/appointment-calendar/`。新增语义仅列需求,不预定义字段名、HTTP 路径或动作代码。生产者交付真实 DTO/OpenAPI、权限、直接测试后再接写入;不在现有普通分批或跟进命令中夹带未实现的共约调整。
|
|
||||||
|
|
||||||
| 接入点与现有真实入口 | 可用部分 | 尚需生产者提供的精确语义 |
|
|
||||||
|---|---|---|
|
|
||||||
| `AppointmentBatchForm.vue`、`batchApi.ts`;GET `/appointment-planning/batches/{batchKey}`、POST `/appointment-planning/appointments/repartition` | 原来源核实、当前前端一次拆两批(服务端支持最多 20 批)、全部当前终点 | 车次/排车单到逐客户逐来源当前装载的引用;当前可调整量及版本;先送 0/全量/中间量各自资格;移出确认后原车保留结果与后送批次,是否有待确认草稿。不能把现有 splitBatch 的非空限制直接删除 |
|
|
||||||
| `WorkAppointmentForm.vue`、`overseas-warehouse/api/inboundOrders.ts` 的 get/updateFbaAppointment;`api.ts` 的 deleteAppointment | 单批计划、确认、取消、原批续办、同键重试 | 独立共同预约身份、范围版本、当前成员/箱数/原确认时段/关联车辆、仅本客户或整份的允许动作;读取待回复变化及保存/确认/拒绝语义。旧事实与待确认输入分别返回,不能写普通计划来冒充移出成功 |
|
|
||||||
| `WorkAppointmentForm.vue` 的重约衔接,后续独立共约表单只在合同冻结后装配 | 已取消单批沿原号 update,保留分配 | 整组重约的当前候选、已退出/已另约/已完成/其他处理中成员与原因、各成员当前去向;共用/独立结果、新有效关系身份、仓库覆盖确认依据、原车复用资格及范围并发校验 |
|
|
||||||
| `WorkDispatchForm.vue`、`WorkExistingDispatchForm.vue`;`overseas-warehouse/api/dispatches.ts` 的 getBatchDispatchCandidates、草稿锁定/预排;既有 TripPreparationDialog | 按真实托盘、每客户排车,再沿已有排车单安排车辆 | 已按当前真实整托候选分别创建客户排车单,再从结果页使用另一张已备排车单业务号共车;本批默认只选当前合格实物。部分箱量无法映射时先走原库存拆托,非本轮新建任意拆托接口需求;真实资源资格和装载链待 HTTP |
|
|
||||||
| `overseas-master-data/pages/TripDetailView.vue` 本车排车单及 `overseas-warehouse/pages/DispatchesView.vue` | 原业务排车、审核、装载、发车规则继续使用;当前任务未修改这些页面 | 本车客户卡片的客户业务名称、batchKey/来源/数量/当前预约覆盖、未确认变化、当前去向与可调整目标;对应允许动作;原车无货的权威关闭结果。不能以解除排车单关联替代客户移出 |
|
|
||||||
| `WorkDetailPanel.vue`、`workApi.ts` 的 GET `/appointment-work/items/{key}` | 消费 allowedActions、nextAction、blockReasons、relatedItems;保存成功后刷新 | 新命令的稳定目标与白名单动作、受影响工作键、原批到当前批次的工作项引用。当前 currentBatches 只有预约快照,子批保存后不能凭业务号或拼接 batchKey 猜新工作键;目前仍刷新进入时的原事项 |
|
|
||||||
| `WorkDetailPanel.vue`、`AppointmentCalendarView.vue`、`workNavigation.ts` | 日期、月份、流程、类型、范围、分页及原事项返回已有支持 | 新结果逐步骤成功/失败/待补、已持久保存对象、失败步骤允许的重试动作和幂等身份;用于只重试失败部分,并明确原车和后送需求都存在 |
|
|
||||||
|
|
||||||
独立修复:`WorkAppointmentForm` 首次读取失败后重试须初始化真实确认资料和偏移;版本冲突后仍保留已编辑输入。`AppointmentBatchForm` 切换当前去向先清除旧快照,首次读新批失败再重试须按新批初始化日期/数量,不能复用旧批草稿。对应新增直接测试分别在同名 `.test.ts`;不涉及新合同或环境写入。本次仅运行上述两个测试文件,16 项通过(新增 2 项);未重复运行上一批完整模块检查。
|
|
||||||
|
|
||||||
只读联审的子批续办缺口已接入真实 GET `/appointment-work/items/resolve?batchKey=...&customerId=...`:`BatchWorkResolution` 返回唯一 detail 或多客户 candidates。`WorkBatchContinuation.vue` 多候选必须明确选客户,再读权威 detail;读失败只重试 GET。`WorkAppointmentForm` 保存返回真实预约快照,`WorkDetailPanel` 用其 batchKey 定位子批,刷新摘要但不再先刷新旧事项/弹回旧事项。`WorkDetailPanel.test.ts` 与 `AppointmentCalendarView.test.ts` 已覆盖子批下一步、车辆续办、返回旧事项及原未定日期分页;工作键不在浏览器拼接。
|
|
||||||
|
|
||||||
### V13 集成操作与判定清单(待合同与集成窗口)
|
|
||||||
|
|
||||||
以下是验收设计,不是通过记录。01–11 每项恢复独立的甲 80、乙 160、丁 40 基准,均按客户+来源+目的地核对,不跨场景累计;涉及环境写入时由总控按授权窗口执行。
|
|
||||||
|
|
||||||
| 场景 | 操作与必须观察到的结果 |
|
|
||||||
|---|---|
|
|
||||||
| 01 | 原车乙卡片先送 0,确认仓库回复后原车 120、乙后送 160;沿乙入口重新约仓/用车,其他客户确认不变,无新增整票占量 |
|
|
||||||
| 02 | 乙先送 100、后送 60,后送不填日期;原车 220,60 在全局未定日期可续办,跟进日不填入送货日 |
|
|
||||||
| 03 | 从 60 入口按实际托盘形成客户排车单;另一客户 40 同理。结果页核对两单业务号与真实同仓资格后,沿 Fleet 安排同一车次;分别/共同约仓范围可辨,一车 100,客户归属保留。实物不匹配先走原库存拆托 |
|
|
||||||
| 04 | 后送 60 再选 40,原车客户卡片列 40 新批与 20 待排各一次;两者可直达,不把合并的其他客户数算入乙 |
|
|
||||||
| 05 | 后送量全部再分配,旧入口显示全部当前终点;中间历史、0 箱卡片和重复后送待办均不出现 |
|
|
||||||
| 06 | 调整后先保存待仓库回复,退出再进入仍有待确认输入,旧有效安排保留;未解决前发车被阻断,继续明确回复后只影响对应范围 |
|
|
||||||
| 07 | 退出客户填写他人有效旧约号,提交冲突后保留号码、时段及输入;不自动加入共同预约;重新读取范围后明确再提交 |
|
|
||||||
| 08 | 选择整份共同改期,先核对完整当前成员和车辆;保存同一新时段只影响相关已安排工作,再次无变化保存与复核不新生复核 |
|
|
||||||
| 09 | 整份取消后旧确认和失效目标清除、历史保留;共同重约只选仍需履约成员,仓库确认覆盖后产生新有效关联,沿可用原车续办 |
|
|
||||||
| 10 | 一名成员先独立另约,再进入整组重约;其被排除并显示去向,退出/已完成/其他处理中成员同样不可静默加入;其他成员可分别重约 |
|
|
||||||
| 11 | 先送为 0 合法,全量先送不产生空后送;原车所有有效货物移出后按原车命令关闭待办,已发车则进入原异常处理,不能普通移出 |
|
|
||||||
| 12 | 未定日期分页进入→切月份/图层→当前批续办→返回;原范围、分页、日期及筛选恢复,全局待办不因日历筛选丢失 |
|
|
||||||
| 13 | 分别在货物保存、车辆关联、读取下一步失败处中断;只重试失败步骤,未知结果同键,已成功批次/排车/车次不重复创建;显示真实部分结果 |
|
|
||||||
| 14 | 只读权限、来源不可用、版本变化、约号冲突、跨日和 DST 逐项验证;首次 GET 失败重试不得出现空白可写旧事实,冲突后保留输入,未知数量不作 0 |
|
|
||||||
| 15 | 五类高计数仍固定日格,同车多批只计一辆车;中转与直送分别走真实备货/卸货/还空门槛,未完成卸货或未接手责任不能借复核结束工作 |
|
|
||||||
|
|
||||||
阻塞场景不以按钮禁用、静态截图或 Mock 成功响应记为已验收。合同冻结后先扩充对应组件/API 定向测试,再由总控安排真实场景及 1920×1080、100% 人工截图。本次读取恢复修复后的 `pnpm typecheck` 和 `git diff --check` 均通过;未执行全量构建、真实 HTTP 或部署。
|
|
||||||
|
|
||||||
| 本次操作 | 证据与现状 | 调整结论 |
|
|
||||||
|---|---|---|
|
|
||||||
| 未定日期范围内搜索 | 用户截图 `codex-clipboard-07b5ab03-e467-4ce1-8410-13d05ac5bc51.png` 反馈大量数据缺少搜索,且测试环境仍显示旧卡片 | 全局待办弹框接入 QueryToolbar,支持柜号、批次号、车次号、地点关键词;沿现有 items API 同时传 view(含 UNDATED)与 keyword,服务端全范围筛选后分页,不过滤当前 8 条。搜索/清空回第 1 页,返回明细保留搜索词和分页,原业务跳转的 return URL 保留 workListKeyword。保留全局统计口径;表格与搜索均为当前工作区改动,本任务未部署,未运行验证 |
|
|
||||||
| 所属客户缺失排查 | 用户截图 `codex-clipboard-645f5354-0dfd-4b90-b6f7-05ff9b1f2ffb.png`;`BusinessReference` 只有 kind/key/businessNo/label,客户引用存在 `CUSTOMER + 内部客户键 + null + 所属客户` 的生产路径,详情查询仅合并引用 | 前端按 `businessNo || '—'` 展示,缺少真实客户名称;不能据此认定没有关联客户,也不能回退内部客户键。待工作事项后端按权威客户目录补充名称/业务编号并明确展示合同;遵循开发协作契约,本任务不保留后端改动。未完成接口或环境验收 |
|
|
||||||
| 提醒列与跳转遮罩 | 用户截图 `codex-clipboard-54e0b56d-448c-40da-a147-15798c932091.png` 和按钮反馈 | 提醒列固定 105px,仅显示去重后的条数,点击展开完整可滚动提醒,不撑高表格行。预约页被 KeepAlive 停用时卸载挂到 body 的弹框,恢复时保留父级事项/分页上下文。用户 startTime 截图实际是 INP 采集的空 entries 读取,脚本来源尚待确认,不能将该报错认定为已修复;本轮未运行验证或部署 |
|
|
||||||
| 事项详情的信息层级 | 用户 2026-10-16 截图 `codex-clipboard-cad4abc6-51d1-42f2-8e7b-7914b264348e.png` 反馈排版不清楚、缺少重点 | 顶部突出事项名称与状态;作业时间、时区、地点、负责人和下次跟进复用共享描述表;原有提醒去重后集中展示,保留完成态与跟进日期语义;当前操作与关联资料/历史分区,保留所有动作资格、原业务跳转、默认历史展开条件和未保存保护。空原业务进度不渲染空标题;已知事件代码使用中文名称,未知代码保留在辅助信息中,时间保留原时区。本轮未运行验证或部署,待人工截图确认 |
|
|
||||||
| 列表信息层级与日历视觉细化 | 用户 2026-10-16 截图 `codex-clipboard-6858cde3-eda3-4a02-a043-e1a47143f67c.png`、`codex-clipboard-5a68965d-cdbd-4ce9-b8b3-385d9d76b4f2.png`,并明确要求按建议优化 | 查看详情/历史使用普通描边按钮,办理动作保留主色且仍在左侧;完整标题、状态、作业时间、时区、地点、流程、负责人、跟进日期及异常分层显示。日历类型改浅色底与弱边框,保留语义色、今天/选中态;周末表头与到港参考保持辅助层级,零值弱化、超期数字提示。保留现有覆盖面板、字号、统计和动作链;改后待人工截图确认 |
|
|
||||||
| 工作明细左侧长操作按钮 | 用户 2026-10-16 截图 `codex-clipboard-b36b905a-a223-4fa6-98ca-7ece08149a37.png` 反馈按钮过大;原 108px 列宽、全宽实心按钮导致长文案换行撑高 | 操作列调整为 184px,按钮按文案宽度使用共享 `density-action` 描边样式和 28px 最小高度;完整保留服务端动作标签及点击行为,超长文案仍可换行。业务编号使用深色标题,辅助信息使用说明字号,行间距收紧。适用全部工作明细弹框及全屏态,覆盖早期实心主按钮结论;改后待人工截图确认,本轮未运行验证或部署 |
|
|
||||||
| 流程与工具栏分组 | 用户后续流程下拉、日期工具栏及上下操作区截图(`115df974`、`d217350b`、`80dd9fa1`) | 流程改为四个直接切换按钮;全局待办、流程、日期与类型筛选收进连续白底工作区,各行靠左,保留全局与区间统计边界 |
|
|
||||||
| 日历浏览与日期选择 | 主页面截图;原型 `renderCalendar()`、`.day.selected`、`.todaymark` | 缩小日格空白,今天与选择态分别标识;零项日期只显示日期;显示实际查询起止日期,保留加载失败状态 |
|
|
||||||
| 日期/类型/全局明细 | 展开截图中日历被挤窄;原型第 11 行 `.workspace`、`.panel` 为右侧覆盖布局 | 恢复覆盖式侧边工作面板,不压缩日历;增加展开/收起,标题和关闭固定,正文滚动,分页固定;仍保留左侧业务操作 |
|
|
||||||
| 详情与编辑 | 原型 `renderTask()`、`followForm()` | 保留原侧边详情/表单和原业务跳转;关闭、切换和返回仍经过未保存保护,扩宽不重建表单 |
|
|
||||||
| 今日需跟进 | 仅核对 `AppointmentWorkPolicy.followToday` 和 `AppointmentWorkQueryService.summary` | 保留服务端统计、接口参数及前端数字,不在本次视觉调整中改口径 |
|
|
||||||
|
|
||||||
| 页面/操作 | 原型证据 | 承载与布局 | 实现入口及核对范围 |
|
|
||||||
|---|---|---|---|
|
|
||||||
| 日历首屏、五类计数 | `.calendar`、`renderCalendar()` | 月/周日历,紧凑日格随内容自然增高,五类勾选与类型计数;到港参考单列且不计工作 | `AppointmentCalendarView.vue`、`WorkCalendarPanel.vue`;服务端聚合,实际日期优先由服务端给出 |
|
|
||||||
| 全部待办、今日、超期、未定日期、复核 | `.inboxbar`、`backlog()`、`renderList()` | 日历上方全局入口;侧边分页明细,操作在左,范围明确 | `workApi.ts`;summary 不带月历条件,全关图层不影响全局查询 |
|
|
||||||
| 日期、类型与本柜连续工作 | `openDay()`、`renderList()` 的 container 模式 | 同一侧边面板;确认路线后回本柜未完成事项 | `WorkDetailPanel.vue`;保存刷新摘要、日历和当前范围 |
|
|
||||||
| 下一步、前置事项与返回 | `nextAction()`、`renderTask()`、`.origin-context` | 主按钮直接处理当前下一步;前置项保留原事项返回入口 | 动作 code/target 白名单,重新读取目标资格;原业务执行仍回原入口 |
|
|
||||||
| 回复、路线、收货要求、复核、还空责任 | `planForm()`、`followForm()` | 侧边表单;保留原因、反馈、地点时区与历史;无需预约不造确认号 | `WorkCommandForm.vue`;显式跨日结束日期/时间成对填写,完整当地结束时间严格晚于开始;日期未含时刻时不补造;版本、权限、未知结果同键重试、冲突保留输入 |
|
|
||||||
| 未预约补核实资料 | `cargoFields()`、`cargoSourceHtml()` | 侧边独立表单;逐来源客户、原票、数量与货件 | `CargoVerificationForm.vue`;原箱数与可分配量未知不显示0,不覆盖原订单 |
|
|
||||||
| 编辑/确认/取消原预约 | `planForm()` 及 cancel 分支 | 侧边原预约表单,取消原因和明确确认按钮;不增加假预约 | `WorkAppointmentForm.vue`;复用既有时区与夏令时字段、版本及原业务命令 |
|
|
||||||
| 新建原预约 | `planForm()` | 侧边先读取实际货物预览,再登记预约安排 | `WorkCreateAppointmentForm.vue`;复用原来源预览/创建 API,明确客户与 ORDER/BOOKING 来源,未知结果同键重试 |
|
|
||||||
| 分批、合并 | `splitForm()`、`mergeForm()` | 侧边逐来源数量分配,数量守恒 | `AppointmentBatchForm.vue` 按真实 batches/repartition 合同提交逐来源数量、来源/核实版本、原批次版本和幂等键;被替代快照只读,显示新业务号;无分批资格时仍显示 appointment.items 货物快照 |
|
|
||||||
| 提柜安排、实际提柜、还空 | `executeForm()` | 原货柜页独立表单;返回预约时恢复原事项与筛选 | `ContainerDetailView.vue`;真实车队检索、当前版本和原权限,固定 PICKED_UP 原船节点命令;实际时间由操作者填写,未知结果保留原请求与幂等键 |
|
|
||||||
| 整柜直送逐票卸货 | `executeForm()` | 原货柜页逐来源清单及签收表单,已登记只读 | 原 direct-deliveries API;真实装柜来源、当地时间、IANA 时区、签收人与凭据号,服务端核验路线和还空前置 |
|
|
||||||
| FBA 批次排车与用车 | `executeForm()`、原车次安排入口 | 侧边按真实托盘选择;创建原排车单后进入原车次安排弹窗 | `WorkDispatchForm.vue`;逐来源 batchAllocations 原样提交原草稿分组,每单同客户,未知结果重试原草稿;已有车次按业务号进入原详情 |
|
|
||||||
| 客户仓批次用车 | 原排车与车次安排入口 | 按 DISPATCH 引用读取原排车单,再进入原车次安排 | `WorkExistingDispatchForm.vue`;核对不可变批次键与真实业务号,保留原实物;不调用 FBA 候选,不新建排车单;原派送进度按明确业务引用进入 |
|
|
||||||
| 本柜接仓计划与记录 | `executeForm()`、原入库单详情 | 单计划进入对应客户原单,多计划列出本柜实际关联清单;缺计划时先预览整柜分组 | `WorkReceiptPlans.vue`;复用 container-summaries、原整柜预览/生成 API 和原入库单路由,快照与原资源重试键保持一致;实际收货仍由原仓库作业流程登记 |
|
|
||||||
| 失败、无权限、未保存 | 真实接口与应用验收规则 | 明确失败和重试;错误不改为0项,保留输入和原上下文 | 各组件直接回归;未知命令不执行,未确认保存结果禁止离开 |
|
|
||||||
| 保存后工作清单同步等待 | 用户截图 `codex-clipboard-40520e09-5cbf-489f-9941-325bdf22bdea.png`,顶部保存成功、正文续办 A0409 | 保留当前事项弹框和保存结果,不改变承载方式 | `useWorkSyncRead.ts` 仅对当前完整工作清单同步守卫重读 GET;间隔2秒,累计等待最多30秒,超限显示原错误;日历、汇总、明细与批次续办一致,不重复写入 |
|
|
||||||
| 查看原排车单、继续安排本批车辆 | 用户截图 `codex-clipboard-4791b73f-7a9f-4be5-910a-38911e135ef4.png`、`codex-clipboard-e5b41c4b-a00c-4b99-ac06-cd23ec910aa9.png` | 原排车单进入正式路由,事项弹框随缓存页停用而移除;继续配车沿目标事项读取资格 | 保留已有 `pageActive/onDeactivated` 修复;跨事项 `nextAction` 仅导航,目标事项重新核对 `allowedActions`,不继承送仓资格或执行旧动作。修复后待人工截图确认 |
|
|
||||||
| 刷新后沿用已有FBA排车单 | 当前对话指定沿用原DS;`WorkExistingDispatchForm.vue` 的既有原排车列表和 `TripPreparationDialog` | 保留事项弹框,显示本批原排车单;继续用原安排车次弹框,不重复选托盘或创建 | `WorkDispatchForm.vue` 先读当前批次 `receiving.transport`,再按原排车单 `appointmentBatches` 校验批次/客户;已绑定车次直接查看,关系读取失败不显示创建入口;剩余实物仅显式选择后读取。待人工截图确认 |
|
|
||||||
|
|
||||||
视觉目标:1920×1080、100%缩放,待人工截图确认。单元测试与类型检查单独报告,不代表真实接口或页面验收通过。原业务跳转缺少的业务号/客户范围在协作交接中列明,不由前端补造;工作 Slot 与原预约编辑均保留完整跨日时间。原业务页面返回入口只接受预约工作页,并保留原事项、前置事项、筛选及页码。
|
|
||||||
|
|
||||||
2026-10-20 用户追加整页白底修正:整页主要列表外层workbench-table及整页详情workbench-panel显式增加is-page-surface,由公共样式移除最外圈border/radius/shadow。内部指标、图表、并列卡片、子表格线、弹框和日历左右独立面板保留;本批不改padding、脚本或承载。预约页面没有额外整页面板,当前双面板结构保持,不给左右面板增加该modifier。
|
|
||||||
|
|
||||||
|
|
||||||
### 2026-10-21 弹框表单可用性修复
|
|
||||||
|
|
||||||
依据:本轮弹框可用性反馈;沿用本文件原有逐操作承载,不调整业务字段与提交逻辑。
|
|
||||||
|
|
||||||
| 页面/文件 | 操作与承载 | 结构问题与修复 | 验收 |
|
|
||||||
|---|---|---|---|
|
|
||||||
| WorkCommandForm、AppointmentBatchForm、WorkReceivingPanel、CargoVerificationForm | 预约工作弹框中的命令、批次、收货范围与货物核实 | 原生控件未命中 Element 表单样式;显式复用 workbench-input,并通过 appointmentNativeForms.css 补齐标签/控件排列、fieldset 间距及底部提交区 | 定向回归通过;待人工1920×1080、100%截图确认 |
|
|
||||||
| WorkAppointmentForm、WorkDispatchForm | 预约取消、按预约批次排车 | 取消原因与计划托位原生控件接入同一局部表单样式;复选框与既有候选分页保留 | 定向回归通过;待人工截图确认 |
|
|
||||||
|
|
||||||
本次6个Vue仅变更样式导入、class与操作区容器;与修改前快照逐项核对,业务脚本、v-model、事件、权限/禁用条件均一致。类型检查、全量回归与构建由总控统一收口。
|
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import type { ReceivingMember, ReceivingTransport } from './receivingApi'
|
|
||||||
defineProps<{ members: ReceivingMember[]; transport?: ReceivingTransport }>()
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<div aria-label="当前覆盖范围">
|
|
||||||
<div v-for="(member, index) in members" :key="`${member.batchKey}:${member.customerId}`" class="receiving-member">
|
|
||||||
<b>{{ member.appointmentNo }} · {{ member.customerName || '—' }} · 范围 {{ index + 1 }}</b>
|
|
||||||
<p v-for="source in member.sources" :key="`${source.sourceKey}:${source.destinationKey}`">{{ source.inboundCode || '—' }} · {{ source.packageCount }} 箱</p>
|
|
||||||
</div>
|
|
||||||
<p v-if="!members.length">当前无可纳入的货物。</p>
|
|
||||||
<template v-if="transport"><p v-for="(vehicle, index) in transport.vehicles" :key="index">车辆:{{ vehicle.tripNo || '车次未关联' }} · 排车单 {{ vehicle.dispatchNo || '未关联' }} · {{ vehicle.packageCount }} 箱</p><p v-for="reason in transport.blockReasons" :key="reason" role="status">{{ reason }}</p><p v-if="!transport.vehicles.length">当前未关联车辆。</p></template>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
<style scoped>.receiving-member { border-bottom: 1px solid var(--workbench-border); padding-block: var(--admin-space-3); }</style>
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import SourceAppointmentPanel from './SourceAppointmentPanel.vue'
|
|
||||||
import { resolvePlanningSource, resolvePlanningOrder } from './planningApi'
|
|
||||||
vi.mock('./planningApi', () => ({ resolvePlanningSource: vi.fn(), resolvePlanningOrder: vi.fn() }))
|
|
||||||
beforeEach(() => vi.clearAllMocks())
|
|
||||||
it('shows every associated appointment for a multi-batch source and opens the chosen business number', async () => {
|
|
||||||
const source = { customerId: 'customer-a', sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8' }
|
|
||||||
vi.mocked(resolvePlanningSource).mockResolvedValue({source:{...source,orderId:'1',inboundCode:'IN-TEST',bookingNo:null,containerNo:'CN-TEST',originWarehouseId:'warehouse-1',originWarehouseName:'测试仓',destinationWarehouseCode:'ONT8',packages:100,sourceVersion:'v1',canFollowup:true,blockReasons:[]},coverage:{status:'MULTIPLE',missingFields:[],changeReviewRequired:false,appointments:['AP-A','AP-B'].map(appointmentNo=>({appointmentNo,confirmationNo:null,status:'PENDING',confirmedAt:null,confirmedEndAt:null,timezone:null}))}})
|
|
||||||
const wrapper = mount(SourceAppointmentPanel,{props:{source,canLeave:async()=>true},global:{stubs:{ElButton:{template:'<button><slot/></button>'},CargoVerificationForm:true,WorkAppointmentForm:{name:'WorkAppointmentForm',props:['appointmentNo'],template:'<div>{{ appointmentNo }}</div>'},AppointmentBatchForm:true,LoadErrorState:true,ApiErrorMeta:true}}})
|
|
||||||
await flushPromises(); expect(wrapper.text()).toContain('共 2 个关联预约')
|
|
||||||
await wrapper.findAll('button').find(button=>button.text()==='AP-B')!.trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({name:'WorkAppointmentForm'}).props('appointmentNo')).toBe('AP-B')
|
|
||||||
expect(resolvePlanningSource).toHaveBeenCalledExactlyOnceWith(source); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('resolves an arrived external order to canonical BOOKING and passes only that source to cargo verification', async () => {
|
|
||||||
const input = { orderId: '9007199254740993', customerId: 'customer-a', destinationKey: 'FBA:ONT8' }
|
|
||||||
vi.mocked(resolvePlanningOrder).mockResolvedValue({source:{sourceKey:'BOOKING:external-booking',customerId:'customer-a',destinationKey:'FBA:ONT8',orderId:input.orderId,inboundCode:'IN-EXTERNAL',bookingNo:'BK-EXTERNAL',containerNo:null,originWarehouseId:'warehouse-1',originWarehouseName:'测试仓',destinationWarehouseCode:'ONT8',packages:100,sourceVersion:'booking-v1',canFollowup:true,blockReasons:[]},coverage:{status:'MULTIPLE',missingFields:[],changeReviewRequired:false,appointments:[]}})
|
|
||||||
const wrapper = mount(SourceAppointmentPanel,{props:{source:input,canLeave:async()=>true},global:{stubs:{ElButton:true,CargoVerificationForm:{name:'CargoVerificationForm',props:['source'],template:'<div />'},WorkAppointmentForm:true,AppointmentBatchForm:true,LoadErrorState:true,ApiErrorMeta:true}}})
|
|
||||||
await flushPromises()
|
|
||||||
expect(resolvePlanningOrder).toHaveBeenCalledExactlyOnceWith(input)
|
|
||||||
expect(resolvePlanningSource).not.toHaveBeenCalled()
|
|
||||||
expect(wrapper.getComponent({name:'CargoVerificationForm'}).props('source')).toEqual({sourceKey:'BOOKING:external-booking',customerId:'customer-a',destinationKey:'FBA:ONT8'})
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import { computed, onMounted, ref } from 'vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { resolvePlanningSource, resolvePlanningOrder, type ResolvedPlanningSource, type PlanningSourceLookup } from './planningApi'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
import CargoVerificationForm from './CargoVerificationForm.vue'
|
|
||||||
import WorkAppointmentForm from './WorkAppointmentForm.vue'
|
|
||||||
import AppointmentBatchForm from './AppointmentBatchForm.vue'
|
|
||||||
const props = defineProps<{ source: PlanningSourceLookup; canLeave: LeaveGuard }>()
|
|
||||||
const emit = defineEmits<{ updated: [] }>()
|
|
||||||
const context = ref<ResolvedPlanningSource | null>(null), error = ref<ApiErrorDetails | null>(null), loading = ref(false)
|
|
||||||
const appointmentNo = ref<string | null>(null), batchKey = ref<string | null>(null)
|
|
||||||
const canonicalSource = computed(() => context.value ? { sourceKey: context.value.source.sourceKey, customerId: context.value.source.customerId, destinationKey: context.value.source.destinationKey } : null)
|
|
||||||
async function load() {
|
|
||||||
loading.value = true; error.value = null
|
|
||||||
try { context.value = 'sourceKey' in props.source ? await resolvePlanningSource(props.source) : await resolvePlanningOrder(props.source) }
|
|
||||||
catch (cause) { error.value = getApiErrorDetails(cause, '货源预约关联读取失败') }
|
|
||||||
finally { loading.value = false }
|
|
||||||
}
|
|
||||||
async function openAppointment(number: string) { if (await props.canLeave()) { appointmentNo.value = number; batchKey.value = null } }
|
|
||||||
async function openBatch(key: string) { if (await props.canLeave()) { batchKey.value = key; appointmentNo.value = null } }
|
|
||||||
async function back() { if (await props.canLeave()) { appointmentNo.value = null; batchKey.value = null; await load() } }
|
|
||||||
async function updated() { emit('updated'); await load() }
|
|
||||||
onMounted(load)
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section aria-label="货源与全部预约批次">
|
|
||||||
<el-button v-if="appointmentNo || batchKey" @click="back">返回本票全部预约</el-button>
|
|
||||||
<AppointmentBatchForm v-if="batchKey" :key="batchKey" :batch-key="batchKey" @updated="updated" @appointment="openAppointment" />
|
|
||||||
<WorkAppointmentForm v-else-if="appointmentNo" :key="appointmentNo" :appointment-no="appointmentNo" :cancel="false" :can-write="true" @saved="updated" @batch="openBatch" />
|
|
||||||
<template v-else>
|
|
||||||
<h3>本票预约与货物核实</h3>
|
|
||||||
<LoadErrorState v-if="error" title="货源预约关联读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<p v-if="loading">正在读取全部关联预约…</p>
|
|
||||||
<template v-else-if="context && !error"><p>{{ context.source.inboundCode || context.source.bookingNo || '原票业务号未提供' }} · {{ context.source.destinationWarehouseCode || '目的仓待核实' }}</p><p v-for="reason in context.source.blockReasons" :key="reason">{{ reason }}</p><p>共 {{ context.coverage.appointments.length }} 个关联预约,分别查看和处理。</p><div v-for="appointment in context.coverage.appointments" :key="appointment.appointmentNo" class="source-appointment"><el-button @click="openAppointment(appointment.appointmentNo)">{{ appointment.appointmentNo }}</el-button><span>{{ appointment.confirmedAt || '尚无确认时段' }} · {{ appointment.timezone || '地点时区待核实' }}</span></div><CargoVerificationForm v-if="canonicalSource" :source="canonicalSource" @saved="updated" /></template>
|
|
||||||
</template>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
<style scoped>.source-appointment { display: flex; flex-wrap: wrap; align-items: center; gap: var(--admin-space-3); padding-block: var(--admin-space-3); border-bottom: 1px solid var(--workbench-border); }</style>
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import TripAppointmentPanel from './TripAppointmentPanel.vue'
|
|
||||||
import { getDispatch, getFbaAppointment, type DispatchBatchReference } from '@/modules/overseas-warehouse'
|
|
||||||
import { getAppointmentBatch } from './batchApi'
|
|
||||||
import { getReceivingContext } from './receivingApi'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
vi.mock('vue-router', () => ({ onBeforeRouteLeave: vi.fn() }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => true }) }))
|
|
||||||
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getDispatch: vi.fn(), getFbaAppointment: vi.fn() }))
|
|
||||||
vi.mock('./batchApi', async original => ({ ...await original<typeof import('./batchApi')>(), getAppointmentBatch: vi.fn() }))
|
|
||||||
vi.mock('./receivingApi', async original => ({ ...await original<typeof import('./receivingApi')>(), getReceivingContext: vi.fn() }))
|
|
||||||
const reference = (batchKey = 'FBA_APPOINTMENT:1', batchNo: string | null = 'AP-001'): DispatchBatchReference => ({ batchKey, batchNo, recordVersion: 0, customerId: 'customer-a', sources: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', packageCount: 70 }] })
|
|
||||||
function render(overrides: Partial<InstanceType<typeof TripAppointmentPanel>['$props']> = {}) { return mount(TripAppointmentPanel, { props: { dispatches: [{ dispatchNo: 'DS-A', customerId: 'customer-a', packageCount: 70, appointmentBatches: [reference()] }], previousDispatches: [], historyUnavailableReason: null, canWrite: true, ...overrides }, global: { stubs: {
|
|
||||||
ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' },
|
|
||||||
AppDialog: { props: ['modelValue'], template: '<div v-if="modelValue"><slot /></div>' },
|
|
||||||
WorkReceivingPanel: { name: 'WorkReceivingPanel', props: ['batchKey', 'initialCustomerId'], template: '<div data-receiving />' },
|
|
||||||
WorkBatchContinuation: { name: 'WorkBatchContinuation', props: ['batchKey', 'customerId'], template: '<div data-continuation />' },
|
|
||||||
AppointmentBatchForm: true, WorkAppointmentForm: true,
|
|
||||||
LoadErrorState: { props: ['message'], template: '<p role="alert">{{ message }}</p>' },
|
|
||||||
} } }) }
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks()
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(batchContext())
|
|
||||||
vi.mocked(getReceivingContext).mockResolvedValue({ batch: batchContext().appointment, agreements: [], pendingChanges: [], plans: [], executionScope: { version: 'execution-v1', members: [] }, transport: { version: 'scope-v1', vehicles: [], blockReasons: [] }, allowedActions: [], blockReasons: [] })
|
|
||||||
})
|
|
||||||
it('renders all current 40/20 destinations for the bound customer and directly opens the exact customer adjustment', async () => {
|
|
||||||
const context = batchContext(), forty = batchContext('AP-40', 'FBA_APPOINTMENT:40').appointment, twenty = batchContext('AP-20', 'FBA_APPOINTMENT:20').appointment
|
|
||||||
forty.items[0]!.packageCount = 40; forty.items[1]!.packageCount = 999; twenty.items = [{ ...context.appointment.items[0]!, packageCount: 20 }]
|
|
||||||
context.currentBatches = [forty, twenty]; vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('40 箱'); expect(wrapper.text()).toContain('20 箱'); expect(wrapper.text()).not.toContain('999')
|
|
||||||
expect(wrapper.text()).not.toContain('internal-dispatch'); expect(wrapper.text()).not.toContain('customer-a')
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '调整本客户先送 / 后送')!.trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkReceivingPanel' }).props()).toMatchObject({ batchKey: 'FBA_APPOINTMENT:1', initialCustomerId: 'customer-a' })
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('continues a current destination by its batch and customer rather than guessing a work key', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '继续本批当前工作')!.trigger('click'); await flushPromises()
|
|
||||||
const continuation = wrapper.getComponent({ name: 'WorkBatchContinuation' })
|
|
||||||
expect(continuation.props()).toMatchObject({ batchKey: 'FBA_APPOINTMENT:1', customerId: 'customer-a' })
|
|
||||||
continuation.vm.$emit('open', 'real-work-key'); expect(wrapper.emitted('work')).toEqual([['real-work-key']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('uses historical source refs when the bound customer has completely left the original batch', async () => {
|
|
||||||
const context = batchContext(), moved = context.appointment.items[0]!
|
|
||||||
context.appointment.items = [context.appointment.items[1]!]
|
|
||||||
const current = batchContext('AP-LATER', 'FBA_APPOINTMENT:2').appointment
|
|
||||||
current.items = [{ ...moved, packageCount: 70 }]; context.currentBatches = [context.appointment, current]
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('AP-LATER')
|
|
||||||
expect(wrapper.text()).toContain('IN-A · 70 箱')
|
|
||||||
expect(wrapper.text()).not.toContain('范围当前不可匹配'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('reports missing references and read failures without looking up legacy appointment numbers', async () => {
|
|
||||||
const wrapper = render({ dispatches: [{ dispatchNo: 'DS-A', customerId: 'customer-a', packageCount: 70, appointmentBatches: [] }] }); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('没有预约批次引用')
|
|
||||||
expect(getDispatch).not.toHaveBeenCalled(); expect(getFbaAppointment).not.toHaveBeenCalled(); expect(getAppointmentBatch).not.toHaveBeenCalled()
|
|
||||||
vi.mocked(getAppointmentBatch).mockRejectedValueOnce(new Error('read failed'))
|
|
||||||
await wrapper.setProps({ dispatches: [{ dispatchNo: 'DS-A', customerId: 'customer-a', packageCount: 70, appointmentBatches: [reference()] }] }); await flushPromises()
|
|
||||||
expect(wrapper.get('[role="alert"]').text()).toContain('读取失败'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('reads all stable references without a legacy appointment number and deduplicates repeated bindings', async () => {
|
|
||||||
vi.mocked(getAppointmentBatch).mockImplementation(async key => batchContext(key === 'FBA_APPOINTMENT:1' ? 'AP-001' : 'AP-002', key))
|
|
||||||
vi.mocked(getReceivingContext).mockImplementation(async key => ({ batch: batchContext('AP', key).appointment, agreements: [], pendingChanges: [], plans: [], executionScope: { version: 'v1', members: [] }, transport: { version: 'v1', vehicles: [], blockReasons: [] }, allowedActions: [], blockReasons: [] }))
|
|
||||||
const refs = [reference(), reference('FBA_APPOINTMENT:2', 'AP-002')]
|
|
||||||
const wrapper = render({ dispatches: [{ dispatchNo: 'DS-A', customerId: 'customer-a', packageCount: 100, appointmentBatches: refs }, { dispatchNo: 'DS-B', customerId: 'customer-a', packageCount: 70, appointmentBatches: [reference()] }] }); await flushPromises()
|
|
||||||
expect(wrapper.findAll('article')).toHaveLength(2)
|
|
||||||
expect(wrapper.text()).toContain('DS-A、DS-B'); expect(wrapper.text()).toContain('AP-002')
|
|
||||||
expect(getAppointmentBatch).toHaveBeenCalledTimes(2); expect(getReceivingContext).toHaveBeenCalledTimes(2)
|
|
||||||
expect(getDispatch).not.toHaveBeenCalled(); expect(getFbaAppointment).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('reenters a removed customer through history and displays only current 40/20 source destinations', async () => {
|
|
||||||
const context = batchContext(), source = context.appointment.items[0]!
|
|
||||||
const forty = batchContext('AP-40', 'FBA_APPOINTMENT:40').appointment, twenty = batchContext('AP-20', 'FBA_APPOINTMENT:20').appointment
|
|
||||||
forty.items = [{ ...source, packageCount: 40 }, { ...source, id: 'other', sourceKey: 'ORDER:OTHER', inboundCode: 'OTHER-SOURCE', packageCount: 888 }]
|
|
||||||
twenty.items = [{ ...source, packageCount: 20 }, { ...context.appointment.items[1]!, packageCount: 777 }]
|
|
||||||
context.originalSourceRefs.push({ customerId: 'customer-a', sourceKey: 'ORDER:OTHER', destinationKey: 'FBA:ONT8' })
|
|
||||||
context.appointment.items = []; context.currentBatches = [forty, twenty, forty]
|
|
||||||
vi.mocked(getAppointmentBatch).mockResolvedValue(context)
|
|
||||||
const previous = { dispatchNo: 'DS-REMOVED', customerId: 'customer-a', recordVersion: 4, recordedAt: '2026-10-16T01:00:00Z', appointmentBatches: [{ ...reference(), sources: [{ ...reference().sources[0]!, packageCount: 9999 }] }] }
|
|
||||||
const wrapper = render({ dispatches: [], previousDispatches: [previous, { ...previous, recordVersion: 5 }] }); await flushPromises()
|
|
||||||
expect(wrapper.findAll('article')).toHaveLength(1)
|
|
||||||
expect(wrapper.text()).toContain('仅供追溯'); expect(wrapper.text()).toContain('40 箱'); expect(wrapper.text()).toContain('20 箱')
|
|
||||||
for (const unexpected of ['9999', '888', '777', 'OTHER-SOURCE', '调整本客户先送 / 后送']) expect(wrapper.text()).not.toContain(unexpected)
|
|
||||||
const buttons = wrapper.findAll('button').filter(button => button.text() === '继续本批当前工作'); expect(buttons).toHaveLength(2)
|
|
||||||
await buttons[1]!.trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkBatchContinuation' }).props()).toMatchObject({ batchKey: 'FBA_APPOINTMENT:20', customerId: 'customer-a' })
|
|
||||||
expect(getAppointmentBatch).toHaveBeenCalledTimes(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps current cards readable with incomplete history and never fabricates historical entries', async () => {
|
|
||||||
const wrapper = render({ historyUnavailableReason: '部分原绑定记录缺少来源证据' }); await flushPromises()
|
|
||||||
expect(wrapper.get('[role="alert"]').text()).toContain('部分原绑定记录缺少来源证据')
|
|
||||||
expect(wrapper.findAll('article')).toHaveLength(1); expect(wrapper.text()).toContain('当前关联排车单:DS-A')
|
|
||||||
expect(wrapper.text()).not.toContain('历史关联排车单:'); expect(wrapper.text()).toContain('70 箱'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('blocks invalid reference customer identity before reading or opening current work', async () => {
|
|
||||||
const wrapper = render({ dispatches: [{ dispatchNo: 'DS-A', customerId: 'another-customer', packageCount: 70, appointmentBatches: [reference()] }] }); await flushPromises()
|
|
||||||
expect(wrapper.get('[role="alert"]').text()).toContain('客户或来源范围不完整')
|
|
||||||
expect(getAppointmentBatch).not.toHaveBeenCalled(); expect(wrapper.text()).not.toContain('继续本批当前工作'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import { computed, onMounted, onBeforeUnmount, provide, ref, watch } from 'vue'
|
|
||||||
import { onBeforeRouteLeave } from 'vue-router'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { type DispatchBatchReference, type FbaAppointmentDto } from '@/modules/overseas-warehouse'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import AppDialog from '@/shared/components/AppDialog.vue'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import { getAppointmentBatch, type FbaAppointmentBatchContext } from './batchApi'
|
|
||||||
import { getReceivingContext, type ReceivingContext } from './receivingApi'
|
|
||||||
import WorkReceivingPanel from './WorkReceivingPanel.vue'
|
|
||||||
import AppointmentBatchForm from './AppointmentBatchForm.vue'
|
|
||||||
import WorkAppointmentForm from './WorkAppointmentForm.vue'
|
|
||||||
import WorkBatchContinuation from './WorkBatchContinuation.vue'
|
|
||||||
import type { TripPreviousDispatch } from '@/modules/overseas-master-data'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
const props = defineProps<{ dispatches: Array<{ dispatchNo: string; customerId: string; packageCount: number; appointmentBatches: DispatchBatchReference[] }>; previousDispatches: TripPreviousDispatch[]; historyUnavailableReason: string | null; canWrite: boolean }>()
|
|
||||||
const emit = defineEmits<{ updated: []; work: [key: string]; external: [path: string] }>()
|
|
||||||
type Card = { key: string; batchKey: string; batchNo: string | null; customerId: string; current: boolean; dispatchNos: string[]; historyNos: string[]; sources: DispatchBatchReference['sources']; batch: FbaAppointmentBatchContext | null; receiving: ReceivingContext | null; error: ApiErrorDetails | null }
|
|
||||||
const access = useAccessPreviewStore(), cards = ref<Card[]>([]), loading = ref(false)
|
|
||||||
const readable = computed(() => ['platform:appointment:list', 'platform:overseas-warehouse:dispatch:list'].every(permission => access.can(permission)))
|
|
||||||
const selected = ref<{ batchKey: string; customerId: string } | null>(null), mode = ref<'receiving' | 'batch' | 'appointment' | 'continue'>('receiving'), appointmentNo = ref('')
|
|
||||||
const guards = new Set<LeaveGuard>()
|
|
||||||
provide('appointment-work-leave-guard', (guard: LeaveGuard) => { guards.add(guard); return () => guards.delete(guard) })
|
|
||||||
async function canLeave() { for (const guard of guards) if (!await guard()) return false; return true }
|
|
||||||
defineExpose({ canLeave })
|
|
||||||
onBeforeRouteLeave(canLeave)
|
|
||||||
let generation = 0
|
|
||||||
async function load() {
|
|
||||||
if (!readable.value) return
|
|
||||||
const current = ++generation; loading.value = true
|
|
||||||
const batches = new Map<string, Promise<FbaAppointmentBatchContext>>(), receiving = new Map<string, Promise<ReceivingContext>>()
|
|
||||||
const references = new Map<string, Card>()
|
|
||||||
const add = (binding: { dispatchNo: string; customerId: string; appointmentBatches: DispatchBatchReference[] }, historical: boolean) => {
|
|
||||||
for (const reference of binding.appointmentBatches) {
|
|
||||||
const key = JSON.stringify([reference.batchKey, reference.customerId])
|
|
||||||
let card = references.get(key)
|
|
||||||
if (!card) { card = { key, batchKey: reference.batchKey, batchNo: reference.batchNo, customerId: reference.customerId, current: false, dispatchNos: [], historyNos: [], sources: [], batch: null, receiving: null, error: null }; references.set(key, card) }
|
|
||||||
if (reference.customerId !== binding.customerId || !reference.batchKey || !reference.sources.length) card.error = { message: '排车引用的客户或来源范围不完整,请核对原排车单。' }
|
|
||||||
card.current ||= !historical
|
|
||||||
const numbers = historical ? card.historyNos : card.dispatchNos
|
|
||||||
if (!numbers.includes(binding.dispatchNo)) numbers.push(binding.dispatchNo)
|
|
||||||
for (const source of reference.sources) if (!card.sources.some(existing => existing.sourceKey === source.sourceKey && existing.destinationKey === source.destinationKey)) card.sources.push(source)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
props.dispatches.forEach(binding => add(binding, false))
|
|
||||||
props.previousDispatches.forEach(binding => add(binding, true))
|
|
||||||
const loaded = await Promise.all([...references.values()].map(async card => {
|
|
||||||
if (card.error) return card
|
|
||||||
try {
|
|
||||||
if (!batches.has(card.batchKey)) batches.set(card.batchKey, getAppointmentBatch(card.batchKey))
|
|
||||||
if (!receiving.has(card.batchKey)) receiving.set(card.batchKey, getReceivingContext(card.batchKey))
|
|
||||||
const [batch, scope] = await Promise.all([batches.get(card.batchKey)!, receiving.get(card.batchKey)!])
|
|
||||||
if (batch.appointment.batchKey !== card.batchKey || scope.batch.batchKey !== card.batchKey) throw new Error('批次范围不匹配')
|
|
||||||
card.batch = batch; card.receiving = scope
|
|
||||||
} catch (cause) { card.error = getApiErrorDetails(cause, '本客户预约与去向读取失败') }
|
|
||||||
return card
|
|
||||||
}))
|
|
||||||
if (current === generation) { cards.value = loaded; loading.value = false }
|
|
||||||
}
|
|
||||||
function customerName(card: Card) { return card.receiving?.agreements.flatMap(row => row.members).find(member => member.customerId === card.customerId)?.customerName || '—' }
|
|
||||||
function destinations(card: Card) {
|
|
||||||
if (!card.batch) return []
|
|
||||||
const original = new Set(card.batch.originalSourceRefs.filter(item => item.customerId === card.customerId && card.sources.some(source => source.sourceKey === item.sourceKey && source.destinationKey === item.destinationKey)).map(item => JSON.stringify([item.sourceKey, item.destinationKey])))
|
|
||||||
return [...new Map(card.batch.currentBatches.map(batch => [batch.batchKey, batch])).values()].map(batch => ({ batch, items: batch.items.filter(item => item.customerId === card.customerId && original.has(JSON.stringify([item.sourceKey, item.destinationKey])) && (item.packageCount == null || item.packageCount > 0)) })).filter(row => row.items.length)
|
|
||||||
}
|
|
||||||
async function open(batchKey: string, customerId: string, next: 'receiving' | 'batch' | 'continue') { if (await canLeave()) { selected.value = { batchKey, customerId }; mode.value = next } }
|
|
||||||
async function openAppointment(number: string) { if (await canLeave()) { appointmentNo.value = number; mode.value = 'appointment' } }
|
|
||||||
async function close(done: () => void) { if (await canLeave()) { done(); selected.value = null } }
|
|
||||||
function saved(appointment: FbaAppointmentDto) { if (appointment.batchKey && selected.value) { selected.value = { ...selected.value, batchKey: appointment.batchKey }; mode.value = 'continue' }; updated() }
|
|
||||||
function updated() { emit('updated'); void load() }
|
|
||||||
watch(() => JSON.stringify([props.dispatches, props.previousDispatches]), () => { void load() })
|
|
||||||
onMounted(load)
|
|
||||||
onBeforeUnmount(() => { ++generation })
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section aria-label="本车客户预约与后送去向">
|
|
||||||
<p v-if="!readable">需要预约及排车列表权限才能读取客户预约范围。</p>
|
|
||||||
<p v-if="loading">正在核对本车客户的预约与当前去向…</p>
|
|
||||||
<el-button :loading="loading" @click="load">刷新客户预约与去向</el-button>
|
|
||||||
<p v-if="historyUnavailableReason" role="alert">历史预约引用读取不完整:{{ historyUnavailableReason }}。当前车次仍可查看,请重试读取后再核对历史去向。</p><p v-for="binding in dispatches.filter(row => !row.appointmentBatches.length)" :key="binding.dispatchNo" role="status">{{ binding.dispatchNo }}:本排车单没有预约批次引用,请从原排车单核对业务来源。</p><article v-for="card in cards" :key="card.key" class="trip-customer-card">
|
|
||||||
<h4>{{ customerName(card) }} · {{ card.batchNo || '批次业务号未提供' }}</h4><p v-if="card.current">当前关联排车单:{{ card.dispatchNos.join('、') }}</p><p v-if="card.historyNos.length">历史关联排车单:{{ card.historyNos.join('、') }} · 仅供追溯,不代表当前装载或可排数量。</p>
|
|
||||||
<LoadErrorState v-if="card.error" title="本客户范围不可用" :message="card.error.message" @retry="load" />
|
|
||||||
<template v-if="card.batch && card.receiving">
|
|
||||||
<p v-for="pending in card.receiving.pendingChanges.filter(row => row.intent.customerId === card.customerId)" :key="pending.changeKey" role="status">待仓库回复:{{ pending.intent.reason }}。原安排保留,请继续处理。</p>
|
|
||||||
<el-button v-if="card.current" :disabled="loading || !canWrite" @click="open(card.batch.appointment.batchKey!, card.customerId, 'receiving')">调整本客户先送 / 后送</el-button>
|
|
||||||
<el-button v-if="card.current" :disabled="loading" @click="open(card.batch.appointment.batchKey!, card.customerId, 'batch')">查看批次与完整去向</el-button>
|
|
||||||
<div v-for="destination in destinations(card)" :key="destination.batch.batchKey"><b>{{ destination.batch.appointmentNo }}</b><p>{{ destination.batch.plannedDate || '日期未定' }}</p><p v-for="item in destination.items" :key="item.id">{{ item.inboundCode || '—' }} · {{ item.packageCount == null ? '箱数待核实' : `${item.packageCount} 箱` }}</p><el-button :disabled="loading" @click="open(destination.batch.batchKey!, card.customerId, 'continue')">继续本批当前工作</el-button></div>
|
|
||||||
<p v-if="!destinations(card).length">原客户来源范围当前不可匹配,请核对完整批次去向;此处不代表已完成或没有后送需求。</p>
|
|
||||||
</template>
|
|
||||||
</article>
|
|
||||||
<p v-if="readable && !loading && !cards.length">当前没有可读取的预约批次引用。</p>
|
|
||||||
<AppDialog :model-value="!!selected" title="客户预约与后送安排" width="min(1120px, calc(100vw - 48px))" class="admin-density-dialog admin-density admin-workbench is-dialog" fullscreenable append-to-body :show-footer="false" :before-close="close" :close-on-click-modal="true" :close-on-press-escape="true" destroy-on-close>
|
|
||||||
<template v-if="selected">
|
|
||||||
<WorkReceivingPanel v-if="mode === 'receiving'" :key="`${selected.batchKey}:${selected.customerId}`" :batch-key="selected.batchKey" :initial-customer-id="selected.customerId" :can-write="canWrite" @updated="updated" @appointment="openAppointment" @batch="key => open(key, selected!.customerId, 'batch')" @external="path => emit('external', path)" />
|
|
||||||
<AppointmentBatchForm v-else-if="mode === 'batch'" :key="selected.batchKey" :batch-key="selected.batchKey" @updated="updated" @appointment="openAppointment" />
|
|
||||||
<WorkAppointmentForm v-else-if="mode === 'appointment'" :key="appointmentNo" :appointment-no="appointmentNo" :cancel="false" :can-write="canWrite" @saved="saved" @batch="key => open(key, selected!.customerId, 'batch')" @receiving="key => open(key, selected!.customerId, 'receiving')" />
|
|
||||||
<WorkBatchContinuation v-else :key="`${selected.batchKey}:${selected.customerId}`" :batch-key="selected.batchKey" :customer-id="selected.customerId" @open="key => emit('work', key)" />
|
|
||||||
</template>
|
|
||||||
</AppDialog>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
<style scoped>.trip-customer-card { padding-block: var(--admin-space-4); border-bottom: 1px solid var(--workbench-border); }</style>
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkAppointmentForm from './WorkAppointmentForm.vue'
|
|
||||||
import { getFbaAppointment, updateFbaAppointment, type FbaAppointmentDto } from '@/modules/overseas-warehouse'
|
|
||||||
import { deleteAppointment } from './api'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => true }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
|
||||||
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getFbaAppointment: vi.fn(), updateFbaAppointment: vi.fn() }))
|
|
||||||
vi.mock('./api', async original => ({ ...await original<typeof import('./api')>(), deleteAppointment: vi.fn() }))
|
|
||||||
const detail: FbaAppointmentDto = { id: '1', appointmentNo: 'AP-001', batchKey: 'FBA_APPOINTMENT:1', version: 3, originWarehouseId: 'warehouse-1', fbaWarehouseCode: 'ONT8', selectedCount: 1, items: [], appointmentStatus: 'SUCCESS', confirmationNo: 'EXT-001', appointmentAt: '2026-10-15T23:30:00', appointmentEndAt: '2026-10-16T01:00:00', appointmentStartUtc: '2026-10-16T06:30:00Z', appointmentEndUtc: '2026-10-16T08:00:00Z', timezone: 'America/Los_Angeles' }
|
|
||||||
function render(cancel = false) { return mount(WorkAppointmentForm, { props: { appointmentNo: 'AP-001', cancel, canWrite: true }, global: { stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, FbaAppointmentFields: { name: 'FbaAppointmentFields', props: ['model', 'disabled'], template: '<div />' }, LoadErrorState: { props: ['message'], template: '<section role="alert">{{ message }}<button @click="$emit(\'retry\')">重试读取</button></section>' }, ApiErrorMeta: true } } }) }
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); vi.mocked(getFbaAppointment).mockResolvedValue(detail); vi.mocked(updateFbaAppointment).mockResolvedValue(detail) })
|
|
||||||
it('initializes confirmed facts after an initial read failure instead of showing an empty editable plan', async () => {
|
|
||||||
vi.mocked(getFbaAppointment).mockRejectedValueOnce(new Error('来源暂不可用'))
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.findComponent({ name: 'FbaAppointmentFields' }).exists()).toBe(false)
|
|
||||||
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
|
|
||||||
const model = wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model')
|
|
||||||
expect(model.confirmationNo).toBe('EXT-001'); expect(model.appointmentStatus).toBe('SUCCESS')
|
|
||||||
expect(model.appointmentAt).toBe('2026-10-15T23:30:00'); expect(model.startOffset).toBe('-07:00')
|
|
||||||
expect(wrapper.findAll('button').find(button => button.text() === '保存预约安排')!.attributes('disabled')).toBeDefined()
|
|
||||||
expect(updateFbaAppointment).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('preserves both dates of an existing cross-day appointment and its explicit offsets in the original business command', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model').appointmentRemark = '已核对仓库回复'
|
|
||||||
await flushPromises()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '保存预约安排')!.trigger('click'); await flushPromises()
|
|
||||||
expect(updateFbaAppointment).toHaveBeenCalledWith('AP-001', expect.objectContaining({ version: 3, details: expect.objectContaining({ appointmentAt: '2026-10-15T23:30:00', appointmentEndAt: '2026-10-16T01:00:00', startOffset: '-07:00', endOffset: '-07:00' }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not resubmit unchanged appointment facts, including whitespace-only edits', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const save = wrapper.findAll('button').find(button => button.text() === '保存预约安排')!
|
|
||||||
expect(save.attributes('disabled')).toBeDefined()
|
|
||||||
wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model').confirmationNo = ' EXT-001 '
|
|
||||||
await flushPromises(); await save.trigger('click')
|
|
||||||
expect(updateFbaAppointment).not.toHaveBeenCalled()
|
|
||||||
expect(wrapper.text()).toContain('无需重复保存'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not edit or cancel replaced snapshots and offers the stable batch context for replacement history', async () => {
|
|
||||||
vi.mocked(getFbaAppointment).mockResolvedValue({ ...detail, replacementAppointmentNos: ['AP-NEW'], replacementBatchKeys: ['FBA_APPOINTMENT:2'], repartitionReason: '分批送仓' })
|
|
||||||
const wrapper = render(true); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('原预约已被替代'); expect(wrapper.text()).toContain('AP-NEW')
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '确认取消并继续跟进')!.trigger('click')
|
|
||||||
expect(deleteAppointment).not.toHaveBeenCalled()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '查看替代批次')!.trigger('click')
|
|
||||||
expect(wrapper.emitted('batch')).toEqual([['FBA_APPOINTMENT:1']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
const cancelled: FbaAppointmentDto = { ...detail, version: 4, appointmentStatus: 'CANCELLED', confirmationNo: null, plannedDate: null, plannedAt: null, plannedEndAt: null, appointmentAt: null, appointmentEndAt: null, appointmentStartUtc: null, appointmentEndUtc: null }
|
|
||||||
it('rebooks the cancelled original batch as undated pending without creating or reallocating cargo', async () => {
|
|
||||||
vi.mocked(getFbaAppointment).mockResolvedValueOnce(cancelled).mockResolvedValue({ ...cancelled, version: 5, appointmentStatus: 'PENDING' })
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('货物分配仍保留')
|
|
||||||
const model = wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model')
|
|
||||||
expect(model.appointmentStatus).toBe('PENDING'); expect(model.confirmationNo).toBe(''); expect(model.appointmentAt).toBe('')
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '保存本批重新预约')!.trigger('click'); await flushPromises()
|
|
||||||
expect(updateFbaAppointment).toHaveBeenCalledWith('AP-001', expect.objectContaining({ version: 4, idempotencyKey: expect.any(String), details: expect.objectContaining({ appointmentStatus: 'PENDING', plannedDate: null, confirmationNo: null, appointmentAt: null, appointmentEndAt: null }) }))
|
|
||||||
const payload = vi.mocked(updateFbaAppointment).mock.calls[0]![1]
|
|
||||||
expect(payload).not.toHaveProperty('items'); expect(payload).not.toHaveProperty('sources')
|
|
||||||
expect(deleteAppointment).not.toHaveBeenCalled(); expect(wrapper.emitted('saved')).toHaveLength(1)
|
|
||||||
expect(wrapper.findAll('button').find(button => button.text() === '保存预约安排')!.attributes('disabled')).toBeDefined()
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('retries an uncertain rebooking using the identical command, and preserves input on an explicit conflict', async () => {
|
|
||||||
vi.mocked(getFbaAppointment).mockResolvedValueOnce(cancelled).mockResolvedValue({ ...cancelled, version: 6 })
|
|
||||||
vi.mocked(updateFbaAppointment).mockRejectedValueOnce(new Error('unknown outcome')).mockRejectedValueOnce(new ApiResponseError('外部约号已占用', 'A0409', 409))
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const fields = wrapper.getComponent({ name: 'FbaAppointmentFields' })
|
|
||||||
Object.assign(fields.props('model'), { appointmentStatus: 'SUCCESS', confirmationNo: 'NEW-EXT', appointmentAt: '2026-10-20T10:00:00' })
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '保存本批重新预约')!.trigger('click'); await flushPromises()
|
|
||||||
const first = vi.mocked(updateFbaAppointment).mock.calls[0]![1]
|
|
||||||
expect(fields.props('disabled')).toBe(true)
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '重试本次保存')!.trigger('click'); await flushPromises()
|
|
||||||
expect(updateFbaAppointment).toHaveBeenNthCalledWith(2, 'AP-001', first)
|
|
||||||
expect(fields.props('model').confirmationNo).toBe('NEW-EXT'); expect(fields.props('disabled')).toBe(false)
|
|
||||||
expect(wrapper.emitted('saved')).toBeUndefined()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '保存本批重新预约')!.trigger('click'); await flushPromises()
|
|
||||||
const next = vi.mocked(updateFbaAppointment).mock.calls[2]![1]
|
|
||||||
expect(next.version).toBe(6); expect(next.idempotencyKey).not.toBe(first.idempotencyKey)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('cannot cancel twice or rebook with read-only access', async () => {
|
|
||||||
vi.mocked(getFbaAppointment).mockResolvedValue(cancelled)
|
|
||||||
const wrapper = render(true); await flushPromises()
|
|
||||||
expect(wrapper.findAll('button').find(button => button.text() === '确认取消并继续跟进')!.attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.setProps({ cancel: false, canWrite: false }); await flushPromises()
|
|
||||||
expect(wrapper.findAll('button').find(button => button.text() === '保存本批重新预约')!.attributes('disabled')).toBeDefined()
|
|
||||||
expect(updateFbaAppointment).not.toHaveBeenCalled(); expect(deleteAppointment).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import './appointmentNativeForms.css'
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import { computed, onMounted, reactive, ref } from 'vue'
|
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { getFbaAppointment, updateFbaAppointment, FbaAppointmentFields, createAppointmentForm, appointmentFormError, appointmentPayload, type FbaAppointmentDto } from '@/modules/overseas-warehouse'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import { deleteAppointment } from './api'
|
|
||||||
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
|
|
||||||
const props = defineProps<{ appointmentNo: string; cancel: boolean; canWrite: boolean }>()
|
|
||||||
const emit = defineEmits<{ saved: [appointment: FbaAppointmentDto]; batch: [key: string]; receiving: [key: string] }>()
|
|
||||||
const access = useAccessPreviewStore(), detail = ref<FbaAppointmentDto | null>(null)
|
|
||||||
const form = reactive(createAppointmentForm()), reason = ref(''), baseline = ref(JSON.stringify(appointmentPayload(form)))
|
|
||||||
const loading = ref(false), saving = ref(false), error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null)
|
|
||||||
let initialized = false
|
|
||||||
type SaveRequest = { kind: 'update'; payload: { details: ReturnType<typeof appointmentPayload>; version: number; idempotencyKey: string } } | { kind: 'cancel'; version: number; reason: string }
|
|
||||||
const pending = ref<SaveRequest | null>(null)
|
|
||||||
const changed = computed(() => JSON.stringify(appointmentPayload(form)) !== baseline.value)
|
|
||||||
useWorkDraft(computed(() => changed.value || !!reason.value), computed(() => saving.value || !!pending.value))
|
|
||||||
const replaced = computed(() => !!detail.value?.replacementAppointmentNos?.length || !!detail.value?.replacementBatchKeys?.length)
|
|
||||||
const rebooking = computed(() => !props.cancel && detail.value?.appointmentStatus === 'CANCELLED' && !replaced.value)
|
|
||||||
const writable = computed(() => props.canWrite && !replaced.value && (!props.cancel || detail.value?.appointmentStatus !== 'CANCELLED') && access.can(props.cancel ? 'platform:appointment:delete' : 'platform:overseas-warehouse:inbound-order:fba-appointment'))
|
|
||||||
async function load(preserve = false) {
|
|
||||||
loading.value = true; error.value = null
|
|
||||||
try {
|
|
||||||
detail.value = await getFbaAppointment(props.appointmentNo)
|
|
||||||
if (!preserve || !initialized) {
|
|
||||||
Object.assign(form, createAppointmentForm(detail.value)); if (rebooking.value) form.appointmentStatus = 'PENDING'
|
|
||||||
baseline.value = JSON.stringify(appointmentPayload(form)); initialized = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (cause) { error.value = getApiErrorDetails(cause, '预约详情读取失败') }
|
|
||||||
finally { loading.value = false }
|
|
||||||
}
|
|
||||||
async function save() {
|
|
||||||
if (!detail.value || !writable.value || loading.value || error.value || saving.value) return
|
|
||||||
if (!props.cancel && !pending.value && !changed.value && !rebooking.value) return
|
|
||||||
if (!pending.value) {
|
|
||||||
if (props.cancel) {
|
|
||||||
if (!reason.value.trim()) { ElMessage.warning('请填写取消原因'); return }
|
|
||||||
pending.value = { kind: 'cancel', version: detail.value.version, reason: reason.value.trim() }
|
|
||||||
} else {
|
|
||||||
const invalid = appointmentFormError(form); if (invalid) { ElMessage.warning(invalid); return }
|
|
||||||
pending.value = { kind: 'update', payload: { details: appointmentPayload(form), version: detail.value.version, idempotencyKey: crypto.randomUUID() } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
saving.value = true; saveError.value = null
|
|
||||||
try {
|
|
||||||
if (pending.value.kind === 'cancel') await deleteAppointment(props.appointmentNo, pending.value.version, pending.value.reason)
|
|
||||||
else detail.value = await updateFbaAppointment(props.appointmentNo, pending.value.payload)
|
|
||||||
pending.value = null; reason.value = ''; baseline.value = JSON.stringify(appointmentPayload(form))
|
|
||||||
ElMessage.success(props.cancel ? '原预约已取消,工作需求继续跟进' : '预约安排已保存'); emit('saved', detail.value); await load()
|
|
||||||
} catch (cause) { saveError.value = getApiErrorDetails(cause, '保存结果待确认,请重试本次保存'); if (rejectedCommand(cause)) { pending.value = null; await load(true) } }
|
|
||||||
finally { saving.value = false }
|
|
||||||
}
|
|
||||||
onMounted(() => load())
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section class="work-form appointment-native-form" aria-label="预约安排">
|
|
||||||
<h3>{{ cancel ? '取消本次预约' : rebooking ? '沿原批次重新预约' : '登记预约安排' }}</h3>
|
|
||||||
<LoadErrorState v-if="error" title="预约详情读取失败" :message="error.message" :loading="loading" @retry="load(true)"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<p v-if="loading">正在读取原预约…</p>
|
|
||||||
<template v-if="detail">
|
|
||||||
<p>{{ detail.fbaWarehouseCode }} · {{ detail.appointmentNo }}</p>
|
|
||||||
<p v-if="rebooking">原预约已取消,货物分配仍保留。重新预约将更新本批安排,保留取消历史;请重新填写目标日期或仓库确认,日期未定也可先保存待预约。</p>
|
|
||||||
<p v-if="replaced">原预约已被替代,保留历史只读。当前批次:{{ detail.replacementAppointmentNos?.join('、') || '—' }}。{{ detail.repartitionReason }}</p>
|
|
||||||
<el-button v-if="detail.batchKey && !saving && !pending" @click="emit('batch', detail.batchKey)">{{ replaced ? '查看替代批次' : '分批 / 合并与货物来源' }}</el-button>
|
|
||||||
<el-button v-if="detail.batchKey && !replaced && !saving && !pending" :disabled="loading || !!error" @click="emit('receiving', detail.batchKey)">客户调整 / 共同预约范围</el-button>
|
|
||||||
<template v-if="cancel"><p>取消原预约并保留历史;工作需求与后续跟进仍保留。已有运输安排须满足原业务取消条件。</p><label>取消原因<textarea v-model="reason" :disabled="!writable || saving || !!pending" maxlength="1000" class="workbench-input" /></label></template>
|
|
||||||
<FbaAppointmentFields v-else :model="form" :appointment-no="detail.appointmentNo" :timezone="detail.timezone" :disabled="!writable || loading || !!error || saving || !!pending" />
|
|
||||||
<p v-if="!writable">当前预约仅可查看。</p>
|
|
||||||
<LoadErrorState v-if="saveError" title="预约未保存" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState>
|
|
||||||
<p v-if="!cancel && !rebooking && writable && !changed && !pending">预约内容未修改,无需重复保存。</p>
|
|
||||||
<el-button :type="cancel ? 'danger' : 'primary'" :disabled="!writable || loading || !!error || (!cancel && !rebooking && !pending && !changed)" :loading="saving" @click="save">{{ pending ? '重试本次保存' : cancel ? '确认取消并继续跟进' : rebooking ? '保存本批重新预约' : '保存预约安排' }}</el-button>
|
|
||||||
</template>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
import WorkBatchContinuation from './WorkBatchContinuation.vue'
|
|
||||||
import { resolveBatchWork } from './workApi'
|
|
||||||
import { workDetail, workItem } from './work.test-support'
|
|
||||||
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), resolveBatchWork: vi.fn() }))
|
|
||||||
function render() { return mount(WorkBatchContinuation, { props: { batchKey: 'FBA_APPOINTMENT:40', labels: [{ customerId: 'customer-a', label: 'IN-A' }] }, global: { stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, LoadErrorState: { props: ['message'], template: '<div role="alert">{{ message }}<button @click="$emit(\'retry\')">重试读取</button></div>' }, ApiErrorMeta: true } } }) }
|
|
||||||
beforeEach(() => vi.clearAllMocks())
|
|
||||||
afterEach(() => vi.useRealTimers())
|
|
||||||
it('shows synchronization after a successful save and continues by reading without resubmitting', async () => {
|
|
||||||
vi.useFakeTimers()
|
|
||||||
vi.mocked(resolveBatchWork).mockRejectedValueOnce(new ApiResponseError('预约批次或运输关联已变化,服务端正在协调完整工作清单', 'A0409', 409)).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:40', customerId: null, detail: workDetail({ item: workItem({ workItemKey: 'actual-key' }) }), candidates: [] })
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('同步中')
|
|
||||||
expect(wrapper.text()).toContain('无需重复提交')
|
|
||||||
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
|
|
||||||
await vi.advanceTimersByTimeAsync(2000); await flushPromises()
|
|
||||||
expect(wrapper.emitted('open')).toEqual([['actual-key']])
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('requires a customer selection for multiple real work candidates and uses the selected resolver result', async () => {
|
|
||||||
vi.mocked(resolveBatchWork).mockResolvedValueOnce({ batchKey: 'FBA_APPOINTMENT:40', customerId: null, detail: null, candidates: [{ customerId: 'customer-a', workItemKey: 'real-work-a', batchNo: 'AP-40' }, { customerId: 'customer-b', workItemKey: 'real-work-b', batchNo: 'AP-40' }] }).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:40', customerId: 'customer-a', detail: workDetail({ item: workItem({ workItemKey: 'current-work-a' }) }), candidates: [] })
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.emitted('open')).toBeUndefined(); expect(wrapper.text()).toContain('IN-A'); expect(wrapper.text()).not.toContain('customer-a')
|
|
||||||
await wrapper.findAll('button')[0]!.trigger('click'); await flushPromises()
|
|
||||||
expect(resolveBatchWork).toHaveBeenLastCalledWith('FBA_APPOINTMENT:40', 'customer-a', expect.any(AbortSignal))
|
|
||||||
expect(wrapper.emitted('open')).toEqual([['current-work-a']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps saved results on resolution failure and only retries the read', async () => {
|
|
||||||
vi.mocked(resolveBatchWork).mockRejectedValueOnce(new Error('同步未完成')).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:40', customerId: null, detail: workDetail({ item: workItem({ workItemKey: 'actual-key' }) }), candidates: [] })
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('无需重复提交'); expect(wrapper.emitted('open')).toBeUndefined()
|
|
||||||
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
|
|
||||||
expect(resolveBatchWork).toHaveBeenCalledTimes(2); expect(wrapper.emitted('open')).toEqual([['actual-key']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { resolveBatchWork, type BatchWorkResolution } from './workApi'
|
|
||||||
import { useWorkSyncRead } from './useWorkSyncRead'
|
|
||||||
const props = defineProps<{ batchKey: string; customerId?: string; labels?: Array<{ customerId: string; label: string }> }>()
|
|
||||||
const emit = defineEmits<{ open: [key: string] }>()
|
|
||||||
const resolution = ref<BatchWorkResolution | null>(null), error = ref<ApiErrorDetails | null>(null), loading = ref(false)
|
|
||||||
const controller = new AbortController()
|
|
||||||
const syncRead = useWorkSyncRead(), syncing = syncRead.syncing
|
|
||||||
async function load(customerId = props.customerId) {
|
|
||||||
loading.value = true; error.value = null
|
|
||||||
try { const value = await syncRead.read(() => resolveBatchWork(props.batchKey, customerId, controller.signal), controller.signal); if (controller.signal.aborted) return; resolution.value = value; if (value.detail) emit('open', value.detail.item.workItemKey) }
|
|
||||||
catch (cause) { if (!controller.signal.aborted) error.value = getApiErrorDetails(cause, '当前批次下一步读取失败') }
|
|
||||||
finally { loading.value = false }
|
|
||||||
}
|
|
||||||
onMounted(() => load())
|
|
||||||
onBeforeUnmount(() => controller.abort())
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section aria-label="当前批次续办">
|
|
||||||
<p role="status">{{ syncing ? '预约工作清单同步中,正在自动读取当前批次下一步;已保存内容无需重复提交。' : '正在定位当前批次的工作事项;已保存的内容无需重复提交。' }}</p>
|
|
||||||
<LoadErrorState v-if="error" title="当前批次下一步读取失败" :message="error.message" :loading="loading" @retry="load()"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<template v-if="resolution && !resolution.detail && !error"><p>本批有多个客户,请选择本次继续办理的货物。</p><el-button v-for="(candidate, index) in resolution.candidates" :key="candidate.workItemKey" :disabled="loading" @click="load(candidate.customerId)">{{ candidate.batchNo || '—' }} · {{ labels?.find(row => row.customerId === candidate.customerId)?.label || `客户范围 ${index + 1}` }}</el-button><p v-if="!resolution.candidates.length">当前没有可定位的送仓事项,请核对服务端同步结果。</p></template>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import { mount } from '@vue/test-utils'
|
|
||||||
import { afterEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkCalendarPanel from './WorkCalendarPanel.vue'
|
|
||||||
import { workCalendar } from './work.test-support'
|
|
||||||
import { workTypes } from './workApi'
|
|
||||||
function render() { return mount(WorkCalendarPanel, { props: { anchor: '2026-10-15', mode: 'month', flow: '', types: [...workTypes], calendar: workCalendar, loading: false, failed: false, reference: false, arrivals: [], referenceReady: false } }) }
|
|
||||||
afterEach(() => vi.useRealTimers())
|
|
||||||
it('keeps a busy day at five type summaries and consumes authoritative transport counts unchanged', async () => {
|
|
||||||
const wrapper = render()
|
|
||||||
const counts = { PICKUP: 300, WAREHOUSE_RECEIPT: 300, DELIVERY: 2, TRANSPORT: 1, EMPTY_RETURN: 300 }
|
|
||||||
await wrapper.setProps({ calendar: { ...workCalendar, days: [{ ...workCalendar.days[0]!, total: 903, typeCounts: counts }] } })
|
|
||||||
const day = wrapper.get('[data-date="2026-10-15"]')
|
|
||||||
expect(day.findAll('.type-counts button')).toHaveLength(5)
|
|
||||||
expect(day.get('[data-type="TRANSPORT"]').text()).toContain('1')
|
|
||||||
expect(day.get('[data-type="DELIVERY"]').text()).toContain('2')
|
|
||||||
await day.get('[data-type="TRANSPORT"]').trigger('click')
|
|
||||||
expect(wrapper.emitted('day')).toEqual([['2026-10-15', 'TRANSPORT']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('offers all four flows directly and emits the original filter values with an exclusive selection', async () => {
|
|
||||||
const wrapper = render()
|
|
||||||
const buttons = wrapper.findAll('.flow-controls button')
|
|
||||||
expect(buttons.map(button => button.text())).toEqual(['全部流程', '海外仓中转', '整柜直送', '路线待确认'])
|
|
||||||
expect(wrapper.find('select').exists()).toBe(false)
|
|
||||||
for (const [index, flow] of (['', 'TRANSFER', 'DIRECT', 'UNKNOWN'] as const).entries()) {
|
|
||||||
await buttons[index]!.trigger('click')
|
|
||||||
expect(wrapper.emitted('flow')?.at(-1)).toEqual([flow])
|
|
||||||
await wrapper.setProps({ flow })
|
|
||||||
expect(wrapper.findAll('.flow-controls button[aria-pressed=true]')).toHaveLength(1)
|
|
||||||
expect(buttons[index]!.attributes('aria-pressed')).toBe('true')
|
|
||||||
}
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('distinguishes today from the selected day and type without changing the selected scope', async () => {
|
|
||||||
vi.useFakeTimers(); vi.setSystemTime(new Date('2026-10-15T12:00:00'))
|
|
||||||
const wrapper = render()
|
|
||||||
await wrapper.setProps({ selectedDate: '2026-10-16' })
|
|
||||||
expect(wrapper.get('[data-date="2026-10-15"] .day-heading').attributes('aria-current')).toBe('date')
|
|
||||||
expect(wrapper.get('[data-date="2026-10-15"] .day-heading').attributes('aria-pressed')).toBe('false')
|
|
||||||
expect(wrapper.get('[data-date="2026-10-16"]').classes()).toContain('is-selected')
|
|
||||||
await wrapper.setProps({ selectedDate: '2026-10-15', selectedType: 'DELIVERY' })
|
|
||||||
expect(wrapper.get('[data-date="2026-10-15"] [data-type="DELIVERY"]').attributes('aria-pressed')).toBe('true')
|
|
||||||
expect(wrapper.get('[data-date="2026-10-15"] [data-type="PICKUP"]').attributes('aria-pressed')).toBe('false')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('shows the actual cross-month interval and hides empty-day zeros while keeping dates clickable', async () => {
|
|
||||||
const wrapper = render()
|
|
||||||
expect(wrapper.get('.calendar-counts').text()).toContain('2026-09-28 ~ 2026-11-08')
|
|
||||||
const empty = wrapper.get('[data-date="2026-10-01"] .day-heading')
|
|
||||||
expect(empty.text()).toBe('1')
|
|
||||||
expect(empty.attributes('disabled')).toBeUndefined()
|
|
||||||
await empty.trigger('click'); expect(wrapper.emitted('day')).toEqual([['2026-10-01']])
|
|
||||||
expect(wrapper.get('footer').text()).toContain('未定日期请从上方待办查看')
|
|
||||||
await wrapper.setProps({ mode: 'week' })
|
|
||||||
expect(wrapper.findAll('.work-day')).toHaveLength(7)
|
|
||||||
expect(wrapper.get('.view-switch button:last-child').attributes('aria-pressed')).toBe('true')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('renders server type counts instead of individual event cards and opens exact date/type details', async () => {
|
|
||||||
const wrapper = render()
|
|
||||||
expect(wrapper.findAll('.work-day')).toHaveLength(35)
|
|
||||||
const day = wrapper.get('[data-date="2026-10-15"]')
|
|
||||||
expect(day.get('.day-heading').text()).toContain('2 项')
|
|
||||||
await day.get('[data-type="DELIVERY"]').trigger('click')
|
|
||||||
expect(wrapper.emitted('day')).toEqual([['2026-10-15', 'DELIVERY']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not conflate arrivals, no-booking requirements or completed work with confirmed work', async () => {
|
|
||||||
const wrapper = render()
|
|
||||||
await wrapper.setProps({ reference: true, referenceReady: true, arrivals: [{ containerBookingId: '1', cabinetNo: 'D-1', arrivalAt: '2026-10-15T10:00:00', arrivalType: 'ESTIMATED' }] })
|
|
||||||
expect(wrapper.get('[data-date="2026-10-15"] .day-heading').text()).toContain('2 项')
|
|
||||||
expect(wrapper.get('.calendar-counts').text()).toContain('已完成 1')
|
|
||||||
expect(wrapper.get('.calendar-counts').text()).toContain('已落实 0')
|
|
||||||
await wrapper.get('.arrival-reference').trigger('click'); expect(wrapper.emitted('arrivals')).toEqual([['2026-10-15']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('shows explicit all-off and failure states without manufacturing zero aggregates', async () => {
|
|
||||||
const wrapper = render(); await wrapper.setProps({ types: [], calendar: null })
|
|
||||||
expect(wrapper.text()).toContain('全局待办仍可查看'); expect(wrapper.findAll('.type-counts button')).toHaveLength(0)
|
|
||||||
await wrapper.setProps({ types: [...workTypes], failed: true })
|
|
||||||
expect(wrapper.get('.calendar-counts').text()).toBe('工作统计加载失败')
|
|
||||||
expect(wrapper.get('[data-date="2026-10-15"] .day-heading').text()).not.toContain('0 项'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { computed } from 'vue'
|
|
||||||
import { calendarDates, dateKey, type CalendarMode } from './calendar'
|
|
||||||
import { workTypes, type WorkCalendar, type WorkFlow, type WorkType } from './workApi'
|
|
||||||
import { flowLabels, typeLabels } from './workPresentation'
|
|
||||||
import type { ArrivalCalendarEntry } from './api'
|
|
||||||
const props = defineProps<{ anchor: string; mode: CalendarMode; flow: WorkFlow | ''; types: WorkType[]; calendar: WorkCalendar | null; loading: boolean; failed: boolean; reference: boolean; arrivals: ArrivalCalendarEntry[]; referenceReady: boolean; selectedDate?: string; selectedType?: WorkType }>()
|
|
||||||
const emit = defineEmits<{ anchor: [offset: number]; today: []; mode: [value: CalendarMode]; flow: [value: WorkFlow | '']; types: [value: WorkType[]]; reference: [value: boolean]; day: [date: string, type?: WorkType]; arrivals: [date: string] }>()
|
|
||||||
const days = computed(() => calendarDates(props.anchor, props.mode))
|
|
||||||
const today = dateKey(new Date())
|
|
||||||
const flows: Array<{ value: WorkFlow | ''; label: string }> = [{ value: '', label: '全部流程' }, { value: 'TRANSFER', label: flowLabels.TRANSFER }, { value: 'DIRECT', label: flowLabels.DIRECT }, { value: 'UNKNOWN', label: flowLabels.UNKNOWN }]
|
|
||||||
const aggregates = computed(() => new Map(props.calendar?.days.map(day => [day.date, day]) || []))
|
|
||||||
const heading = computed(() => props.mode === 'month' ? `${props.anchor.slice(0, 4)}年${Number(props.anchor.slice(5, 7))}月` : `${days.value[0]} — ${days.value.at(-1)}`)
|
|
||||||
function toggle(type: WorkType, checked: boolean) { emit('types', checked ? [...props.types, type] : props.types.filter(value => value !== type)) }
|
|
||||||
function arrivalCount(date: string) { return props.arrivals.filter(row => row.arrivalAt.slice(0, 10) === date).length }
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section class="work-calendar" :class="{ 'week-view': mode === 'week' }" aria-label="预约工作日历" :aria-busy="loading">
|
|
||||||
<div v-if="$slots.inbox" class="global-work"><slot name="inbox" /></div>
|
|
||||||
<header class="calendar-toolbar">
|
|
||||||
<div class="flow-controls" role="group" aria-label="日历流程"><span class="muted">流程</span><button v-for="option in flows" :key="option.value" type="button" :data-flow="option.value" :aria-pressed="flow === option.value" @click="emit('flow', option.value)">{{ option.label }}</button></div>
|
|
||||||
<div class="period-controls"><div class="view-switch" aria-label="日历视图"><button type="button" :aria-pressed="mode === 'month'" @click="emit('mode', 'month')">月</button><button type="button" :aria-pressed="mode === 'week'" @click="emit('mode', 'week')">周</button></div><button type="button" aria-label="上一时段" @click="emit('anchor', -1)">‹</button><strong>{{ heading }}</strong><button type="button" aria-label="下一时段" @click="emit('anchor', 1)">›</button><button type="button" title="定位到浏览器当前日期" @click="emit('today')">今天</button></div>
|
|
||||||
<span class="muted">作业地点当地时间</span>
|
|
||||||
</header>
|
|
||||||
<div class="work-layers"><span class="muted">显示类型</span><label v-for="type in workTypes" :key="type" :data-type="type"><input type="checkbox" :checked="types.includes(type)" @change="toggle(type, ($event.target as HTMLInputElement).checked)">{{ typeLabels[type] }}</label><label><input type="checkbox" :checked="reference" @change="emit('reference', ($event.target as HTMLInputElement).checked)">到港参考</label></div>
|
|
||||||
<div class="calendar-counts" aria-live="polite">
|
|
||||||
<span v-if="loading">正在读取工作统计…</span><span v-else-if="failed">工作统计加载失败</span><span v-else-if="!types.length">未勾选工作类型,全局待办仍可查看</span>
|
|
||||||
<template v-else-if="calendar"><strong>当前显示区间 {{ calendar.from }} ~ {{ calendar.to }} · {{ calendar.total }} 项工作</strong><span :class="{ 'is-zero': calendar.counts.pending === 0 }">待安排 {{ calendar.counts.pending }}</span><span :class="{ 'is-zero': calendar.counts.confirmed === 0 }">已落实 {{ calendar.counts.confirmed }}</span><span :class="{ 'is-zero': calendar.counts.noBookingRequired === 0 }">无需预约 {{ calendar.counts.noBookingRequired }}</span><span :class="{ 'is-zero': calendar.counts.review === 0 }">需复核 {{ calendar.counts.review }}</span><span :class="{ 'is-zero': calendar.counts.completed === 0 }">已完成 {{ calendar.counts.completed }}</span></template>
|
|
||||||
</div>
|
|
||||||
<div class="weekdays"><span v-for="day in ['一', '二', '三', '四', '五', '六', '日']" :key="day">周{{ day }}</span></div>
|
|
||||||
<div class="calendar-days">
|
|
||||||
<div v-for="date in days" :key="date" class="work-day" :class="{ outside: mode === 'month' && !date.startsWith(anchor.slice(0, 7)), 'is-today': date === today, 'is-selected': date === selectedDate }" :data-date="date">
|
|
||||||
<button class="day-heading" type="button" :disabled="loading || failed || !types.length" :aria-current="date === today ? 'date' : undefined" :aria-pressed="date === selectedDate" :aria-label="`${date} 工作明细`" @click="emit('day', date)"><span class="date-number">{{ Number(date.slice(8)) }}</span><small v-if="date === today" class="today-mark" title="浏览器当前日期">今天</small><span v-if="loading || failed || !types.length" class="day-total">—</span><span v-else-if="(aggregates.get(date)?.total ?? 0) > 0" class="day-total">{{ aggregates.get(date)?.total }} 项</span></button>
|
|
||||||
<div class="type-counts"><template v-if="!loading && !failed && types.length"><button v-for="type in workTypes.filter(type => types.includes(type) && (aggregates.get(date)?.typeCounts[type] ?? 0) > 0)" :key="type" type="button" :data-type="type" :aria-pressed="date === selectedDate && type === selectedType" :aria-label="`${date} ${typeLabels[type]} ${aggregates.get(date)?.typeCounts[type]} 项`" @click="emit('day', date, type)"><span>{{ typeLabels[type] }}</span><b>{{ aggregates.get(date)?.typeCounts[type] }}</b></button></template></div>
|
|
||||||
<button v-if="reference && referenceReady && arrivalCount(date)" type="button" class="arrival-reference" @click="emit('arrivals', date)">到港参考 {{ arrivalCount(date) }} 柜</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<footer class="muted">日历只展示有作业日期的事项,未定日期请从上方待办查看。已执行按实际日期展示;到港参考不计工作量。</footer>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
<style scoped>
|
|
||||||
.work-calendar { min-width: 0; border: 1px solid var(--cc-border); background: var(--admin-surface); }
|
|
||||||
.calendar-toolbar, .period-controls, .work-layers, .calendar-counts { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-3); }
|
|
||||||
.global-work { border-bottom: 1px solid var(--cc-border); }
|
|
||||||
.calendar-toolbar { justify-content: flex-start; column-gap: var(--admin-space-6); padding: var(--admin-space-2) var(--admin-space-5); }
|
|
||||||
.flow-controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-2); }
|
|
||||||
.period-controls strong { min-width: 100px; text-align: center; }
|
|
||||||
.work-layers, .calendar-counts { padding: var(--admin-space-2) var(--admin-space-5); border-top: 1px solid var(--cc-border); }
|
|
||||||
.work-layers label { display: inline-flex; align-items: center; gap: var(--admin-space-2); cursor: pointer; }
|
|
||||||
.calendar-counts { min-height: 24px; font-size: var(--admin-font-caption); }
|
|
||||||
.calendar-counts .is-zero { color: var(--el-text-color-secondary); }
|
|
||||||
.weekdays, .calendar-days { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); }
|
|
||||||
.weekdays { text-align: center; padding-block: var(--admin-space-3); background: var(--el-fill-color-light); }
|
|
||||||
.weekdays span:nth-last-child(-n+2) { color: var(--el-text-color-secondary); }
|
|
||||||
.work-day { height: 146px; min-height: 146px; max-height: 146px; box-sizing: border-box; border-top: 1px solid var(--cc-border); border-right: 1px solid var(--cc-border); padding: var(--admin-space-1); }
|
|
||||||
.week-view .work-day { height: 270px; min-height: 270px; max-height: 270px; }
|
|
||||||
.work-day:nth-child(7n) { border-right: 0; }
|
|
||||||
.outside { background: var(--el-fill-color-lighter); }
|
|
||||||
.work-calendar .day-heading { display: flex; align-items: center; gap: var(--admin-space-1); width: 100%; border: 0; padding: 0; min-height: 24px; background: transparent; margin-bottom: var(--admin-space-1); }
|
|
||||||
.date-number { display: inline-flex; align-items: center; justify-content: center; min-width: 24px; height: 24px; border-radius: 50%; font-weight: 600; font-variant-numeric: tabular-nums; }
|
|
||||||
.is-today .date-number { color: var(--el-color-white); background: var(--el-color-primary); font-weight: 600; }
|
|
||||||
.today-mark { color: var(--el-color-primary); font-size: var(--admin-font-caption); }
|
|
||||||
.day-total { margin-left: auto; color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); }
|
|
||||||
.work-day.is-selected { box-shadow: inset 0 0 0 2px var(--el-color-primary); background: var(--el-color-primary-light-9); }
|
|
||||||
.outside .day-heading { color: var(--el-text-color-secondary); }
|
|
||||||
.type-counts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-auto-rows: minmax(24px, auto); gap: var(--admin-space-1); }
|
|
||||||
.work-calendar .type-counts button { display: flex; align-items: center; justify-content: space-between; gap: 2px; border: 1px solid color-mix(in srgb, currentColor 20%, transparent); padding: 0 var(--admin-space-1); font-size: var(--admin-font-caption); background: color-mix(in srgb, currentColor 7%, var(--admin-surface)); min-width: 0; min-height: 24px; white-space: nowrap; }
|
|
||||||
.work-calendar .type-counts button:hover:not(:disabled) { border-color: currentColor; background: color-mix(in srgb, currentColor 12%, var(--admin-surface)); }
|
|
||||||
.work-calendar .type-counts button[aria-pressed=true] { border-color: currentColor; background: color-mix(in srgb, currentColor 14%, var(--admin-surface)); box-shadow: inset 0 0 0 1px currentColor; }
|
|
||||||
.type-counts b { font-variant-numeric: tabular-nums; }
|
|
||||||
[data-type=PICKUP] { color: var(--el-color-primary); } [data-type=WAREHOUSE_RECEIPT] { color: #8356ad; } [data-type=DELIVERY] { color: #27815c; } [data-type=TRANSPORT] { color: #b26a12; } [data-type=EMPTY_RETURN] { color: #a64f69; }
|
|
||||||
.work-calendar .arrival-reference { display: block; border: 0; background: transparent; padding: 0 var(--admin-space-1); margin-top: var(--admin-space-1); min-height: 24px; font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }
|
|
||||||
.work-calendar .arrival-reference:hover { color: var(--el-text-color-regular); background: var(--el-fill-color-light); }
|
|
||||||
footer { padding: var(--admin-space-3) var(--admin-space-5); }
|
|
||||||
button { font: inherit; cursor: pointer; border-radius: var(--admin-radius); min-height: var(--admin-control-height); color: inherit; border: 1px solid var(--cc-border); background: var(--admin-surface); padding: 0 var(--admin-space-3); }
|
|
||||||
.view-switch { display: inline-flex; }
|
|
||||||
.view-switch button { border-radius: 0; min-width: 36px; }
|
|
||||||
.view-switch button:first-child { border-radius: var(--admin-radius) 0 0 var(--admin-radius); }
|
|
||||||
.view-switch button:last-child { border-radius: 0 var(--admin-radius) var(--admin-radius) 0; margin-left: -1px; }
|
|
||||||
.view-switch button[aria-pressed=true], .flow-controls button[aria-pressed=true] { background: var(--el-color-primary-light-9); border-color: var(--el-color-primary); color: var(--el-color-primary); position: relative; }
|
|
||||||
button:hover:not(:disabled) { border-color: var(--el-color-primary); }
|
|
||||||
button:disabled { cursor: default; opacity: .6; } button:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: 1px; }
|
|
||||||
.muted { color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); }
|
|
||||||
</style>
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { createPinia, setActivePinia } from 'pinia'
|
|
||||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import { http } from '@/shared/api/http'
|
|
||||||
import WorkCommandForm from './WorkCommandForm.vue'
|
|
||||||
import { submitWorkCommand } from './workApi'
|
|
||||||
import { followAction, workDetail, workItem } from './work.test-support'
|
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
|
||||||
|
|
||||||
vi.mock('@/core/auth/platformAuthorization', () => ({ listCurrentPlatformPermissionCodes: vi.fn().mockResolvedValue(['platform:appointment:followup']) }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => true }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
|
||||||
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), submitWorkCommand: vi.fn() }))
|
|
||||||
|
|
||||||
function token(userId: string, exp = Math.floor(Date.now() / 1000) + 1800) {
|
|
||||||
// Keep the numeric JSON literal intact; constructing a JS number would lose precision before decoding.
|
|
||||||
const payload = `{"user_id":${userId},"username":"test_operator","app_code":"PLATFORM","exp":${exp}}`
|
|
||||||
return `header.${Buffer.from(payload).toString('base64url')}.signature`
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
const values = new Map<string, string>()
|
|
||||||
vi.stubGlobal('localStorage', {
|
|
||||||
getItem: (key: string) => values.get(key) ?? null,
|
|
||||||
setItem: (key: string, value: string) => values.set(key, value),
|
|
||||||
removeItem: (key: string) => values.delete(key),
|
|
||||||
})
|
|
||||||
setActivePinia(createPinia())
|
|
||||||
vi.mocked(submitWorkCommand).mockResolvedValue({ item: workItem(), affectedWorkItemKeys: [] })
|
|
||||||
})
|
|
||||||
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
['login', '2110664514823360515'], ['login', '"2110664514823360515"'],
|
|
||||||
['restore', '2110664514823360515'], ['restore', '"2110664514823360515"'],
|
|
||||||
])('preserves the %s session ID through the real follow-up form for JSON %s', async (mode, userId) => {
|
|
||||||
const accessToken = token(userId)
|
|
||||||
if (mode === 'restore') {
|
|
||||||
localStorage.setItem('cc-admin-token', accessToken)
|
|
||||||
localStorage.setItem('cc-admin-permission-codes', '[]')
|
|
||||||
}
|
|
||||||
const auth = useAuthStore()
|
|
||||||
if (mode === 'login') {
|
|
||||||
vi.spyOn(http, 'post').mockResolvedValue({ code: '200', data: { accessToken, refreshToken: 'test-refresh', expiresIn: 1800, refreshExpiresIn: 604800 } })
|
|
||||||
await auth.login('test_operator', 'test-password')
|
|
||||||
}
|
|
||||||
expect(auth.user?.id).toBe('2110664514823360515')
|
|
||||||
expect(auth.isAuthenticated).toBe(true)
|
|
||||||
const wrapper = mount(WorkCommandForm, {
|
|
||||||
props: { detail: workDetail({ item: workItem({ owner: null }) }), action: followAction, refreshing: false },
|
|
||||||
global: {
|
|
||||||
provide: { 'appointment-work-leave-guard': () => () => undefined },
|
|
||||||
stubs: { ElButton: { template: '<button><slot /></button>' }, LoadErrorState: true, ApiErrorMeta: true },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
try {
|
|
||||||
expect((wrapper.get('select').element as HTMLSelectElement).value).toBe('2110664514823360515')
|
|
||||||
await wrapper.get('textarea').setValue('已联系负责人')
|
|
||||||
await wrapper.get('form').trigger('submit')
|
|
||||||
await flushPromises()
|
|
||||||
expect(submitWorkCommand).toHaveBeenCalledWith('work-delivery-1', expect.objectContaining({
|
|
||||||
command: 'SAVE_FOLLOWUP', payload: { ownerId: '2110664514823360515', followupDate: '2026-10-15', note: '已联系负责人' },
|
|
||||||
}))
|
|
||||||
} finally { wrapper.unmount() }
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each([token('2110664514823360515', 1), 'header.%.signature'])('does not restore an expired or malformed token: %s', accessToken => {
|
|
||||||
localStorage.setItem('cc-admin-token', accessToken)
|
|
||||||
const auth = useAuthStore()
|
|
||||||
expect(auth.user).toBeNull()
|
|
||||||
expect(auth.isAuthenticated).toBe(false)
|
|
||||||
expect(localStorage.getItem('cc-admin-token')).toBeNull()
|
|
||||||
})
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
import { DatePickerStub, TimePickerStub } from './temporal-picker.test-support'
|
|
||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkCommandForm from './WorkCommandForm.vue'
|
|
||||||
import { submitWorkCommand, type WorkAction } from './workApi'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
import { followAction, workDetail, workItem } from './work.test-support'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
const session = vi.hoisted(() => ({ canWrite: true }))
|
|
||||||
vi.mock('@/core/auth/auth', () => ({ useAuthStore: () => ({ user: { id: 'user-1', name: '测试调度' } }) }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => session.canWrite }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
|
||||||
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), submitWorkCommand: vi.fn() }))
|
|
||||||
let guard: LeaveGuard
|
|
||||||
function render(action: WorkAction = followAction, detail = workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) })) {
|
|
||||||
return mount(WorkCommandForm, { props: { detail, action, refreshing: false }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: {
|
|
||||||
ElDatePicker: DatePickerStub, ElTimePicker: TimePickerStub,
|
|
||||||
ElButton: { props: ['nativeType', 'disabled'], template: '<button :type="nativeType" :disabled="disabled"><slot /></button>' },
|
|
||||||
LoadErrorState: { props: ['message'], template: '<div role="alert">{{ message }}</div>' }, ApiErrorMeta: true,
|
|
||||||
} } })
|
|
||||||
}
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); session.canWrite = true; vi.mocked(submitWorkCommand).mockResolvedValue({ item: workItem(), affectedWorkItemKeys: [] }) })
|
|
||||||
it('sends only follow-up ownership and feedback, retaining the undated work and the exact retry command', async () => {
|
|
||||||
vi.mocked(submitWorkCommand).mockRejectedValueOnce(new Error('connection lost'))
|
|
||||||
const wrapper = render()
|
|
||||||
await wrapper.get('textarea').setValue('已联系,等待回复'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const first = vi.mocked(submitWorkCommand).mock.calls[0]![1]
|
|
||||||
expect(first).toMatchObject({ command: 'SAVE_FOLLOWUP', expectedVersion: 3, payload: { ownerId: 'user-1', note: '已联系,等待回复', followupDate: '2026-10-15' } })
|
|
||||||
expect(first.payload).not.toHaveProperty('target'); expect(await guard()).toBe(false)
|
|
||||||
expect(wrapper.get('fieldset').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(submitWorkCommand).toHaveBeenNthCalledWith(2, 'work-delivery-1', first)
|
|
||||||
expect(wrapper.emitted('saved')).toHaveLength(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('preserves entered feedback after a conflict and uses the newly read version on an explicit resubmission', async () => {
|
|
||||||
vi.mocked(submitWorkCommand).mockRejectedValueOnce(new ApiResponseError('版本已变化', 'A0409', 409))
|
|
||||||
const wrapper = render(); await wrapper.get('textarea').setValue('保留此反馈')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const first = vi.mocked(submitWorkCommand).mock.calls[0]![1]
|
|
||||||
expect(wrapper.emitted('refresh')).toHaveLength(1)
|
|
||||||
await wrapper.setProps({ detail: workDetail({ item: workItem({ version: 4 }) }) })
|
|
||||||
expect((wrapper.get('textarea').element as HTMLTextAreaElement).value).toBe('保留此反馈')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const second = vi.mocked(submitWorkCommand).mock.calls[1]![1]
|
|
||||||
expect(second.expectedVersion).toBe(4); expect(second.idempotencyKey).not.toBe(first.idempotencyKey)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('uses the distinct review version and never substitutes the item version or marks work complete', async () => {
|
|
||||||
const action: WorkAction = { code: 'RESOLVE_REVIEW', label: '复核安排', targetWorkItemKey: null, target: { kind: 'WORK_COMMAND', command: 'RESOLVE_REVIEW' } }
|
|
||||||
const wrapper = render(action, workDetail({ item: workItem({ allowedActions: [action], reviewRequired: true }), review: { version: 12, reasons: ['到港日期调整'] } }))
|
|
||||||
await wrapper.get('textarea').setValue('已核对原安排'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(submitWorkCommand).toHaveBeenCalledWith('work-delivery-1', expect.objectContaining({ expectedVersion: 3, command: 'RESOLVE_REVIEW', payload: { reviewVersion: 12, note: '已核对原安排' } }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('requires receiving instructions for a customer warehouse that needs no appointment and does not invent a time', async () => {
|
|
||||||
const action: WorkAction = { code: 'SAVE_REQUIREMENT', label: '登记收货要求', targetWorkItemKey: null, target: { kind: 'WORK_COMMAND', command: 'SAVE_REQUIREMENT' } }
|
|
||||||
const wrapper = render(action)
|
|
||||||
await wrapper.get('input[type=checkbox]').setValue(false)
|
|
||||||
await wrapper.findAll('textarea')[1]!.setValue('客户仓确认无需预约')
|
|
||||||
await wrapper.get('form').trigger('submit'); expect(submitWorkCommand).not.toHaveBeenCalled()
|
|
||||||
await wrapper.findAll('textarea')[0]!.setValue('工作日9至16点到仓联系收货人')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(submitWorkCommand).toHaveBeenCalledWith('work-delivery-1', expect.objectContaining({ command: 'SAVE_REQUIREMENT', payload: { target: null, bookingRequired: false, receivingRequirements: '工作日9至16点到仓联系收货人', reason: '客户仓确认无需预约' } }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps a return handoff separate from original carrier plans and records external acceptance evidence', async () => {
|
|
||||||
const action: WorkAction = { code: 'ACCEPT_RETURN', label: '记录接手反馈', targetWorkItemKey: null, target: { kind: 'WORK_COMMAND', command: 'ACCEPT_RETURN' } }
|
|
||||||
const wrapper = render(action, workDetail({ item: workItem({ type: 'EMPTY_RETURN', allowedActions: [action] }), returnHandoff: { version: 7, from: { kind: 'USER', id: 'user-1', name: '测试调度' }, to: { kind: 'EXTERNAL', id: null, name: '测试还空车队' }, status: 'PENDING_ACCEPTANCE', reason: '原车次调整' } }))
|
|
||||||
await wrapper.get('form').trigger('submit'); expect(submitWorkCommand).not.toHaveBeenCalled()
|
|
||||||
await wrapper.get('textarea').setValue('接手车队已回复确认'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(submitWorkCommand).toHaveBeenCalledWith('work-delivery-1', expect.objectContaining({ command: 'ACCEPT_RETURN', payload: { handoffVersion: 7, note: '接手车队已回复确认' } }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('denies command submission without write permission even when a submit event is forced', async () => {
|
|
||||||
session.canWrite = false; const wrapper = render()
|
|
||||||
await wrapper.get('form').trigger('submit'); expect(submitWorkCommand).not.toHaveBeenCalled()
|
|
||||||
expect(wrapper.text()).toContain('当前仅可查看'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
const requirementAction: WorkAction = { code: 'SAVE_REQUIREMENT', label: '登记收货要求', targetWorkItemKey: null, target: { kind: 'WORK_COMMAND', command: 'SAVE_REQUIREMENT' } }
|
|
||||||
it('preserves an explicit cross-day local interval in the requirement request', async () => {
|
|
||||||
const wrapper = render(requirementAction)
|
|
||||||
await wrapper.findAll('textarea')[1]!.setValue('跨日收货窗口')
|
|
||||||
const dates = wrapper.findAll('input[data-picker-kind=date]'), times = wrapper.findAll('input[data-picker-kind=time]')
|
|
||||||
await dates[0]!.setValue('2026-10-15'); await times[0]!.setValue('23:00')
|
|
||||||
await dates[1]!.setValue('2026-10-16'); await times[1]!.setValue('01:00')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(submitWorkCommand).toHaveBeenCalledWith('work-delivery-1', expect.objectContaining({ payload: expect.objectContaining({ target: { date: '2026-10-15', startTime: '23:00', endDate: '2026-10-16', endTime: '01:00', timezone: 'America/Los_Angeles' } }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it.each([
|
|
||||||
['2026-10-16', '', '23:00'], ['', '01:00', '23:00'],
|
|
||||||
['2026-10-15', '22:00', '23:00'], ['2026-10-15', '23:00', '23:00'],
|
|
||||||
['2026-10-16', '01:00', ''],
|
|
||||||
])('rejects incomplete or non-increasing interval %s %s %s without inferring a next day', async (endDate, endTime, startTime) => {
|
|
||||||
const wrapper = render(requirementAction)
|
|
||||||
await wrapper.findAll('textarea')[1]!.setValue('核对时间')
|
|
||||||
const dates = wrapper.findAll('input[data-picker-kind=date]'), times = wrapper.findAll('input[data-picker-kind=time]')
|
|
||||||
await dates[0]!.setValue('2026-10-15'); await times[0]!.setValue(startTime)
|
|
||||||
await dates[1]!.setValue(endDate); await times[1]!.setValue(endTime)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(submitWorkCommand).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('saves a date-only requirement with all time fields null', async () => {
|
|
||||||
const wrapper = render(requirementAction)
|
|
||||||
await wrapper.findAll('textarea')[1]!.setValue('具体时段待回复')
|
|
||||||
await wrapper.findAll('input[data-picker-kind=date]')[0]!.setValue('2026-10-15')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(submitWorkCommand).toHaveBeenCalledWith('work-delivery-1', expect.objectContaining({ payload: expect.objectContaining({ target: { date: '2026-10-15', startTime: null, endDate: null, endTime: null, timezone: 'America/Los_Angeles' } }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import './appointmentNativeForms.css'
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import InlineHelp from '@/shared/components/InlineHelp.vue'
|
|
||||||
import { computed, reactive, ref } from 'vue'
|
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { listSuppliers, type Supplier } from '@/modules/suppliers'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import { submitWorkCommand, type WorkAction, type WorkDetail, type WorkCommand, type WorkCommandPayload, type WorkCommandResult } from './workApi'
|
|
||||||
import { actionAllowed, commandName } from './workPresentation'
|
|
||||||
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
|
|
||||||
const props = defineProps<{ detail: WorkDetail; action: WorkAction; refreshing: boolean }>()
|
|
||||||
const emit = defineEmits<{ saved: [result: WorkCommandResult, command: WorkCommand['command']]; refresh: [] }>()
|
|
||||||
const auth = useAuthStore(), access = useAccessPreviewStore()
|
|
||||||
const command = computed(() => commandName(props.action))
|
|
||||||
const item = computed(() => props.detail.item)
|
|
||||||
const form = reactive({ flow: item.value.flow === 'DIRECT' ? 'DIRECT' : 'TRANSFER', ownerId: item.value.owner?.id || auth.user?.id || '', followupDate: item.value.followupDate || '', note: '', reason: '', date: item.value.target?.date || '', startTime: item.value.target?.startTime || '', endDate: item.value.target?.endDate || '', endTime: item.value.target?.endTime || '', bookingRequired: props.detail.requirement?.bookingRequired ?? true, receivingRequirements: props.detail.requirement?.receivingRequirements || '', recipientKind: 'EXTERNAL', recipientId: '', recipientName: '' })
|
|
||||||
const baseline = ref(JSON.stringify(form)), pending = ref<WorkCommand | null>(null), saving = ref(false), error = ref<ApiErrorDetails | null>(null)
|
|
||||||
const supplierKeyword = ref(''), suppliers = ref<Supplier[]>([]), supplierTotal = ref(0), supplierLoading = ref(false), supplierError = ref<ApiErrorDetails | null>(null)
|
|
||||||
let supplierRequest = 0
|
|
||||||
async function searchSuppliers() {
|
|
||||||
const request = ++supplierRequest; supplierError.value = null; suppliers.value = []; form.recipientId = ''
|
|
||||||
if (!access.can('platform:supplier:list')) { supplierError.value = { message: '当前账号没有供应商读取权限,请联系有权限的负责人选择车队。' }; return }
|
|
||||||
supplierLoading.value = true
|
|
||||||
try { const result = await listSuppliers({ page: 1, size: 20, category: 'TRUCKING', truckingScope: 'OVERSEAS', status: 'ACTIVE', keyword: supplierKeyword.value }); if (request === supplierRequest) { suppliers.value = result.records; supplierTotal.value = result.total } }
|
|
||||||
catch (cause) { if (request === supplierRequest) supplierError.value = getApiErrorDetails(cause, '还空车队读取失败') }
|
|
||||||
finally { if (request === supplierRequest) supplierLoading.value = false }
|
|
||||||
}
|
|
||||||
function changeRecipient() { form.recipientId = ''; form.recipientName = ''; if (form.recipientKind === 'SUPPLIER') void searchSuppliers() }
|
|
||||||
useWorkDraft(computed(() => baseline.value !== JSON.stringify(form)), computed(() => saving.value || !!pending.value))
|
|
||||||
const owners = computed(() => {
|
|
||||||
const people = [item.value.owner, auth.user ? { id: auth.user.id, name: auth.user.name } : null, ...props.detail.relatedItems.map(row => row.owner)]
|
|
||||||
return [...new Map(people.filter((person): person is { id: string; name: string } => !!person?.id).map(person => [person.id, person])).values()]
|
|
||||||
})
|
|
||||||
const permission = computed(() => command.value === 'SAVE_FOLLOWUP' || command.value === 'RESOLVE_REVIEW' ? 'platform:appointment:followup' : 'platform:appointment:manage-work')
|
|
||||||
const allowed = computed(() => !!command.value && actionAllowed(item.value, props.action) && access.can(permission.value))
|
|
||||||
const missingContext = computed(() => {
|
|
||||||
if (command.value === 'RESOLVE_REVIEW' && props.detail.review == null) return '当前没有可复核的影响版本,请刷新事项。'
|
|
||||||
if (command.value === 'ACCEPT_RETURN' && props.detail.returnHandoff == null) return '当前没有有效的还空交接,请刷新事项。'
|
|
||||||
if (command.value === 'SAVE_REQUIREMENT' && form.date && !item.value.timezone) return '作业地点时区未核实,暂不能保存带日期的要求。'
|
|
||||||
return ''
|
|
||||||
})
|
|
||||||
function payload(): WorkCommandPayload | null {
|
|
||||||
const note = form.note.trim(), reason = form.reason.trim()
|
|
||||||
switch (command.value) {
|
|
||||||
case 'CONFIRM_ROUTE': return { command: 'CONFIRM_ROUTE', payload: { flow: form.flow === 'DIRECT' ? 'DIRECT' : 'TRANSFER', reason: reason || null } }
|
|
||||||
case 'SAVE_FOLLOWUP':
|
|
||||||
if (!form.ownerId || !note) { ElMessage.warning('请选择跟进负责人并填写本次回复'); return null }
|
|
||||||
return { command: 'SAVE_FOLLOWUP', payload: { ownerId: form.ownerId, followupDate: form.followupDate || null, note } }
|
|
||||||
case 'RESOLVE_REVIEW':
|
|
||||||
if (!props.detail.review || !note) { ElMessage.warning('请核对当前影响并填写处理结果'); return null }
|
|
||||||
return { command: 'RESOLVE_REVIEW', payload: { reviewVersion: props.detail.review.version, note } }
|
|
||||||
case 'SAVE_REQUIREMENT':
|
|
||||||
if (!reason || (!form.bookingRequired && !form.receivingRequirements.trim())) { ElMessage.warning('请填写处理说明;无需预约时必须填写真实收货要求'); return null }
|
|
||||||
if ((form.startTime || form.endDate || form.endTime) && !form.date) { ElMessage.warning('填写时段前需明确目标日期'); return null }
|
|
||||||
if (!!form.endDate !== !!form.endTime) { ElMessage.warning('结束日期和结束时间须同时填写或同时留空'); return null }
|
|
||||||
if (form.endDate && (!form.startTime || form.endDate + 'T' + form.endTime <= form.date + 'T' + form.startTime)) { ElMessage.warning('完整的当地结束时间须晚于开始时间'); return null }
|
|
||||||
return { command: 'SAVE_REQUIREMENT', payload: { target: form.date && item.value.timezone ? { date: form.date, startTime: form.startTime || null, endDate: form.endDate || null, endTime: form.endTime || null, timezone: item.value.timezone } : null, bookingRequired: form.bookingRequired, receivingRequirements: form.receivingRequirements.trim(), reason } }
|
|
||||||
case 'HANDOFF_RETURN': {
|
|
||||||
const person = owners.value.find(owner => owner.id === form.recipientId)
|
|
||||||
const supplier = suppliers.value.find(candidate => candidate.id === form.recipientId)
|
|
||||||
const recipient = form.recipientKind === 'USER' && person ? { kind: 'USER' as const, id: person.id, name: person.name } : form.recipientKind === 'SUPPLIER' && supplier && !supplierLoading.value && !supplierError.value ? { kind: 'SUPPLIER' as const, id: supplier.id, name: supplier.name } : form.recipientKind === 'EXTERNAL' ? { kind: 'EXTERNAL' as const, id: null, name: form.recipientName.trim() } : null
|
|
||||||
if (!recipient?.name || !reason) { ElMessage.warning('请明确接手方并填写转交原因'); return null }
|
|
||||||
return { command: 'HANDOFF_RETURN', payload: { recipient, reason } }
|
|
||||||
}
|
|
||||||
case 'ACCEPT_RETURN':
|
|
||||||
if (!props.detail.returnHandoff) return null
|
|
||||||
if (props.detail.returnHandoff.to.kind !== 'USER' && !note) { ElMessage.warning('请记录外部接手方已确认的反馈依据'); return null }
|
|
||||||
return { command: 'ACCEPT_RETURN', payload: { handoffVersion: props.detail.returnHandoff.version, note: note || null } }
|
|
||||||
default: return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function save() {
|
|
||||||
if (!allowed.value || props.refreshing || saving.value || missingContext.value) return
|
|
||||||
if (!pending.value) { const request = payload(); if (!request) return; pending.value = { ...request, expectedVersion: item.value.version, idempotencyKey: crypto.randomUUID() } }
|
|
||||||
saving.value = true; error.value = null
|
|
||||||
try {
|
|
||||||
const request = pending.value, result = await submitWorkCommand(item.value.workItemKey, request)
|
|
||||||
pending.value = null; baseline.value = JSON.stringify(form); ElMessage.success('已保存,工作待办已更新'); emit('saved', result, request.command)
|
|
||||||
} catch (cause) {
|
|
||||||
error.value = getApiErrorDetails(cause, '本次保存结果待确认,请重试同一次保存')
|
|
||||||
if (rejectedCommand(cause)) { pending.value = null; emit('refresh') }
|
|
||||||
} finally { saving.value = false }
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<form class="density-form work-form appointment-native-form" @submit.prevent="save">
|
|
||||||
<h3>{{ action.label }}<InlineHelp v-if="command === 'SAVE_FOLLOWUP'" title="跟进日期说明"><p>跟进日期不代替作业日期;未完成事项仍保留在待办中。</p></InlineHelp><InlineHelp v-if="command === 'RESOLVE_REVIEW'" title="核对结果说明"><p>原安排需要改期时,请先处理原安排,再记录核对结果。</p></InlineHelp></h3>
|
|
||||||
<p v-if="!allowed">当前仅可查看。此操作需要有效的服务端资格和对应操作权限。</p>
|
|
||||||
<p v-if="missingContext" role="alert">{{ missingContext }}</p>
|
|
||||||
<fieldset :disabled="!allowed || refreshing || saving || !!pending">
|
|
||||||
<template v-if="command === 'CONFIRM_ROUTE'"><label>运输方式<select v-model="form.flow" class="workbench-input"><option value="TRANSFER">先入海外仓,再分批送仓</option><option value="DIRECT">整柜直接送目的仓</option></select></label><label>路线说明<textarea v-model="form.reason" maxlength="1000" class="workbench-input" /></label></template>
|
|
||||||
<template v-else-if="command === 'SAVE_FOLLOWUP'"><label>跟进负责人<select v-model="form.ownerId" required class="workbench-input"><option value="" disabled>请选择负责人</option><option v-for="person in owners" :key="person.id" :value="person.id">{{ person.name }}</option></select></label><label>本次回复<textarea v-model="form.note" required maxlength="1000" class="workbench-input" /></label><label>下次跟进日期(可留空)<el-date-picker v-model="form.followupDate" type="date" :disabled="!allowed || refreshing || saving || !!pending" format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable /></label></template>
|
|
||||||
<template v-else-if="command === 'RESOLVE_REVIEW'"><p v-for="reason in detail.review?.reasons" :key="reason">{{ reason }}</p><label>本次核对结果<textarea v-model="form.note" required maxlength="1000" class="workbench-input" /></label></template>
|
|
||||||
<template v-else-if="command === 'SAVE_REQUIREMENT'"><label>目标日期(可暂不填)<el-date-picker v-model="form.date" type="date" :disabled="!allowed || refreshing || saving || !!pending" format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable /></label><div class="time-fields"><label>开始时段(可留空)<el-time-picker v-model="form.startTime" :disabled="!allowed || refreshing || saving || !!pending" format="HH:mm" value-format="HH:mm" clearable /></label><label>结束日期(可留空)<el-date-picker v-model="form.endDate" type="date" :disabled="!allowed || refreshing || saving || !!pending" format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable /></label><label>结束时段(可留空)<el-time-picker v-model="form.endTime" :disabled="!allowed || refreshing || saving || !!pending" format="HH:mm" value-format="HH:mm" clearable /></label></div><p>{{ item.timezone || '地点时区待核实' }}</p><label v-if="item.type === 'DELIVERY'"><input v-model="form.bookingRequired" type="checkbox">需要收货方预约</label><label>收货要求<textarea v-model="form.receivingRequirements" :required="!form.bookingRequired" maxlength="1000" class="workbench-input" /></label><label>处理说明<textarea v-model="form.reason" required maxlength="1000" class="workbench-input" /></label></template>
|
|
||||||
<template v-else-if="command === 'HANDOFF_RETURN'"><p>转交保留原预约和责任记录;接手方确认前持续跟进。</p><label>接手方类型<select v-model="form.recipientKind" @change="changeRecipient" class="workbench-input"><option value="EXTERNAL">外部车队 / 联系人</option><option value="SUPPLIER">已登记海外车队</option><option value="USER">当前关联负责人</option></select></label><label v-if="form.recipientKind === 'EXTERNAL'">接手方名称<input v-model="form.recipientName" required maxlength="200" class="workbench-input"></label><template v-else-if="form.recipientKind === 'SUPPLIER'"><label>查找海外车队<input v-model="supplierKeyword" maxlength="80" @keydown.enter.prevent="searchSuppliers" class="workbench-input"></label><el-button :loading="supplierLoading" @click="searchSuppliers">查询车队</el-button><LoadErrorState v-if="supplierError" title="还空车队不可用" :message="supplierError.message" @retry="searchSuppliers" /><label>接手车队<select v-model="form.recipientId" required :disabled="supplierLoading || !!supplierError" class="workbench-input"><option value="" disabled>请选择已登记海外车队</option><option v-for="supplier in suppliers" :key="supplier.id" :value="supplier.id">{{ supplier.name }}</option></select></label><p v-if="supplierTotal > suppliers.length">请输入更完整名称缩小查询范围。</p></template><label v-else>接手负责人<select v-model="form.recipientId" required class="workbench-input"><option value="" disabled>请选择</option><option v-for="person in owners" :key="person.id" :value="person.id">{{ person.name }}</option></select></label><label>转交原因<textarea v-model="form.reason" required maxlength="1000" class="workbench-input" /></label></template>
|
|
||||||
<template v-else-if="command === 'ACCEPT_RETURN'"><p>原责任方:{{ detail.returnHandoff?.from.name || '—' }} → 接手方:{{ detail.returnHandoff?.to.name || '—' }}</p><label>接手反馈依据<textarea v-model="form.note" :required="detail.returnHandoff?.to.kind !== 'USER'" maxlength="1000" class="workbench-input" /></label><p>确认接手只记录责任,实际还空仍按原业务操作。</p></template>
|
|
||||||
</fieldset>
|
|
||||||
<LoadErrorState v-if="error" title="工作操作未保存" :message="error.message" :show-retry="false"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<div class="density-actions density-actions--footer appointment-form-actions"><el-button type="primary" native-type="submit" :disabled="!allowed || refreshing || !!missingContext" :loading="saving">{{ pending ? '重试本次保存' : command === 'CONFIRM_ROUTE' ? '确认路线,继续本柜工作' : '保存并更新待办' }}</el-button></div>
|
|
||||||
</form>
|
|
||||||
</template>
|
|
||||||
<style scoped>.time-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--admin-space-3); }</style>
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkCreateAppointmentForm from './WorkCreateAppointmentForm.vue'
|
|
||||||
import { previewPlanningBatch, createSourceAppointment, type PlanningBatchPreview } from './planningApi'
|
|
||||||
import type { SourceReference } from './workApi'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
const access = vi.hoisted(() => ({ write: true }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => access.write }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
|
||||||
vi.mock('./planningApi', async original => ({ ...await original<typeof import('./planningApi')>(), previewPlanningBatch: vi.fn(), createSourceAppointment: vi.fn() }))
|
|
||||||
const sources: SourceReference[] = [{ sourceKey: 'BOOKING:external-1', customerId: '9007199254740999', destinationKey: 'FBA:ONT8' }]
|
|
||||||
const preview: PlanningBatchPreview = { group: { originWarehouseId: 'origin-1', destinationKey: 'FBA:ONT8', packages: 30, sourceCount: 1, customerCount: 1, readinessIncomplete: true, readyFrom: null, readyTo: null, unknownQuantitySources: 0 }, originWarehouseName: '测试起运仓', destinationWarehouseCode: 'ONT8', destinationTimezone: 'America/Los_Angeles', missingFields: [], sources: [{ ...sources[0]!, destinationKey: 'FBA:ONT8', orderId: null, inboundCode: null, bookingNo: 'BK-TEST', containerNo: null, originWarehouseId: 'origin-1', originWarehouseName: '测试起运仓', destinationWarehouseCode: 'ONT8', packages: 30, sourceVersion: null, canFollowup: true, blockReasons: [] }] }
|
|
||||||
let guard: LeaveGuard
|
|
||||||
function render(input = sources) { return mount(WorkCreateAppointmentForm, { props: { sources: input, canWrite: true }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, FbaAppointmentFields: { name: 'FbaAppointmentFields', props: ['model', 'disabled'], template: '<input v-model="model.plannedDate" type="date">' }, LoadErrorState: { props: ['message'], template: '<p>{{ message }}</p>' }, ApiErrorMeta: true } } }) }
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); access.write = true; vi.mocked(previewPlanningBatch).mockResolvedValue(preview); vi.mocked(createSourceAppointment).mockResolvedValue(batchContext().appointment) })
|
|
||||||
it('shows readable preview requirements without exposing missing-field machine codes', async () => {
|
|
||||||
vi.mocked(previewPlanningBatch).mockResolvedValue({ ...preview, missingFields: ['READY_WINDOW_UNVERIFIED', 'CARGO_QUANTITY_REVIEW'] })
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('货物备妥窗口待核实')
|
|
||||||
expect(wrapper.text()).toContain('货量或重复关联需要核对。')
|
|
||||||
expect(wrapper.text()).not.toContain('READY_WINDOW_UNVERIFIED')
|
|
||||||
expect(wrapper.text()).not.toContain('CARGO_QUANTITY_REVIEW')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('previews and creates the exact canonical external source and customer without inventing times', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(previewPlanningBatch).toHaveBeenCalledWith(sources)
|
|
||||||
await wrapper.get('input').setValue('2026-10-16'); await wrapper.get('button').trigger('click'); await flushPromises()
|
|
||||||
expect(createSourceAppointment).toHaveBeenCalledWith(expect.objectContaining({ sources, originWarehouseId: 'origin-1', fbaWarehouseCode: 'ONT8', details: expect.objectContaining({ plannedDate: '2026-10-16', plannedAt: null, plannedEndAt: null, appointmentStatus: 'PENDING' }) }))
|
|
||||||
expect(wrapper.emitted('saved')).toHaveLength(1); expect(wrapper.text()).not.toContain('external-1'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('retains the same immutable request after an unknown outcome and blocks leaving', async () => {
|
|
||||||
vi.mocked(createSourceAppointment).mockRejectedValueOnce(new Error('connection lost'))
|
|
||||||
const wrapper = render(); await flushPromises(); await wrapper.get('button').trigger('click'); await flushPromises()
|
|
||||||
const request = vi.mocked(createSourceAppointment).mock.calls[0]![0]
|
|
||||||
expect(await guard()).toBe(false)
|
|
||||||
await wrapper.get('button').trigger('click'); await flushPromises()
|
|
||||||
expect(createSourceAppointment).toHaveBeenNthCalledWith(2, request); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('refreshes qualification after conflict while keeping user-entered dates', async () => {
|
|
||||||
vi.mocked(createSourceAppointment).mockRejectedValueOnce(new ApiResponseError('来源变化', 'A0409', 409))
|
|
||||||
const wrapper = render(); await flushPromises(); await wrapper.get('input').setValue('2026-10-16')
|
|
||||||
await wrapper.get('button').trigger('click'); await flushPromises()
|
|
||||||
expect(previewPlanningBatch).toHaveBeenCalledTimes(2)
|
|
||||||
expect((wrapper.get('input').element as HTMLInputElement).value).toBe('2026-10-16')
|
|
||||||
expect(wrapper.emitted('saved')).toBeUndefined(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('rejects missing destination scope and lacks a write path without permission', async () => {
|
|
||||||
const missing = render([{ ...sources[0]!, destinationKey: null }]); await flushPromises()
|
|
||||||
expect(previewPlanningBatch).not.toHaveBeenCalled(); expect(missing.text()).toContain('缺少完整货源'); missing.unmount()
|
|
||||||
access.write = false; const readonly = render(); await flushPromises(); await readonly.get('button').trigger('click')
|
|
||||||
expect(createSourceAppointment).not.toHaveBeenCalled(); readonly.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { computed, onMounted, reactive, ref } from 'vue'
|
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { FbaAppointmentFields, createAppointmentForm, appointmentFormError, appointmentPayload, overseasWarehousePermissions, type FbaAppointmentDto } from '@/modules/overseas-warehouse'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import { previewPlanningBatch, createSourceAppointment, type PlanningBatchPreview, type SourceAppointmentPayload } from './planningApi'
|
|
||||||
import type { SourceReference } from './workApi'
|
|
||||||
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
|
|
||||||
import { workReason } from './workPresentation'
|
|
||||||
const props = defineProps<{ sources: SourceReference[]; canWrite: boolean }>()
|
|
||||||
const emit = defineEmits<{ saved: [appointment: FbaAppointmentDto] }>()
|
|
||||||
const access = useAccessPreviewStore(), preview = ref<PlanningBatchPreview | null>(null)
|
|
||||||
const form = reactive(createAppointmentForm()), baseline = ref(JSON.stringify(form))
|
|
||||||
const loading = ref(false), saving = ref(false), error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null)
|
|
||||||
const pending = ref<SourceAppointmentPayload | null>(null)
|
|
||||||
const writable = computed(() => props.canWrite && access.can(overseasWarehousePermissions.inboundOrderAppointment))
|
|
||||||
useWorkDraft(computed(() => baseline.value !== JSON.stringify(form)), computed(() => saving.value || !!pending.value))
|
|
||||||
async function load() {
|
|
||||||
if (!props.sources.length || props.sources.some(source => !source.customerId || !source.sourceKey || !source.destinationKey)) { error.value = { message: '缺少完整货源、客户或目的仓范围,无法新建预约。' }; return }
|
|
||||||
loading.value = true; error.value = null
|
|
||||||
try { preview.value = await previewPlanningBatch(props.sources.map(source => ({ ...source, destinationKey: source.destinationKey! }))) }
|
|
||||||
catch (cause) { error.value = getApiErrorDetails(cause, '预约货物预览失败') }
|
|
||||||
finally { loading.value = false }
|
|
||||||
}
|
|
||||||
async function save() {
|
|
||||||
if (!writable.value || loading.value || saving.value || error.value || !preview.value) return
|
|
||||||
if (!pending.value) {
|
|
||||||
const invalid = appointmentFormError(form); if (invalid) { ElMessage.warning(invalid); return }
|
|
||||||
pending.value = { originWarehouseId: preview.value.group.originWarehouseId, fbaWarehouseCode: preview.value.destinationWarehouseCode, sources: preview.value.sources.map(source => ({ sourceKey: source.sourceKey, customerId: source.customerId, destinationKey: source.destinationKey })), details: appointmentPayload(form), idempotencyKey: crypto.randomUUID() }
|
|
||||||
}
|
|
||||||
saving.value = true; saveError.value = null
|
|
||||||
try {
|
|
||||||
const result = await createSourceAppointment(pending.value)
|
|
||||||
pending.value = null; baseline.value = JSON.stringify(form)
|
|
||||||
ElMessage.success(`预约安排 ${result.appointmentNo} 已保存`); emit('saved', result)
|
|
||||||
} catch (cause) {
|
|
||||||
saveError.value = getApiErrorDetails(cause, '创建结果待确认,请重试本次请求')
|
|
||||||
if (rejectedCommand(cause)) { pending.value = null; await load() }
|
|
||||||
} finally { saving.value = false }
|
|
||||||
}
|
|
||||||
onMounted(load)
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section class="work-form density-dialog-sections" aria-label="新建预约安排">
|
|
||||||
<LoadErrorState v-if="error" title="预约货物预览失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<p v-if="loading">正在核对本次货物范围…</p>
|
|
||||||
<template v-if="preview && !error">
|
|
||||||
<section class="density-dialog-section" data-tone="summary" aria-label="本次预约货物">
|
|
||||||
<h3 class="density-dialog-section__title">本次预约货物</h3>
|
|
||||||
<table class="density-table"><tbody>
|
|
||||||
<tr><th scope="row">起运仓</th><td>{{ preview.originWarehouseName || '—' }}</td><th scope="row">目的FBA仓</th><td>{{ preview.destinationWarehouseCode || '—' }}</td></tr>
|
|
||||||
<tr><th scope="row">票数</th><td>{{ preview.group.sourceCount }}</td><th scope="row">箱数</th><td>{{ preview.group.packages ?? '箱数待核实' }}</td></tr>
|
|
||||||
<tr><th scope="row">货物业务号</th><td colspan="3"><template v-for="(source, index) in preview.sources" :key="`${source.customerId}:${source.sourceKey}`">{{ index ? '、' : '' }}{{ source.inboundCode || source.bookingNo || '原票业务号未提供' }}</template></td></tr>
|
|
||||||
</tbody></table>
|
|
||||||
<p v-for="field in preview.missingFields" :key="field" role="status" class="density-dialog-note">{{ workReason(field) }}</p>
|
|
||||||
<p v-if="preview.group.readinessIncomplete" role="status" class="density-dialog-note">货物备妥窗口待核实。</p>
|
|
||||||
</section>
|
|
||||||
<FbaAppointmentFields continuous :model="form" :timezone="preview.destinationTimezone" :disabled="!writable || loading || saving || !!pending" />
|
|
||||||
<LoadErrorState v-if="saveError" title="预约尚未创建" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState>
|
|
||||||
<div class="density-actions density-actions--footer"><el-button type="primary" :disabled="!writable || loading" :loading="saving" @click="save">{{ pending ? '重试本次创建' : '保存预约安排' }}</el-button></div>
|
|
||||||
</template>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkDetailPanel from './WorkDetailPanel.vue'
|
|
||||||
import { getWorkDetail, resolveBatchWork, type WorkAction, type WorkDetail } from './workApi'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
import { followAction, workDetail, workItem } from './work.test-support'
|
|
||||||
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), getWorkDetail: vi.fn(), resolveBatchWork: vi.fn() }))
|
|
||||||
function render(detail: WorkDetail, initialAction?: WorkAction) {
|
|
||||||
vi.mocked(getWorkDetail).mockResolvedValue(detail)
|
|
||||||
return mount(WorkDetailPanel, { props: { itemKey: detail.item.workItemKey, initialAction, canLeave: async () => true }, global: { stubs: {
|
|
||||||
ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' },
|
|
||||||
CargoVerificationForm: { name: 'CargoVerificationForm', props: ['source'], template: '<div data-cargo />' },
|
|
||||||
WorkCommandForm: { name: 'WorkCommandForm', props: ['detail', 'action'], template: '<div data-command />' },
|
|
||||||
WorkAppointmentForm: { name: 'WorkAppointmentForm', props: ['appointmentNo', 'canWrite'], template: '<div data-appointment />' },
|
|
||||||
WorkReceivingPanel: { name: 'WorkReceivingPanel', props: ['batchKey', 'canWrite'], template: '<div data-receiving-scope />' },
|
|
||||||
WorkCreateAppointmentForm: { name: 'WorkCreateAppointmentForm', props: ['sources', 'canWrite'], template: '<div data-create />' },
|
|
||||||
WorkDispatchForm: { name: 'WorkDispatchForm', props: ['batchKeys', 'canWrite'], template: '<div data-dispatch />' },
|
|
||||||
WorkExistingDispatchForm: { name: 'WorkExistingDispatchForm', props: ['dispatches', 'canWrite'], template: '<div data-existing-dispatch />' },
|
|
||||||
WorkReceiptPlans: { name: 'WorkReceiptPlans', props: ['containerBookingId'], template: '<div data-receiving />' },
|
|
||||||
LoadErrorState: { props: ['message'], template: '<section role="alert">{{ message }}<button @click="$emit(\'retry\')">重试读取</button></section>' }, ApiErrorMeta: true,
|
|
||||||
} } })
|
|
||||||
}
|
|
||||||
beforeEach(() => vi.clearAllMocks())
|
|
||||||
it('navigates the server-selected transport next step outside the delivery write permissions', async () => {
|
|
||||||
const transport: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '继续安排本批车辆', targetWorkItemKey: 'transport-current', target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['FBA_APPOINTMENT:1'] } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ nextAction: transport, allowedActions: [followAction] }) }))
|
|
||||||
await flushPromises()
|
|
||||||
await wrapper.get('.primary-next-action').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.emitted('open')).toEqual([['transport-current', transport]])
|
|
||||||
expect(wrapper.text()).not.toContain('操作资格已变化')
|
|
||||||
expect(wrapper.find('[data-dispatch]').exists()).toBe(false)
|
|
||||||
wrapper.unmount()
|
|
||||||
const target = render(workDetail({ item: workItem({ workItemKey: 'transport-current', type: 'TRANSPORT', allowedActions: [], nextAction: null }) }), transport)
|
|
||||||
await flushPromises()
|
|
||||||
expect(target.find('[data-dispatch]').exists()).toBe(false)
|
|
||||||
expect(target.emitted('open')).toBeUndefined()
|
|
||||||
target.unmount()
|
|
||||||
})
|
|
||||||
it('stays on the saved item and offers only the newly fetched primary next step', async () => {
|
|
||||||
const wrapper = render(workDetail(), followAction); await flushPromises()
|
|
||||||
const transport: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '继续安排本批车辆', targetWorkItemKey: 'transport-current', target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['FBA_APPOINTMENT:1'] } }
|
|
||||||
vi.mocked(getWorkDetail).mockResolvedValue(workDetail({ item: workItem({ nextAction: transport, allowedActions: [transport, followAction] }) }))
|
|
||||||
wrapper.getComponent({ name: 'WorkCommandForm' }).vm.$emit('saved', { item: workItem(), affectedWorkItemKeys: [] }, 'SAVE_FOLLOWUP'); await flushPromises()
|
|
||||||
expect(wrapper.find('[data-command]').exists()).toBe(false)
|
|
||||||
expect(wrapper.text()).toContain('本次保存已完成')
|
|
||||||
expect(wrapper.get('.primary-next-action').text()).toBe('继续安排本批车辆')
|
|
||||||
expect(wrapper.findAll('.more-actions button').map(button => button.text())).toEqual(['记录回复'])
|
|
||||||
await wrapper.get('.primary-next-action').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.emitted('open')).toEqual([['transport-current', transport]])
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not repeat a saved command or enable stale actions when the next-step read fails', async () => {
|
|
||||||
const wrapper = render(workDetail(), followAction); await flushPromises()
|
|
||||||
vi.mocked(getWorkDetail).mockRejectedValueOnce(new Error('下一步服务暂不可用'))
|
|
||||||
wrapper.getComponent({ name: 'WorkCommandForm' }).vm.$emit('saved', { item: workItem(), affectedWorkItemKeys: [] }, 'SAVE_FOLLOWUP'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('无需重复提交已保存内容')
|
|
||||||
expect(wrapper.get('.primary-next-action').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.get('.primary-next-action').attributes('disabled')).toBeUndefined()
|
|
||||||
expect(wrapper.emitted('saved')).toHaveLength(1)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('shows an undated job separately from its follow-up date and flags missing follow-up ownership', async () => {
|
|
||||||
const wrapper = render(workDetail()); await flushPromises()
|
|
||||||
expect(wrapper.get('.followup-summary').text()).toContain('2026-10-15')
|
|
||||||
expect(wrapper.get('.followup-summary').text()).toContain('作业日期未定,跟进日不作为作业日期')
|
|
||||||
wrapper.unmount()
|
|
||||||
const missing = render(workDetail({ item: workItem({ owner: null, followupDate: null }) })); await flushPromises()
|
|
||||||
expect(missing.text()).toContain('负责人待分派')
|
|
||||||
expect(missing.text()).toContain('请补充下一次跟进安排')
|
|
||||||
missing.unmount()
|
|
||||||
})
|
|
||||||
it('never sends customer-warehouse dispatch batches to the FBA candidate endpoint', async () => {
|
|
||||||
const action: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '安排运输', targetWorkItemKey: null, target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['DISPATCH:9007199254740999'] } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }), action); await flushPromises()
|
|
||||||
expect(wrapper.findComponent({ name: 'WorkDispatchForm' }).exists()).toBe(false); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('resolves a customer-warehouse batch using the frozen work item batch number', async () => {
|
|
||||||
const action: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '安排运输', targetWorkItemKey: null, target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['DISPATCH:9007199254740999'] } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ batchKey: 'DISPATCH:9007199254740999', batchNo: 'DS-ORIGINAL', allowedActions: [action], nextAction: action }) }), action); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkExistingDispatchForm' }).props('dispatches')).toEqual([{ batchKey: 'DISPATCH:9007199254740999', dispatchNo: 'DS-ORIGINAL' }])
|
|
||||||
expect(wrapper.findComponent({ name: 'WorkDispatchForm' }).exists()).toBe(false); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('opens real batch dispatch when the server has not bound a trip yet', async () => {
|
|
||||||
const action: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '安排运输', targetWorkItemKey: null, target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['FBA_APPOINTMENT:1'] } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }), action); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkDispatchForm' }).props('batchKeys')).toEqual(['FBA_APPOINTMENT:1']); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('loads the exact container plan list for a multiple-plan receiving target', async () => {
|
|
||||||
const action: WorkAction = { code: 'RECORD_EXECUTION', label: '查看接仓', targetWorkItemKey: null, target: { kind: 'WAREHOUSE_RECEIPT', inboundPlanId: null, inboundPlanNo: null, customerId: null, containerBookingId: '9007199254740999' } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }), action); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkReceiptPlans' }).props('containerBookingId')).toBe('9007199254740999'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('opens a real create form for unappointed sources with their exact customer scope', async () => {
|
|
||||||
const action: WorkAction = { code: 'SAVE_PLAN', label: '安排预约', targetWorkItemKey: null, target: { kind: 'FBA_APPOINTMENT', appointmentId: null, batchKey: null, sources: [{ sourceKey: 'BOOKING:1', customerId: 'customer-a', destinationKey: 'FBA:ONT8' }] } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }), action); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkCreateAppointmentForm' }).props('sources')).toEqual(action.target.kind === 'FBA_APPOINTMENT' ? action.target.sources : [])
|
|
||||||
expect(wrapper.text()).not.toContain('尚未关联可操作的预约记录'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('opens the server-selected prerequisite instead of issuing the current item command', async () => {
|
|
||||||
const action = { ...followAction, targetWorkItemKey: 'work-pickup-1' }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }), action); await flushPromises()
|
|
||||||
expect(wrapper.emitted('open')).toEqual([['work-pickup-1', action]])
|
|
||||||
expect(wrapper.findComponent({ name: 'WorkCommandForm' }).exists()).toBe(false); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('uses explicit cargo context and preserves large customer IDs without inspecting a business key', async () => {
|
|
||||||
const action: WorkAction = { code: 'VERIFY_CARGO', label: '核实货物资料', targetWorkItemKey: null, target: { kind: 'CARGO_VERIFICATION', source: { customerId: '9007199254740999', sourceKey: 'BOOKING:B-1', destinationKey: 'FBA:ONT8' } } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }), action); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'CargoVerificationForm' }).props('source')).toEqual(action.target.kind === 'CARGO_VERIFICATION' ? action.target.source : null)
|
|
||||||
expect(wrapper.text()).not.toContain('9007199254740999'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('rechecks current qualification before opening a previously offered write action', async () => {
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [], nextAction: null, blockReasons: ['预约已由其他人修改'] }) }), followAction); await flushPromises()
|
|
||||||
expect(wrapper.findComponent({ name: 'WorkCommandForm' }).exists()).toBe(false)
|
|
||||||
expect(wrapper.text()).toContain('预约已由其他人修改'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('continues the real unbatched cargo action into original appointment creation with exact source scope', async () => {
|
|
||||||
const source = { customerId: 'customer-a', sourceKey: 'BOOKING:9007199254740999', destinationKey: 'FBA:ONT8' }
|
|
||||||
const action: WorkAction = { code: 'VERIFY_CARGO', label: '核实货物并建立预约', targetWorkItemKey: null, target: { kind: 'CARGO_VERIFICATION', source } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }) }), action); await flushPromises()
|
|
||||||
wrapper.getComponent({ name: 'CargoVerificationForm' }).vm.$emit('saved'); await flushPromises()
|
|
||||||
expect(wrapper.emitted('saved')).toBeUndefined()
|
|
||||||
await wrapper.findAll('button').find(button => button.text() === '核对货物并新建原预约')!.trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkCreateAppointmentForm' }).props('sources')).toEqual([source]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('uses the matched appointment business number and never passes the internal appointment ID to the old API', async () => {
|
|
||||||
const action: WorkAction = { code: 'CHANGE_BOOKING', label: '调整预约', targetWorkItemKey: null, target: { kind: 'FBA_APPOINTMENT', appointmentId: 'internal-id', batchKey: 'batch-1', sources: [] } }
|
|
||||||
const detail = workDetail({ item: workItem({ allowedActions: [action], nextAction: action }), references: [{ kind: 'FBA_APPOINTMENT', key: 'batch-1', businessNo: 'AP-TEST', label: '预约' }] })
|
|
||||||
const wrapper = render(detail, action); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkAppointmentForm' }).props('appointmentNo')).toBe('AP-TEST'); wrapper.unmount()
|
|
||||||
const missing = render({ ...detail, references: [] }, action); await flushPromises()
|
|
||||||
expect(missing.findComponent({ name: 'WorkAppointmentForm' }).exists()).toBe(false)
|
|
||||||
expect(missing.text()).toContain('尚未关联可操作的预约记录'); missing.unmount()
|
|
||||||
})
|
|
||||||
it('opens the receiving scope for the exact batch without changing the current work identity or losing result context', async () => {
|
|
||||||
const action: WorkAction = { code: 'CHANGE_BOOKING', label: '调整预约', targetWorkItemKey: null, target: { kind: 'FBA_APPOINTMENT', appointmentId: 'internal-id', batchKey: 'FBA_APPOINTMENT:1', sources: [] } }
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ allowedActions: [action], nextAction: action }), references: [{ kind: 'FBA_APPOINTMENT', key: 'FBA_APPOINTMENT:1', businessNo: 'AP-TEST', label: '预约' }] }), action)
|
|
||||||
await flushPromises(); wrapper.getComponent({ name: 'WorkAppointmentForm' }).vm.$emit('receiving', 'FBA_APPOINTMENT:1'); await flushPromises()
|
|
||||||
const scope = wrapper.getComponent({ name: 'WorkReceivingPanel' })
|
|
||||||
expect(scope.props('batchKey')).toBe('FBA_APPOINTMENT:1')
|
|
||||||
scope.vm.$emit('updated'); await flushPromises()
|
|
||||||
expect(wrapper.emitted('updated')).toHaveLength(1)
|
|
||||||
expect(getWorkDetail).toHaveBeenCalledTimes(2)
|
|
||||||
expect(getWorkDetail).toHaveBeenLastCalledWith('work-delivery-1', expect.any(AbortSignal))
|
|
||||||
expect(wrapper.findComponent({ name: 'WorkReceivingPanel' }).exists()).toBe(true)
|
|
||||||
expect(wrapper.emitted('saved')).toBeUndefined()
|
|
||||||
scope.vm.$emit('appointment', 'AP-LATER'); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkAppointmentForm' }).props('appointmentNo')).toBe('AP-LATER')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('resolves the saved later batch and offers its real vehicle next action instead of refreshing the historical work', async () => {
|
|
||||||
const edit: WorkAction = { code: 'CHANGE_BOOKING', label: '调整预约', targetWorkItemKey: null, target: { kind: 'FBA_APPOINTMENT', appointmentId: '1', batchKey: 'FBA_APPOINTMENT:1', sources: [] } }
|
|
||||||
const original = workDetail({ item: workItem({ allowedActions: [edit], nextAction: edit }), references: [{ kind: 'FBA_APPOINTMENT', key: 'FBA_APPOINTMENT:1', businessNo: 'AP-OLD', label: '预约' }] })
|
|
||||||
const wrapper = render(original, edit); await flushPromises()
|
|
||||||
wrapper.getComponent({ name: 'WorkAppointmentForm' }).vm.$emit('receiving', 'FBA_APPOINTMENT:1'); await flushPromises()
|
|
||||||
wrapper.getComponent({ name: 'WorkReceivingPanel' }).vm.$emit('appointment', 'AP-LATER-40'); await flushPromises()
|
|
||||||
const transport: WorkAction = { code: 'ARRANGE_TRANSPORT', label: '继续安排本批车辆', targetWorkItemKey: 'real-transport-later', target: { kind: 'FLEET_TRIP', tripId: null, batchKeys: ['FBA_APPOINTMENT:40'] } }
|
|
||||||
const childDetail = workDetail({ item: workItem({ workItemKey: 'real-work-child', batchKey: 'FBA_APPOINTMENT:40', nextAction: transport, allowedActions: [transport] }) })
|
|
||||||
vi.mocked(resolveBatchWork).mockResolvedValue({ batchKey: 'FBA_APPOINTMENT:40', customerId: 'customer-a', detail: childDetail, candidates: [] })
|
|
||||||
wrapper.getComponent({ name: 'WorkAppointmentForm' }).vm.$emit('saved', batchContext('AP-LATER-40', 'FBA_APPOINTMENT:40').appointment); await flushPromises()
|
|
||||||
expect(resolveBatchWork).toHaveBeenCalledWith('FBA_APPOINTMENT:40', undefined, expect.any(AbortSignal))
|
|
||||||
expect(getWorkDetail).toHaveBeenCalledTimes(1)
|
|
||||||
expect(wrapper.emitted('saved')).toBeUndefined()
|
|
||||||
expect(wrapper.emitted('open')).toEqual([['real-work-child']]); wrapper.unmount()
|
|
||||||
const current = render(childDetail); await flushPromises()
|
|
||||||
expect(current.get('.primary-next-action').text()).toBe('继续安排本批车辆')
|
|
||||||
await current.get('.primary-next-action').trigger('click'); await flushPromises()
|
|
||||||
expect(current.emitted('open')).toEqual([['real-transport-later', transport]]); current.unmount()
|
|
||||||
})
|
|
||||||
it('displays all associated containers of a shared trip without creating duplicate transport work', async () => {
|
|
||||||
const wrapper = render(workDetail({ item: workItem({ type: 'TRANSPORT', containers: [{ containerBookingId: '1', bookingNo: 'D-1', containerNo: 'TEST-CN-A' }, { containerBookingId: '2', bookingNo: 'D-2', containerNo: 'TEST-CN-B' }] }) })); await flushPromises()
|
|
||||||
expect(wrapper.findAll('.container-links button')).toHaveLength(2)
|
|
||||||
await wrapper.findAll('.container-links button')[1]!.trigger('click'); expect(wrapper.emitted('container')).toEqual([['2', 'TEST-CN-B']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,200 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import { getWorkDetail, type WorkAction, type WorkDetail, type WorkCommand, type WorkCommandResult } from './workApi'
|
|
||||||
import { actionAllowed, actionRoute, referenceRoute, commandName, flowLabels, typeLabels, workDate, workStatus, workReason, sameAction } from './workPresentation'
|
|
||||||
import CargoVerificationForm from './CargoVerificationForm.vue'
|
|
||||||
import WorkCommandForm from './WorkCommandForm.vue'
|
|
||||||
import WorkAppointmentForm from './WorkAppointmentForm.vue'
|
|
||||||
import WorkCreateAppointmentForm from './WorkCreateAppointmentForm.vue'
|
|
||||||
import WorkDispatchForm from './WorkDispatchForm.vue'
|
|
||||||
import WorkExistingDispatchForm from './WorkExistingDispatchForm.vue'
|
|
||||||
import WorkReceiptPlans from './WorkReceiptPlans.vue'
|
|
||||||
import AppointmentBatchForm from './AppointmentBatchForm.vue'
|
|
||||||
import WorkReceivingPanel from './WorkReceivingPanel.vue'
|
|
||||||
import WorkBatchContinuation from './WorkBatchContinuation.vue'
|
|
||||||
import type { FbaAppointmentDto } from '@/modules/overseas-warehouse'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
import { useWorkSyncRead } from './useWorkSyncRead'
|
|
||||||
const props = defineProps<{ itemKey: string; initialAction?: WorkAction | null; canLeave: LeaveGuard }>()
|
|
||||||
const emit = defineEmits<{ open: [key: string, action?: WorkAction]; external: [path: string]; saved: [result?: WorkCommandResult, command?: WorkCommand['command']]; updated: []; container: [id: string, label: string] }>()
|
|
||||||
const detail = ref<WorkDetail | null>(null), loading = ref(false), error = ref<ApiErrorDetails | null>(null), action = ref<WorkAction | null>(null)
|
|
||||||
const attentionReasons = computed(() => [...new Set([
|
|
||||||
...(detail.value?.item.blockReasons || []),
|
|
||||||
...(detail.value?.item.missingFields || []),
|
|
||||||
...(detail.value?.item.overdueReasons || []),
|
|
||||||
].map(workReason))])
|
|
||||||
const needsFollowup = computed(() => !!detail.value && detail.value.item.executionStatus !== 'COMPLETED' && (!detail.value.item.owner || !detail.value.item.followupDate))
|
|
||||||
const historyLabels: Record<string, string> = { BASELINE_OBSERVED: '同步原业务状态', GENERATED: '创建工作事项', CONFIRM_ROUTE: '确认路线', SAVE_FOLLOWUP: '记录跟进', RESOLVE_REVIEW: '处理复核', SAVE_REQUIREMENT: '保存预约要求', HANDOFF_RETURN: '交接还空责任', ACCEPT_RETURN: '确认接手还空' }
|
|
||||||
function historyTime(value: string) { return value.replace('T', ' ').replace(/\.\d+(?=Z|[+-]\d{2}:\d{2}$)/, '').replace(/Z$/, ' UTC') }
|
|
||||||
const receivingOwners = computed(() => [detail.value?.item.owner, ...(detail.value?.relatedItems.map(item => item.owner) || [])].filter((person): person is { id: string; name: string } => !!person?.id))
|
|
||||||
const actionNotice = ref('')
|
|
||||||
const saveCompleted = ref(false)
|
|
||||||
const creatingFromCargo = ref(false)
|
|
||||||
const batchKey = ref<string | null>(null), openedAppointmentNo = ref<string | null>(null)
|
|
||||||
const receivingKey = ref<string | null>(null)
|
|
||||||
const continuation = ref<{ batchKey: string; customerId?: string; labels?: Array<{ customerId: string; label: string }> } | null>(null)
|
|
||||||
let controller: AbortController | null = null, request = 0
|
|
||||||
const syncRead = useWorkSyncRead(), syncing = syncRead.syncing
|
|
||||||
async function load() {
|
|
||||||
const generation = ++request; controller?.abort(); controller = new AbortController(); loading.value = true; error.value = null
|
|
||||||
const signal = controller.signal
|
|
||||||
try { const result = await syncRead.read(() => getWorkDetail(props.itemKey, signal), signal); if (generation === request) detail.value = result }
|
|
||||||
catch (cause) { if (generation === request) error.value = getApiErrorDetails(cause, '工作事项读取失败') }
|
|
||||||
finally { if (generation === request) loading.value = false }
|
|
||||||
}
|
|
||||||
const fbaNumber = computed(() => {
|
|
||||||
const target = action.value?.target
|
|
||||||
if (target?.kind !== 'FBA_APPOINTMENT' || !target.appointmentId) return null
|
|
||||||
return detail.value?.references.find(ref => ref.kind === 'FBA_APPOINTMENT' && ref.key === target.batchKey)?.businessNo || null
|
|
||||||
})
|
|
||||||
const cargoSource = computed(() => {
|
|
||||||
const target = action.value?.target
|
|
||||||
return target?.kind === 'CARGO_VERIFICATION' ? { ...target.source, destinationKey: target.source.destinationKey || undefined } : null
|
|
||||||
})
|
|
||||||
const createSources = computed(() => creatingFromCargo.value && action.value?.target.kind === 'CARGO_VERIFICATION' ? [action.value.target.source] : action.value?.target.kind === 'FBA_APPOINTMENT' && !action.value.target.appointmentId && ['SAVE_PLAN', 'REQUEST_BOOKING', 'RECORD_CONFIRMATION'].includes(action.value.code) ? action.value.target.sources : null)
|
|
||||||
const dispatchBatchKeys = computed(() => {
|
|
||||||
const target = action.value?.target
|
|
||||||
if (target?.kind !== 'FLEET_TRIP' || target.tripId || action.value?.code !== 'ARRANGE_TRANSPORT') return null
|
|
||||||
return target.batchKeys.length && target.batchKeys.every(key => /^FBA_APPOINTMENT:\d+$/.test(key)) ? target.batchKeys : null
|
|
||||||
})
|
|
||||||
const existingDispatches = computed(() => {
|
|
||||||
const target = action.value?.target
|
|
||||||
if (target?.kind !== 'FLEET_TRIP' || target.tripId || action.value?.code !== 'ARRANGE_TRANSPORT' || target.batchKeys.length !== 1) return []
|
|
||||||
const batchKey = target.batchKeys[0]!, item = detail.value?.item
|
|
||||||
return /^DISPATCH:\d+$/.test(batchKey) && item?.batchKey === batchKey && item.batchNo ? [{ batchKey, dispatchNo: item.batchNo }] : []
|
|
||||||
})
|
|
||||||
const canAct = computed(() => !!detail.value && !!action.value && actionAllowed(detail.value.item, action.value) && !error.value && !loading.value)
|
|
||||||
const secondaryActions = computed(() => detail.value?.item.allowedActions.filter(candidate => candidate.code !== action.value?.code && (action.value || !detail.value?.item.nextAction || !sameAction(candidate, detail.value.item.nextAction))) || [])
|
|
||||||
async function choose(next: WorkAction) {
|
|
||||||
if (!detail.value || loading.value || error.value || !await props.canLeave()) return
|
|
||||||
actionNotice.value = ''
|
|
||||||
// 跨事项的主要下一步只用于导航,目标面板会重新读取并校验自己的写入资格。
|
|
||||||
const linkedNext = next.targetWorkItemKey && next.targetWorkItemKey !== props.itemKey && detail.value.item.nextAction && sameAction(next, detail.value.item.nextAction)
|
|
||||||
if (!linkedNext && !actionAllowed(detail.value.item, next)) { actionNotice.value = '操作资格已变化,请刷新事项后查看当前下一步。'; return }
|
|
||||||
saveCompleted.value = false
|
|
||||||
if (next.targetWorkItemKey && next.targetWorkItemKey !== props.itemKey) { emit('open', next.targetWorkItemKey, next); return }
|
|
||||||
const path = actionRoute(next, detail.value.references, detail.value.item)
|
|
||||||
if (path) { emit('external', path); return }
|
|
||||||
action.value = next; batchKey.value = null; openedAppointmentNo.value = null; receivingKey.value = null; continuation.value = null; creatingFromCargo.value = false
|
|
||||||
if (next.code === 'EDIT_BATCH' && next.target.kind === 'FBA_APPOINTMENT' && next.target.batchKey) { batchKey.value = next.target.batchKey; return }
|
|
||||||
if (next.target.kind === 'WORK_COMMAND' && !commandName(next)) actionNotice.value = '当前操作尚未提供可用入口,请联系负责人核对。'
|
|
||||||
if (next.target.kind === 'FBA_APPOINTMENT' && !fbaNumber.value && !createSources.value) actionNotice.value = '尚未关联可操作的预约记录,请先核实批次与预约关系。'
|
|
||||||
if (next.target.kind === 'FLEET_TRIP' && !dispatchBatchKeys.value?.length && !existingDispatches.value.length) actionNotice.value = '尚未关联可进入的车次或可排批次,请核对运输来源。'
|
|
||||||
}
|
|
||||||
async function saved(result?: WorkCommandResult, command?: WorkCommand['command']) {
|
|
||||||
action.value = null; batchKey.value = null; openedAppointmentNo.value = null; receivingKey.value = null; creatingFromCargo.value = false; actionNotice.value = ''; saveCompleted.value = true
|
|
||||||
emit('saved', result, command)
|
|
||||||
await load()
|
|
||||||
}
|
|
||||||
async function savedAppointment(appointment: FbaAppointmentDto) {
|
|
||||||
if (!appointment.batchKey) { await saved(); return }
|
|
||||||
action.value = null; batchKey.value = null; openedAppointmentNo.value = null; receivingKey.value = null; saveCompleted.value = true
|
|
||||||
continuation.value = { batchKey: appointment.batchKey, labels: [...new Set(appointment.items.map(item => item.customerId))].map(customerId => ({ customerId, label: appointment.items.filter(item => item.customerId === customerId).map(item => item.inboundCode || '—').join('、') })) }
|
|
||||||
emit('updated')
|
|
||||||
}
|
|
||||||
async function receivingUpdated() { emit('updated'); await load() }
|
|
||||||
async function cargoSaved() { emit('updated'); await load() }
|
|
||||||
async function createFromCargo() { if (canAct.value && await props.canLeave()) creatingFromCargo.value = true }
|
|
||||||
async function openBatch(key: string) { if (await props.canLeave()) { batchKey.value = key; openedAppointmentNo.value = null; receivingKey.value = null } }
|
|
||||||
async function openAppointment(number: string) { if (await props.canLeave()) { openedAppointmentNo.value = number; batchKey.value = null; receivingKey.value = null } }
|
|
||||||
async function openReceiving(key: string) { if (await props.canLeave()) { receivingKey.value = key; batchKey.value = null; openedAppointmentNo.value = null } }
|
|
||||||
onMounted(async () => {
|
|
||||||
await load()
|
|
||||||
// A predecessor's action is only a hint: use the newly fetched item's own qualification.
|
|
||||||
if (props.initialAction && detail.value) {
|
|
||||||
const own = detail.value.item.allowedActions.find(candidate => candidate.code === props.initialAction?.code && candidate.target.kind === props.initialAction?.target.kind)
|
|
||||||
if (own) await choose(own)
|
|
||||||
else if (detail.value.item.nextAction) await choose(detail.value.item.nextAction)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
onBeforeUnmount(() => { ++request; controller?.abort() })
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<div class="work-detail" :aria-busy="loading">
|
|
||||||
<LoadErrorState v-if="error" title="工作事项读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<p v-if="loading" role="status">{{ syncing ? '预约工作清单同步中,正在自动读取最新事项;已保存内容无需重复提交。' : '正在读取当前事项与操作资格…' }}</p>
|
|
||||||
<template v-if="detail">
|
|
||||||
<header class="detail-overview">
|
|
||||||
<div class="detail-title"><h3>{{ detail.item.title }}</h3><el-tag :type="detail.item.executionStatus === 'COMPLETED' ? 'success' : detail.item.reviewRequired ? 'warning' : 'info'" size="small">{{ workStatus(detail.item) }}</el-tag></div>
|
|
||||||
<p class="detail-category">{{ typeLabels[detail.item.type] }} · {{ flowLabels[detail.item.flow] }}</p>
|
|
||||||
</header>
|
|
||||||
<dl class="density-fields detail-facts" aria-label="事项关键信息">
|
|
||||||
<div><dt>作业时间</dt><dd>{{ workDate(detail.item) }}</dd></div>
|
|
||||||
<div><dt>作业时区</dt><dd>{{ detail.item.timezone || '地点时区待核实' }}</dd></div>
|
|
||||||
<div><dt>作业地点</dt><dd>{{ detail.item.destinationName || detail.item.originName || '地点待核实' }}</dd></div>
|
|
||||||
<div><dt>负责人</dt><dd>{{ detail.item.owner?.name || '待分派' }}</dd></div>
|
|
||||||
<div class="followup-summary"><dt>下次跟进</dt><dd>{{ detail.item.followupDate || '尚未安排' }}<span v-if="detail.item.dateBasis === 'NONE'" class="field-note">作业日期未定,跟进日不作为作业日期</span></dd></div>
|
|
||||||
</dl>
|
|
||||||
<div v-if="detail.item.containers.length" class="container-links"><span>关联货柜</span><el-button v-for="container in detail.item.containers" :key="container.containerBookingId" class="density-action" data-tone="primary" @click="emit('container', container.containerBookingId, container.containerNo || container.bookingNo || '本柜')">{{ container.containerNo || container.bookingNo || '—' }} · 本柜待办</el-button></div>
|
|
||||||
<aside v-if="needsFollowup || attentionReasons.length" class="attention-panel" aria-label="事项提醒">
|
|
||||||
<h4>事项提醒</h4>
|
|
||||||
<ul>
|
|
||||||
<li v-if="needsFollowup">{{ !detail.item.owner ? '负责人待分派。' : '' }}{{ !detail.item.followupDate ? '请补充下一次跟进安排。' : '' }}请记录跟进;若无操作权限,请联系负责人。</li>
|
|
||||||
<li v-for="reason in attentionReasons" :key="reason">{{ reason }}</li>
|
|
||||||
</ul>
|
|
||||||
</aside>
|
|
||||||
<p v-if="detail.returnHandoff">还空责任:{{ detail.returnHandoff.from.name }} → {{ detail.returnHandoff.to.name }} · {{ detail.returnHandoff.status === 'PENDING_ACCEPTANCE' ? '接手方待确认,持续跟进' : '已确认接手' }}</p>
|
|
||||||
<section class="current-work" aria-label="当前处理">
|
|
||||||
<h4>{{ detail.item.executionStatus === 'COMPLETED' ? '事项结果' : '当前处理' }}</h4>
|
|
||||||
<p v-if="detail.item.executionStatus === 'COMPLETED'" class="completion-summary">当前事项已完成,可查看关联工作和历史记录。</p>
|
|
||||||
<template v-if="!action && !continuation">
|
|
||||||
<p v-if="saveCompleted" role="status" class="save-result">本次保存已完成。{{ loading ? '正在读取当前下一步…' : error ? '下一步读取失败,请重试读取事项,无需重复提交已保存内容。' : detail.item.executionStatus === 'COMPLETED' ? '当前事项已完成,可返回查看其他待办。' : '请按当前下一步继续处理。' }}</p>
|
|
||||||
<el-button v-if="detail.item.nextAction" class="primary-next-action" type="primary" :disabled="loading || !!error" @click="choose(detail.item.nextAction)">{{ detail.item.nextAction.label }}</el-button>
|
|
||||||
<p v-else-if="detail.item.executionStatus !== 'COMPLETED'">当前没有可执行的下一步,请根据缺项或前置说明联系负责人。</p>
|
|
||||||
</template>
|
|
||||||
<p v-if="actionNotice" role="status" class="work-warning">{{ actionNotice }}</p>
|
|
||||||
<WorkBatchContinuation v-if="continuation" :key="JSON.stringify(continuation)" v-bind="continuation" @open="key => emit('open', key)" />
|
|
||||||
<WorkReceivingPanel v-else-if="receivingKey" :key="receivingKey" :batch-key="receivingKey" :owners="receivingOwners" :can-write="!loading && !error" @updated="receivingUpdated" @appointment="openAppointment" @batch="openBatch" @external="path => emit('external', path)" />
|
|
||||||
<AppointmentBatchForm v-else-if="batchKey" :key="batchKey" :batch-key="batchKey" @updated="emit('updated')" @appointment="openAppointment" />
|
|
||||||
<WorkAppointmentForm v-else-if="openedAppointmentNo" :key="openedAppointmentNo" :appointment-no="openedAppointmentNo" :cancel="false" :can-write="true" @saved="savedAppointment" @batch="openBatch" @receiving="openReceiving" />
|
|
||||||
<WorkCommandForm v-else-if="action && commandName(action)" :key="`${itemKey}:${action.code}`" :detail="detail" :action="action" :refreshing="loading || !!error" @refresh="load" @saved="saved" />
|
|
||||||
<template v-else-if="cargoSource && !creatingFromCargo"><CargoVerificationForm :key="`${cargoSource.customerId}:${cargoSource.sourceKey}:${cargoSource.destinationKey}`" :source="cargoSource" @saved="cargoSaved" /><el-button :disabled="!canAct" @click="createFromCargo">核对货物并新建原预约</el-button></template>
|
|
||||||
<WorkAppointmentForm v-else-if="fbaNumber && action" :key="`${fbaNumber}:${action.code}`" :appointment-no="fbaNumber" :cancel="action.code === 'CANCEL_BOOKING'" :can-write="canAct" @saved="savedAppointment" @batch="openBatch" @receiving="openReceiving" />
|
|
||||||
<WorkCreateAppointmentForm v-else-if="createSources" :key="JSON.stringify(createSources)" :sources="createSources" :can-write="canAct" @saved="saved()" />
|
|
||||||
<WorkDispatchForm v-else-if="dispatchBatchKeys?.length" :key="JSON.stringify(dispatchBatchKeys)" :batch-keys="dispatchBatchKeys" :can-write="canAct" @updated="emit('updated')" @external="path => emit('external', path)" @batch="openBatch" />
|
|
||||||
<WorkExistingDispatchForm v-else-if="existingDispatches.length" :key="JSON.stringify(existingDispatches)" :dispatches="existingDispatches" :can-write="canAct" @updated="emit('updated')" @external="path => emit('external', path)" />
|
|
||||||
<WorkReceiptPlans v-else-if="action?.target.kind === 'WAREHOUSE_RECEIPT'" :key="action.target.containerBookingId" :container-booking-id="action.target.containerBookingId" :can-write="canAct" @updated="emit('updated')" @external="path => emit('external', path)" />
|
|
||||||
<section v-else-if="action?.target.kind === 'READ_ONLY' && action.target.references.length" aria-label="原业务进度"><h4>原业务进度</h4><p v-for="reference in action.target.references" :key="`${reference.kind}:${reference.key}`"><el-button v-if="referenceRoute(reference)" :disabled="!canAct" @click="emit('external', referenceRoute(reference)!)">{{ reference.label }} · {{ reference.businessNo }}</el-button><span v-else>{{ reference.label }} · {{ reference.businessNo || '—' }}</span></p></section>
|
|
||||||
<details v-if="secondaryActions.length"><summary>更多操作</summary><div class="more-actions"><el-button v-for="candidate in secondaryActions" :key="`${candidate.code}:${candidate.targetWorkItemKey}`" :disabled="loading || !!error" @click="choose(candidate)">{{ candidate.label }}</el-button></div></details>
|
|
||||||
</section>
|
|
||||||
<section class="detail-records" aria-label="关联资料与历史">
|
|
||||||
<details><summary>关联工作 · {{ detail.relatedItems.length }} 项</summary><div v-for="related in detail.relatedItems" :key="related.workItemKey" class="related-row"><div>{{ related.title }}<p>{{ workStatus(related) }} · {{ workDate(related) }}</p></div><el-button class="density-action" @click="emit('open', related.workItemKey)">查看</el-button></div><p v-if="!detail.relatedItems.length">暂无关联工作</p></details>
|
|
||||||
<details><summary>原业务记录 · {{ detail.references.length }} 项</summary><p v-for="reference in detail.references" :key="`${reference.kind}:${reference.key}`">{{ reference.label }} · {{ reference.businessNo || '—' }}</p><p v-if="!detail.references.length">暂无原业务记录</p></details>
|
|
||||||
<details :open="action?.code === 'VIEW_HISTORY'"><summary>操作记录 · {{ detail.history.length }} 条</summary><div v-for="(entry, index) in detail.history" :key="index" class="history-entry"><div class="history-heading"><b>{{ historyLabels[entry.action] || '事项记录' }}</b><time :datetime="entry.occurredAt">{{ historyTime(entry.occurredAt) }}</time></div><p>{{ entry.summary }}</p><small>{{ entry.operatorName || '—' }}<span v-if="!historyLabels[entry.action]"> · {{ entry.action }}</span></small></div><p v-if="!detail.history.length">暂无记录</p></details>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
<style scoped>
|
|
||||||
.work-detail { font-size: var(--admin-font-body); line-height: 1.6; color: var(--el-text-color-primary); }
|
|
||||||
.detail-overview { margin-bottom: var(--admin-space-5); }
|
|
||||||
.detail-title { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-3); }
|
|
||||||
.detail-title h3 { margin: 0; font-size: var(--admin-font-title); }
|
|
||||||
.detail-category { margin: var(--admin-space-1) 0 0; color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); }
|
|
||||||
.work-detail .detail-facts { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
|
||||||
.followup-summary { grid-column: 1 / -1; }
|
|
||||||
.field-note { margin-left: var(--admin-space-5); color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); }
|
|
||||||
.container-links, .more-actions { display: flex; align-items: center; flex-wrap: wrap; gap: var(--admin-space-3); }
|
|
||||||
.container-links { margin-top: var(--admin-space-3); }
|
|
||||||
.container-links > span { color: var(--el-text-color-secondary); font-size: var(--admin-font-caption); }
|
|
||||||
.attention-panel { margin-top: var(--admin-space-5); padding: var(--admin-space-3) var(--admin-space-5); border: 1px solid var(--el-color-warning-light-7); border-radius: var(--admin-dialog-section-radius); background: var(--el-color-warning-light-9); color: var(--el-color-warning-dark-2); }
|
|
||||||
.attention-panel h4, .current-work > h4 { margin: 0 0 var(--admin-space-1); font-size: var(--admin-font-section); }
|
|
||||||
.attention-panel ul { margin: 0; padding-left: var(--admin-space-6); font-size: var(--admin-font-caption); }
|
|
||||||
.current-work { margin-top: var(--admin-space-5); padding-block: var(--admin-space-5); border-top: 1px solid var(--workbench-border); }
|
|
||||||
.current-work > p { margin: var(--admin-space-2) 0; }
|
|
||||||
.completion-summary { color: var(--el-color-success-dark-2); }
|
|
||||||
.detail-records { border-top: 1px solid var(--workbench-border); }
|
|
||||||
.detail-records > details { border-bottom: 1px solid var(--workbench-border); }
|
|
||||||
summary { cursor: pointer; padding-block: var(--admin-space-3); font-weight: 600; }
|
|
||||||
summary:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: -2px; }
|
|
||||||
.detail-records p { margin: var(--admin-space-1) 0; }
|
|
||||||
.related-row, .history-heading { display: flex; align-items: baseline; justify-content: space-between; flex-wrap: wrap; gap: var(--admin-space-3); }
|
|
||||||
.related-row, .history-entry { border-bottom: 1px solid var(--workbench-border); padding-block: var(--admin-space-3); }
|
|
||||||
.related-row:last-child, .history-entry:last-child { border-bottom: 0; }
|
|
||||||
.related-row p, .history-entry small, .history-heading time { font-size: var(--admin-font-caption); color: var(--el-text-color-secondary); }
|
|
||||||
.work-warning { color: var(--el-color-warning-dark-2); }
|
|
||||||
</style>
|
|
||||||
@@ -1,197 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkDispatchForm from './WorkDispatchForm.vue'
|
|
||||||
import { getDispatch, getBatchDispatchCandidates, listDispatchCandidates, createDispatchDraft, createDispatchDraftContainer, listDispatchDrafts, lockDispatchDraftPallet, convertDispatchDraft, releaseDispatchDraft, type BatchDispatchCandidate, type Candidate, type CommandResult, type DispatchDetail, type DispatchDraft } from '@/modules/overseas-warehouse'
|
|
||||||
import { ApiResponseError, http } from '@/shared/api/http'
|
|
||||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
|
||||||
import { getReceivingContext, type ReceivingContext } from './receivingApi'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
const access = vi.hoisted(() => ({ allowed: true, denied: [] as string[] }))
|
|
||||||
const identity = vi.hoisted(() => ({ id: '' }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: (permission: string) => access.allowed && !access.denied.includes(permission) }) }))
|
|
||||||
vi.mock('@/core/auth/auth', () => ({ useAuthStore: () => ({ user: identity }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
|
||||||
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getDispatch: vi.fn(), getBatchDispatchCandidates: vi.fn(), listDispatchCandidates: vi.fn(), createDispatchDraft: vi.fn(), createDispatchDraftContainer: vi.fn(), listDispatchDrafts: vi.fn(), lockDispatchDraftPallet: vi.fn(), convertDispatchDraft: vi.fn(), releaseDispatchDraft: vi.fn() }))
|
|
||||||
vi.mock('./receivingApi', async original => ({ ...await original<typeof import('./receivingApi')>(), getReceivingContext: vi.fn() }))
|
|
||||||
const clone = <T,>(value: T): T => JSON.parse(JSON.stringify(value)) as T
|
|
||||||
const batch = 'FBA_APPOINTMENT:1'
|
|
||||||
function receiving(key = batch, vehicles: ReceivingContext['transport']['vehicles'] = []): ReceivingContext { return { batch: batchContext('AP-1', key).appointment, plans: [], agreements: [], pendingChanges: [], transport: { version: 'transport', vehicles, blockReasons: [] }, executionScope: { version: 'execution', members: [] }, allowedActions: [], blockReasons: [] } }
|
|
||||||
function row(id = '9007199254740993', customerId = 'customer-a', key = batch): BatchDispatchCandidate { return { planPalletId: id, palletNo: `PALLET-${id.slice(-2)}`, planId: `plan-${id}`, planNo: 'IP-001', customerId, sourceStage: 'RECEIVED', packageCount: 12, allocations: [{ planPalletId: id, batchKey: key, customerId, sourceKey: customerId === 'customer-a' ? 'ORDER:1' : 'BOOKING:2', destinationKey: 'FBA:ONT8', packageCount: 12, recordVersion: 4 }], blockReasons: [] } }
|
|
||||||
function candidate(value = row()): Candidate { const base = { selection: { sourceType: 'INBOUND_PLAN', planPalletId: value.planPalletId, returnReceiptId: null, relabelNo: null, warehousePalletId: `pallet-${value.planPalletId}`, sourceVersion: `source-${value.planPalletId}` }, sourceKey: `cargo-${value.planPalletId}`, sourceVersion: `source-${value.planPalletId}`, customerId: value.customerId, customerName: value.customerId === 'customer-a' ? '客户甲' : '客户乙', warehouseId: 'origin-1', warehouseCode: 'LAX', warehouseName: '真实起运仓', orderNo: 'LM-1', inboundCode: 'IN-A', planNo: value.planNo, palletNo: value.palletNo, containerNo: null, destination: { key: 'CODE:ONT8', type: 'FBA', warehouseId: null, warehouseCode: 'ONT8', warehouseName: 'ONT8', address: null, postalCode: null, contactName: null, contactPhone: null }, availablePackages: 12, suggestedWeightKg: null, suggestedVolumeCbm: null, measurementSource: null, appointmentBatches: [], blockReasons: [] }; return { ...base, selection: { ...base.selection, sourceType: 'INBOUND_PLAN' }, selectionGroup: { groupKey: base.sourceKey, groupVersion: 'group-1', sources: [{ selection: { ...base.selection, sourceType: 'INBOUND_PLAN' }, sourceKey: base.sourceKey, customerId: base.customerId, customerName: base.customerName, sourceBusinessType: null, sourceBusinessNo: null, packages: base.availablePackages }], pallets: [{ warehousePalletId: base.selection.warehousePalletId, palletNo: base.palletNo, sourceKeys: [base.sourceKey], packageCount: base.availablePackages }], complete: true, blockReasons: [] } } }
|
|
||||||
function detail(no = 'DS/001', version = 1): DispatchDetail {
|
|
||||||
const review = { status: 'NOT_SUBMITTED' as const, reason: null, reviewerId: null, reviewedAt: null, reviewRound: 0, basisHash: null, invalidatedReason: null }
|
|
||||||
return { dispatchNo: no, status: 'ACTIVE', stage: 'BEFORE_LOADING', recordVersion: version, reviewState: 'DRAFT', reviews: { dispatchReview: review, loadingReview: review }, counts: { itemCount: 1, palletCount: 1, packageCount: 12, pickedPackageCount: 0, shippedPackageCount: 0 }, pickingReconciled: false, actions: { EDIT: { allowed: true, blockCode: null, blockReason: null }, ADD_CARGO: { allowed: true, blockCode: null, blockReason: null } }, vehicleInfo: { vehicle: null, driver: null }, dispatchInfo: { route: null, plannedDepartureAt: null, departedAt: null, estimatedArrivalAt: null, fbaAppointments: [], appointmentBatches: [{ batchKey: batch, batchNo: 'AP-1', recordVersion: 4, customerId: 'customer-a', sources: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', packageCount: 12 }] }] }, documents: { dispatchNo: no, outbounds: [], deliveries: [], createdAt: '', updatedAt: '', remark: null }, orderDetails: [] }
|
|
||||||
}
|
|
||||||
function proof(key: string): CommandResult { return { dispatchNo: 'DS/001', action: 'CREATE', idempotencyKey: key, recordVersion: 1, status: 'ACTIVE', stage: 'BEFORE_LOADING', occurredAt: '2026-10-19T00:00:00Z', effect: 'APPLIED', counts: detail().counts, result: { dispatchNo: 'DS/001', changedItemIds: [] }, replayed: false, alreadyArranged: false } }
|
|
||||||
let guard: LeaveGuard, natives: Candidate[], draft: DispatchDraft
|
|
||||||
function render(props: { batchKeys?: string[]; canWrite?: boolean } = {}) { return mount(WorkDispatchForm, { props: { batchKeys: [batch], canWrite: true, ...props }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: { WorkSharedTripForm: { name: 'WorkSharedTripForm', props: ['dispatchNo', 'canWrite'], template: '<div data-same-dispatch />' }, ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, LoadErrorState: { props: ['message'], template: '<p role="alert">{{ message }}</p>' }, ApiErrorMeta: true } } }) }
|
|
||||||
const button = (wrapper: ReturnType<typeof render>, label: string) => wrapper.findAll('button').find(value => value.text() === label)!
|
|
||||||
it.each([0, '0', '9007199254740993'])('preserves authoritative allocation version %s from the existing batch provider', async recordVersion => {
|
|
||||||
const value = row(); value.allocations[0]!.recordVersion = recordVersion
|
|
||||||
vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: batch, version: 4, candidates: [value], blockReasons: [] })
|
|
||||||
const wrapper = render()
|
|
||||||
try {
|
|
||||||
await flushPromises(); await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises()
|
|
||||||
expect(vi.mocked(convertDispatchDraft).mock.calls[0]![0].groups[0]!.dispatch.batchAllocations[0]!.recordVersion).toBe(recordVersion)
|
|
||||||
} finally { wrapper.unmount() }
|
|
||||||
})
|
|
||||||
it.each([undefined, null, 'bad', 9007199254740992])('blocks an existing-batch candidate lacking a valid authoritative version: %s', async recordVersion => {
|
|
||||||
const value = row(); value.allocations[0]!.recordVersion = recordVersion as unknown as number
|
|
||||||
vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: batch, version: 0, candidates: [value], blockReasons: [] })
|
|
||||||
const wrapper = render()
|
|
||||||
try { await flushPromises(); expect(wrapper.text()).toContain('预约批次版本缺失或无效,请重新读取候选'); expect(createDispatchDraft).not.toHaveBeenCalled() }
|
|
||||||
finally { wrapper.unmount() }
|
|
||||||
})
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.resetAllMocks(); sessionStorage.clear(); identity.id = crypto.randomUUID(); access.allowed = true; access.denied = []
|
|
||||||
natives = [candidate()]; draft = { draftToken: 'server-owned-token', recordVersion: 0, status: 'ACTIVE', warehouseId: 'origin-1', containers: [], sources: [], expiresAt: '2026-10-20T00:00:00Z' }
|
|
||||||
vi.mocked(getReceivingContext).mockImplementation(async key => receiving(key))
|
|
||||||
vi.mocked(getBatchDispatchCandidates).mockImplementation(async key => ({ batchKey: key, version: 4, candidates: [row('9007199254740993', 'customer-a', key)], blockReasons: [] }))
|
|
||||||
vi.mocked(listDispatchCandidates).mockImplementation(async () => ({ total: 1, page: 1, size: 20, pages: 1, candidates: clone(natives), complete: true, snapshotAt: '2026-10-19T00:00:00Z' }))
|
|
||||||
vi.mocked(createDispatchDraft).mockImplementation(async () => clone(draft))
|
|
||||||
vi.mocked(createDispatchDraftContainer).mockImplementation(async body => { draft.recordVersion = 1; draft.containers = [{ draftContainerId: 'container-1', sequenceNo: 1, capacity: body.capacity, sourceKeys: [] }]; return clone(draft) })
|
|
||||||
vi.mocked(lockDispatchDraftPallet).mockImplementation(async body => { const source = natives.find(value => value.selection.planPalletId === body.source.planPalletId)!; draft.recordVersion = Number(draft.recordVersion) + 1; draft.sources.push(clone(source)); draft.containers[0]!.sourceKeys.push(source.sourceKey); return clone(draft) })
|
|
||||||
vi.mocked(convertDispatchDraft).mockImplementation(async body => ({ draftToken: body.draftToken, replayed: false, vehicles: [{ draftContainerId: 'container-1', dispatch: proof(body.groups[0]!.dispatch.idempotencyKey) }] }))
|
|
||||||
vi.mocked(getDispatch).mockImplementation(async no => detail(no)); vi.mocked(listDispatchDrafts).mockImplementation(async () => [clone(draft)])
|
|
||||||
vi.mocked(releaseDispatchDraft).mockImplementation(async () => ({ ...clone(draft), status: 'RELEASED', containers: [], sources: [] }))
|
|
||||||
})
|
|
||||||
it('creates the whole dispatch when native Long candidate quantities arrive as strings and batch quantities are Integers', async () => {
|
|
||||||
const actual = await vi.importActual<typeof import('../overseas-warehouse/api/dispatches')>('../overseas-warehouse/api/dispatches')
|
|
||||||
const get = vi.spyOn(http, 'get').mockResolvedValue(parseApiJsonResponse(JSON.stringify({ code: '200', data: { total: 1, page: 1, size: 20, pages: 1, candidates: [{ ...candidate(), availablePackages: '12' }], complete: true, snapshotAt: '' } })))
|
|
||||||
vi.mocked(listDispatchCandidates).mockImplementation(actual.listDispatchCandidates)
|
|
||||||
const wrapper = render()
|
|
||||||
try {
|
|
||||||
await flushPromises(); expect(wrapper.get('input').attributes('disabled')).toBeUndefined()
|
|
||||||
await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises()
|
|
||||||
expect(convertDispatchDraft).toHaveBeenCalledOnce(); expect(vi.mocked(convertDispatchDraft).mock.calls[0]![0].groups[0]!.dispatch.batchAllocations).toEqual(row().allocations)
|
|
||||||
expect(vi.mocked(lockDispatchDraftPallet).mock.calls[0]![0].source.planPalletId).toBe('9007199254740993'); expect(wrapper.emitted('updated')).toHaveLength(1)
|
|
||||||
} finally { wrapper.unmount(); get.mockRestore() }
|
|
||||||
})
|
|
||||||
it('restores existing batch dispatches after remount and navigates to the same whole dispatch without any creation', async () => {
|
|
||||||
vi.mocked(getReceivingContext).mockImplementation(async key => receiving(key, [{ dispatchNo: 'DS/EXISTING', batchKey: key, customerId: 'customer-a', tripNo: null, version: null, status: 'ACTIVE', packageCount: 12 }]))
|
|
||||||
for (let index = 0; index < 2; index++) {
|
|
||||||
const wrapper = render(); await flushPromises(); expect(wrapper.text()).toContain('DS/EXISTING')
|
|
||||||
await button(wrapper, '继续维护本车').trigger('click'); expect(wrapper.emitted('external')).toEqual([['/overseas-warehouse/dispatches/DS%2FEXISTING']]); expect(wrapper.text()).not.toContain('创建整车排车单'); wrapper.unmount()
|
|
||||||
}
|
|
||||||
expect(getBatchDispatchCandidates).not.toHaveBeenCalled(); expect(createDispatchDraft).not.toHaveBeenCalled(); expect(convertDispatchDraft).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
it('does not fall back to new creation when transport relations fail or their nested batch ownership differs', async () => {
|
|
||||||
vi.mocked(getReceivingContext).mockRejectedValueOnce(new Error('unavailable')); const failed = render(); await flushPromises(); expect(failed.text()).toContain('批次可排实物读取失败'); expect(getBatchDispatchCandidates).not.toHaveBeenCalled(); failed.unmount()
|
|
||||||
vi.mocked(getReceivingContext).mockResolvedValueOnce(receiving(batch, [{ dispatchNo: 'DS-OLD', batchKey: batch, customerId: 'customer-b', tripNo: null, version: null, status: 'ACTIVE', packageCount: 12 }]))
|
|
||||||
const mismatch = render(); await flushPromises(); expect(mismatch.text()).toContain('排车单与工作批次关联不一致'); expect(mismatch.text()).not.toContain('核对本批剩余可排实物'); expect(createDispatchDraft).not.toHaveBeenCalled(); mismatch.unmount()
|
|
||||||
})
|
|
||||||
it('reads remaining physical cargo only after an explicit choice while retaining the original dispatch', async () => {
|
|
||||||
vi.mocked(getReceivingContext).mockImplementation(async key => receiving(key, [{ dispatchNo: 'DS-OLD', batchKey: key, customerId: 'customer-a', tripNo: null, version: null, status: 'ACTIVE', packageCount: 12 }]))
|
|
||||||
const wrapper = render(); await flushPromises(); expect(getBatchDispatchCandidates).not.toHaveBeenCalled()
|
|
||||||
await button(wrapper, '核对本批剩余可排实物').trigger('click'); await flushPromises(); expect(getBatchDispatchCandidates).toHaveBeenCalledExactlyOnceWith(batch); expect(wrapper.text()).toContain('DS-OLD'); expect(convertDispatchDraft).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('uses a server-owned draft, explicit zero versions, native source hashes and exact allocations for one whole dispatch', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises()
|
|
||||||
expect(createDispatchDraft).toHaveBeenCalledWith({ warehouseId: 'origin-1', idempotencyKey: expect.any(String) })
|
|
||||||
expect(createDispatchDraftContainer).toHaveBeenCalledWith({ draftToken: 'server-owned-token', recordVersion: 0, idempotencyKey: expect.any(String), capacity: 30 })
|
|
||||||
expect(lockDispatchDraftPallet).toHaveBeenCalledWith({ draftToken: 'server-owned-token', draftContainerId: 'container-1', recordVersion: 1, idempotencyKey: expect.any(String), source: natives[0]!.selection })
|
|
||||||
const request = vi.mocked(convertDispatchDraft).mock.calls[0]![0]
|
|
||||||
expect(request).toMatchObject({ draftToken: 'server-owned-token', recordVersion: 2, groups: [{ draftContainerId: 'container-1', dispatch: { warehouseId: 'origin-1', cargo: [natives[0]!.selection], batchAllocations: row().allocations, vehicle: null, driver: null } }] })
|
|
||||||
expect(wrapper.text()).toContain('DS/001'); expect(wrapper.emitted('updated')).toHaveLength(1); expect(await guard()).toBe(true)
|
|
||||||
await button(wrapper, '继续维护本车').trigger('click'); expect(wrapper.emitted('external')).toEqual([['/overseas-warehouse/dispatches/DS%2F001']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('combines same-warehouse real customers in one container and keeps each batch source owner', async () => {
|
|
||||||
const second = row('9007199254740994', 'customer-b'); natives.push(candidate(second)); vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: batch, version: 4, candidates: [row(), second], blockReasons: [] })
|
|
||||||
const wrapper = render(); await flushPromises(); expect(wrapper.findAll('input[type=checkbox]').map(input => (input.element as HTMLInputElement).checked)).toEqual([true, true])
|
|
||||||
await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises(); const groups = vi.mocked(convertDispatchDraft).mock.calls[0]![0].groups
|
|
||||||
expect(groups).toHaveLength(1); expect(groups[0]!.dispatch.cargo).toEqual(natives.map(value => value.selection)); expect(groups[0]!.dispatch.batchAllocations.map(value => value.customerId)).toEqual(['customer-a', 'customer-b']); expect(wrapper.text()).not.toContain('共车'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('preserves exact distinct batch allocations while combining selected same-warehouse batches', async () => {
|
|
||||||
const otherKey = 'FBA_APPOINTMENT:2', second = row('9007199254740994', 'customer-b', otherKey); natives.push(candidate(second))
|
|
||||||
vi.mocked(getBatchDispatchCandidates).mockImplementation(async key => ({ batchKey: key, version: 4, candidates: [key === batch ? row() : second], blockReasons: [] }))
|
|
||||||
const wrapper = render({ batchKeys: [batch, otherKey] }); await flushPromises(); for (const input of wrapper.findAll('input[type="checkbox"]')) await input.setValue(true)
|
|
||||||
await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises(); expect(vi.mocked(convertDispatchDraft).mock.calls[0]![0].groups[0]!.dispatch.batchAllocations).toEqual([...row().allocations, ...second.allocations]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps blocked, mismatched-customer, wrong-source and unknown-quantity cargo out of the payload', async () => {
|
|
||||||
const blocked = { ...row('2'), blockReasons: ['本托已被其他排车占用'] }, wrong = row('3'), unknown = { ...row('4'), packageCount: null }, wrongSource = row('5')
|
|
||||||
wrong.allocations[0]!.customerId = 'customer-b'; wrongSource.allocations[0]!.sourceKey = 'ORDER:unrelated'; natives.push(...[blocked, wrong, unknown, wrongSource].map(value => candidate(value)))
|
|
||||||
vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: batch, version: 4, candidates: [row(), blocked, wrong, unknown, wrongSource], blockReasons: [] })
|
|
||||||
const wrapper = render(); await flushPromises(); expect(wrapper.findAll('input[type=checkbox]').map(input => (input.element as HTMLInputElement).checked)).toEqual([true, false, false, false, false])
|
|
||||||
expect(wrapper.text()).toContain('本托已被其他排车占用'); await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises(); expect(vi.mocked(convertDispatchDraft).mock.calls[0]![0].groups[0]!.dispatch.batchAllocations).toEqual(row().allocations); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('accepts partial pages but fails closed on missing versions and cross-warehouse batches', async () => {
|
|
||||||
vi.mocked(listDispatchCandidates).mockResolvedValueOnce({ total: 1, page: 1, size: 20, pages: 1, candidates: natives, complete: false, snapshotAt: '' }); const incomplete = render(); await flushPromises(); expect(incomplete.get('input[type=checkbox]').attributes('disabled')).toBeUndefined(); expect(createDispatchDraft).not.toHaveBeenCalled(); incomplete.unmount()
|
|
||||||
natives[0]!.selection.sourceVersion = ''; const missing = render(); await flushPromises(); expect(missing.text()).toContain('来源版本不完整'); missing.unmount()
|
|
||||||
vi.mocked(getReceivingContext).mockImplementation(async key => { const value = receiving(key); if (key !== batch) value.batch.originWarehouseId = 'another-warehouse'; return value })
|
|
||||||
const cross = render({ batchKeys: [batch, 'FBA_APPOINTMENT:2'] }); await flushPromises(); expect(cross.text()).toContain('相同的起运仓'); expect(convertDispatchDraft).not.toHaveBeenCalled(); cross.unmount()
|
|
||||||
})
|
|
||||||
it('retains the entire original conversion and skips all prior locks after an unknown response, even after remount with the work closed', async () => {
|
|
||||||
vi.mocked(convertDispatchDraft).mockRejectedValueOnce(new Error('lost response'))
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises(); const original = clone(vi.mocked(convertDispatchDraft).mock.calls[0]![0])
|
|
||||||
expect(await guard()).toBe(false); wrapper.unmount()
|
|
||||||
const restored = render({ canWrite: false }); await flushPromises(); expect(restored.text()).toContain('原请求已保留'); await button(restored, '核对并重试原请求').trigger('click'); await flushPromises()
|
|
||||||
expect(convertDispatchDraft).toHaveBeenNthCalledWith(2, original); expect(lockDispatchDraftPallet).toHaveBeenCalledTimes(1); expect(createDispatchDraftContainer).toHaveBeenCalledTimes(1); expect(restored.emitted('updated')).toHaveLength(1); restored.unmount()
|
|
||||||
})
|
|
||||||
it('retries the exact container command after a lost response instead of generating another container key', async () => {
|
|
||||||
vi.mocked(createDispatchDraftContainer).mockRejectedValueOnce(new Error('unknown container'))
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises(); const original = clone(vi.mocked(createDispatchDraftContainer).mock.calls[0]![0])
|
|
||||||
await button(wrapper, '核对并重试原请求').trigger('click'); await flushPromises(); expect(createDispatchDraftContainer).toHaveBeenNthCalledWith(2, original); expect(createDispatchDraft).toHaveBeenCalledTimes(1); expect(convertDispatchDraft).toHaveBeenCalledTimes(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps a proven CREATE across failed current-detail GET and only repeats the read', async () => {
|
|
||||||
vi.mocked(getDispatch).mockRejectedValueOnce(new Error('GET unavailable'))
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises(); expect(convertDispatchDraft).toHaveBeenCalledTimes(1); expect(wrapper.emitted('updated')).toBeUndefined()
|
|
||||||
await button(wrapper, '核对并重试原请求').trigger('click'); await flushPromises(); expect(convertDispatchDraft).toHaveBeenCalledTimes(1); expect(getDispatch).toHaveBeenCalledTimes(2); expect(wrapper.emitted('updated')).toHaveLength(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('never releases an unknown result for a later rejection, and releases only an explicitly rejected owned draft at its read-back version', async () => {
|
|
||||||
vi.mocked(lockDispatchDraftPallet).mockRejectedValueOnce(new Error('unknown')).mockRejectedValueOnce(new ApiResponseError('conflict', 'A0409', 409))
|
|
||||||
const unknown = render(); await flushPromises(); await button(unknown, '创建整车排车单').trigger('click'); await flushPromises(); await button(unknown, '核对并重试原请求').trigger('click'); await flushPromises(); expect(unknown.text()).not.toContain('按明确拒绝结果释放'); expect(await guard()).toBe(false); unknown.unmount()
|
|
||||||
sessionStorage.clear(); vi.mocked(lockDispatchDraftPallet).mockRejectedValueOnce(new ApiResponseError('conflict', 'A0409', 409)); draft = { ...draft, draftToken: 'another-owned-token', containers: [], recordVersion: 0 }
|
|
||||||
const rejected = render(); await flushPromises(); await button(rejected, '创建整车排车单').trigger('click'); await flushPromises(); draft.recordVersion = 9
|
|
||||||
await button(rejected, '按明确拒绝结果释放本草稿并重新核对').trigger('click'); await flushPromises(); expect(releaseDispatchDraft).toHaveBeenCalledWith({ draftToken: 'another-owned-token', recordVersion: 9, idempotencyKey: expect.any(String) }); rejected.unmount()
|
|
||||||
})
|
|
||||||
it('preserves quantity-split navigation and uses create permission rather than the removed smart-dispatch permission', async () => {
|
|
||||||
access.denied = ['platform:overseas-warehouse:inbound-order:smart-dispatch']; const wrapper = render(); await flushPromises()
|
|
||||||
await button(wrapper, '按当前批次箱数分批').trigger('click'); expect(wrapper.emitted('batch')).toEqual([[batch]]); expect(lockDispatchDraftPallet).not.toHaveBeenCalled()
|
|
||||||
await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises(); expect(convertDispatchDraft).toHaveBeenCalledTimes(1)
|
|
||||||
await button(wrapper, '为本车添加同仓货物').trigger('click'); expect(wrapper.getComponent({ name: 'WorkSharedTripForm' }).props('dispatchNo')).toBe('DS/001'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not read scoped cargo without original permissions or create while only read access remains', async () => {
|
|
||||||
access.allowed = false; const denied = render(); await flushPromises(); expect(getReceivingContext).not.toHaveBeenCalled(); denied.unmount()
|
|
||||||
access.allowed = true; access.denied = ['platform:overseas-warehouse:dispatch:create']; const readonly = render(); await flushPromises(); expect(button(readonly, '创建整车排车单').attributes('disabled')).toBeDefined(); expect(createDispatchDraft).not.toHaveBeenCalled(); readonly.unmount()
|
|
||||||
})
|
|
||||||
it('shows batch-level blockers even without rows and refuses duplicate physical candidates across batches', async () => {
|
|
||||||
vi.mocked(getBatchDispatchCandidates).mockResolvedValueOnce({ batchKey: batch, version: 4, candidates: [], blockReasons: ['原批次已替代,请进入当前批次'] })
|
|
||||||
const blocked = render(); await flushPromises(); expect(blocked.get('[role="alert"]').text()).toContain('原批次已替代'); expect(createDispatchDraft).not.toHaveBeenCalled(); blocked.unmount()
|
|
||||||
const duplicate = render({ batchKeys: [batch, 'FBA_APPOINTMENT:2'] }); await flushPromises(); expect(duplicate.findAll('input').every(input => input.attributes('disabled') !== undefined)).toBe(true); expect(duplicate.text()).toContain('同一实物'); expect(convertDispatchDraft).not.toHaveBeenCalled(); duplicate.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps original batch allocations and selected cargo while paging through associated plan candidates', async () => {
|
|
||||||
const first = row(), second = row('9007199254740994', 'customer-b')
|
|
||||||
natives = [candidate(first), candidate(second)]
|
|
||||||
vi.mocked(getBatchDispatchCandidates).mockResolvedValue({ batchKey: batch, version: 4, candidates: [first, second], blockReasons: [] })
|
|
||||||
vi.mocked(listDispatchCandidates).mockImplementation(async query => ({ total: 21, page: query.page!, size: query.size!, pages: 2, candidates: [clone(natives[query.page === 2 ? 1 : 0]!)], complete: false, snapshotAt: '' }))
|
|
||||||
const wrapper = render()
|
|
||||||
try {
|
|
||||||
await flushPromises(); expect(wrapper.findAll('input[type=checkbox]')).toHaveLength(1)
|
|
||||||
await wrapper.get('input[type=checkbox]').setValue(true)
|
|
||||||
const state = wrapper.vm as unknown as { changeCandidatePage(page: number): void }
|
|
||||||
state.changeCandidatePage(2); await flushPromises(); await wrapper.get('input[type=checkbox]').setValue(true)
|
|
||||||
expect(listDispatchCandidates).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2, size: 20, warehouseTab: 'ALL', warehouseId: 'origin-1' }))
|
|
||||||
expect(getBatchDispatchCandidates).toHaveBeenCalledTimes(1)
|
|
||||||
expect(listDispatchCandidates).toHaveBeenCalledTimes(2)
|
|
||||||
await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises()
|
|
||||||
expect(convertDispatchDraft).toHaveBeenCalledTimes(1)
|
|
||||||
expect(vi.mocked(convertDispatchDraft).mock.calls[0]![0].groups[0]!.dispatch.batchAllocations).toEqual([...first.allocations, ...second.allocations])
|
|
||||||
} finally { wrapper.unmount() }
|
|
||||||
})
|
|
||||||
it('rejects a selected batch source whose group version changed on another candidate page', async () => {
|
|
||||||
vi.mocked(listDispatchCandidates).mockImplementation(async query => {
|
|
||||||
const value = clone(natives[0]!)
|
|
||||||
if (query.page === 2) value.selectionGroup.groupVersion = 'new-group-version'
|
|
||||||
return { total: 21, page: query.page!, size: query.size!, pages: 2, candidates: [value], complete: false, snapshotAt: '' }
|
|
||||||
})
|
|
||||||
const wrapper = render()
|
|
||||||
try {
|
|
||||||
await flushPromises(); await wrapper.get('input[type=checkbox]').setValue(true)
|
|
||||||
;(wrapper.vm as unknown as { changeCandidatePage(page: number): void }).changeCandidatePage(2)
|
|
||||||
await flushPromises(); await button(wrapper, '创建整车排车单').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('选货组组成已变化')
|
|
||||||
expect(createDispatchDraft).not.toHaveBeenCalled()
|
|
||||||
} finally { wrapper.unmount() }
|
|
||||||
})
|
|
||||||
@@ -1,250 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import './appointmentNativeForms.css'
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import InlineHelp from '@/shared/components/InlineHelp.vue'
|
|
||||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
|
||||||
import { getDispatch, getBatchDispatchCandidates, listDispatchCandidates, useDispatchCandidates, createDispatchDraft, createDispatchDraftContainer, listDispatchDrafts, lockDispatchDraftPallet, convertDispatchDraft, releaseDispatchDraft, dispatchVehicleSpecs, DispatchInputError, requireVersion, requireBatchVersions, requireSelectionGroup, expandSelectionGroups, assertSelectionGroupVersions, selectionGroupBlockReason, validateCommandResult, validateCurrentDispatch, isDefiniteDispatchRejection, type BatchDispatchCandidate, type BatchDispatchCandidates, type Candidate, type DispatchDetail, type DispatchDraft, type ConvertDraft, type ConvertedDraft, type DraftSelection, type VersionCommand } from '@/modules/overseas-warehouse'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import WorkSharedTripForm from './WorkSharedTripForm.vue'
|
|
||||||
import WorkExistingDispatchForm from './WorkExistingDispatchForm.vue'
|
|
||||||
import { getReceivingContext } from './receivingApi'
|
|
||||||
import { useWorkDraft } from './useWorkDraft'
|
|
||||||
const props = defineProps<{ batchKeys: string[]; canWrite: boolean }>()
|
|
||||||
const emit = defineEmits<{ updated: []; external: [path: string]; batch: [key: string] }>()
|
|
||||||
type BatchRow = BatchDispatchCandidate & { key: string; batchKey: string; native: Candidate | null; blockReasons: string[] }
|
|
||||||
type ReadyRow = BatchRow & { native: Candidate }
|
|
||||||
type Step = { action: 'CREATE' | 'CONTAINER' | 'LOCK' | 'CONVERT' | 'RELEASE'; body: Record<string, unknown>; attempted: boolean; rejected: boolean }
|
|
||||||
type Preparation = { warehouseId: string; capacity: number; rows: ReadyRow[]; dispatchKey: string; draft: DispatchDraft | null; containerId: string | null; lockedKeys: string[]; step: Step | null; converted: ConvertedDraft | null; releasing: boolean }
|
|
||||||
const access = useAccessPreviewStore(), auth = useAuthStore(), owner = auth.user?.id || ''
|
|
||||||
const scope = JSON.stringify([...new Set(props.batchKeys)].sort()), storageKey = `appointment-dispatch:${owner}:${scope}`
|
|
||||||
const contexts = ref<BatchDispatchCandidates[]>([]), rows = ref<BatchRow[]>([]), selected = ref<string[]>([]), warehouseId = ref('')
|
|
||||||
const working = ref(false), saving = ref(false), error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null)
|
|
||||||
const candidatePage = useDispatchCandidates(error, listDispatchCandidates)
|
|
||||||
const { page: candidatePageNumber, size: candidatePageSize, total: candidateTotal } = candidatePage
|
|
||||||
const loading = computed(() => working.value || candidatePage.loading.value)
|
|
||||||
const selectedRows = ref<Record<string, BatchRow>>({})
|
|
||||||
let receivingContexts: Awaited<ReturnType<typeof getReceivingContext>>[] = []
|
|
||||||
let nativeGeneration = 0
|
|
||||||
const capacity = ref(30), result = ref<DispatchDetail | null>(null), pending = ref<Preparation | null>(null), corrupted = ref(false)
|
|
||||||
const adding = ref(false), addingBusy = ref(false), arrangingRemaining = ref(false), existingReady = ref(false)
|
|
||||||
const existing = ref<Array<{ batchKey: string; dispatchNo: string; customerId: string }>>([]), baseline = ref('[]')
|
|
||||||
const readable = computed(() => ['platform:appointment:list', 'platform:overseas-warehouse:last-mile-order:list', 'platform:overseas-warehouse:inbound-order:list', 'platform:overseas-warehouse:dispatch:list'].every(permission => access.can(permission)))
|
|
||||||
const canCreate = computed(() => readable.value && access.can('platform:overseas-warehouse:dispatch:create'))
|
|
||||||
const writable = computed(() => props.canWrite && canCreate.value && !corrupted.value && (!existing.value.length || existingReady.value))
|
|
||||||
const chosen = computed(() => selected.value.map(key => selectedRows.value[key]).filter((row): row is BatchRow => Boolean(row)))
|
|
||||||
const unresolved = computed(() => saving.value || Boolean(pending.value) || corrupted.value)
|
|
||||||
useWorkDraft(computed(() => JSON.stringify(selected.value) !== baseline.value && !result.value), unresolved)
|
|
||||||
const clone = <T,>(value: T): T => JSON.parse(JSON.stringify(value)) as T
|
|
||||||
let generation = 0
|
|
||||||
function ensureOwner() { if (!owner || auth.user?.id !== owner || JSON.stringify([...new Set(props.batchKeys)].sort()) !== scope) throw new DispatchInputError('排车登录身份或批次范围已变化,请重新进入原事项') }
|
|
||||||
function persist() { ensureOwner(); if (pending.value) sessionStorage.setItem(storageKey, JSON.stringify(pending.value)); else sessionStorage.removeItem(storageKey) }
|
|
||||||
try { const saved = owner && sessionStorage.getItem(storageKey); if (saved) pending.value = JSON.parse(saved) as Preparation }
|
|
||||||
catch { corrupted.value = true; saveError.value = { message: '原排车请求记录损坏,请保留现场核对,不能另建排车单' } }
|
|
||||||
function reasons(row: BatchRow) { return row.blockReasons }
|
|
||||||
function physicalCount(values: BatchRow[]) { return new Set(values.flatMap(row => row.native?.selectionGroup.pallets.map(pallet => pallet.warehousePalletId || pallet.palletNo || row.key) || [])).size }
|
|
||||||
function detailPath(no: string) { return `/overseas-warehouse/dispatches/${encodeURIComponent(no)}` }
|
|
||||||
async function load() {
|
|
||||||
if (!readable.value || pending.value || corrupted.value) return
|
|
||||||
const current = ++generation, batches = [...new Set(props.batchKeys)]
|
|
||||||
working.value = true; error.value = null; existingReady.value = false; rows.value = []; selected.value = []; baseline.value = '[]'; contexts.value = []; selectedRows.value = {}; candidatePage.reset(); nativeGeneration++
|
|
||||||
try {
|
|
||||||
if (!batches.length || batches.some(key => !/^FBA_APPOINTMENT:\d+$/.test(key))) throw new DispatchInputError('请从真实预约批次进入排车,不能重组其他业务批次')
|
|
||||||
const receiving = await Promise.all(batches.map(key => getReceivingContext(key)))
|
|
||||||
if (current !== generation) return
|
|
||||||
const references: typeof existing.value = []
|
|
||||||
receiving.forEach((context, index) => {
|
|
||||||
const batchKey = batches[index]!
|
|
||||||
if (context.batch.batchKey !== batchKey) throw new DispatchInputError('运输关系与当前预约批次不一致,请重新读取')
|
|
||||||
for (const vehicle of context.transport.vehicles.filter(row => row.batchKey === batchKey && row.status !== 'CANCELLED')) {
|
|
||||||
if (!vehicle.dispatchNo) throw new DispatchInputError('本批已有运输安排但缺少排车单号,请核对原记录')
|
|
||||||
references.push({ batchKey, dispatchNo: vehicle.dispatchNo, customerId: vehicle.customerId })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
existing.value = references
|
|
||||||
if (references.length && !arrangingRemaining.value) return
|
|
||||||
const origins = [...new Set(receiving.map(context => context.batch.originWarehouseId).filter(Boolean))]
|
|
||||||
if (origins.length !== 1 || receiving.some(context => !context.batch.originWarehouseId)) throw new DispatchInputError('所选批次须有明确且相同的起运仓,请从同仓批次继续')
|
|
||||||
warehouseId.value = origins[0]!
|
|
||||||
const batchCandidates = await Promise.all(batches.map(key => getBatchDispatchCandidates(key)))
|
|
||||||
if (current !== generation) return
|
|
||||||
if (batchCandidates.some((context, index) => context.batchKey !== batches[index])) throw new DispatchInputError('实物候选与当前预约批次不一致')
|
|
||||||
requireBatchVersions(batchCandidates.flatMap(context => context.candidates.flatMap(row => row.allocations)))
|
|
||||||
contexts.value = batchCandidates; receivingContexts = receiving
|
|
||||||
await loadCandidatePage(true)
|
|
||||||
} catch (cause) { if (current === generation) error.value = getApiErrorDetails(cause, cause instanceof DispatchInputError ? cause.message : '批次可排实物读取失败') }
|
|
||||||
finally { if (current === generation) working.value = false }
|
|
||||||
}
|
|
||||||
async function loadCandidatePage(autoSelect = false) {
|
|
||||||
const sequence = ++nativeGeneration, current = generation
|
|
||||||
const planIds = [...new Set(contexts.value.flatMap(context => context.candidates.map(row => row.planId)))]
|
|
||||||
if (!planIds.length) { candidatePage.reset(); rows.value = []; return }
|
|
||||||
await candidatePage.load({ warehouseId: warehouseId.value, planIds, page: candidatePageNumber.value, size: candidatePageSize.value, warehouseTab: 'ALL' })
|
|
||||||
if (sequence !== nativeGeneration || current !== generation) return
|
|
||||||
if (error.value) { rows.value = []; return }
|
|
||||||
try {
|
|
||||||
requireBatchVersions(candidatePage.candidates.value.flatMap(row => row.appointmentBatches))
|
|
||||||
rows.value = contexts.value.flatMap((context, index) => context.candidates.map(row => {
|
|
||||||
const matches = candidatePage.candidates.value.filter(value => value.selection.sourceType === 'INBOUND_PLAN' && value.selection.planPalletId === row.planPalletId && value.customerId === row.customerId)
|
|
||||||
const candidate = matches.length === 1 ? matches[0]! : null
|
|
||||||
const sources = receivingContexts[index]!.batch.items
|
|
||||||
const blocks = [...context.blockReasons, ...row.blockReasons]
|
|
||||||
if (!candidate || candidate.warehouseId !== warehouseId.value || !candidate.sourceVersion || candidate.selection.sourceVersion !== candidate.sourceVersion) blocks.push('原生实物来源、起运仓或版本待核实')
|
|
||||||
if (candidate) { const groupBlock = selectionGroupBlockReason(candidate); if (groupBlock) blocks.push(groupBlock) }
|
|
||||||
if (row.packageCount == null || row.packageCount <= 0 || candidate && candidate.availablePackages !== row.packageCount) blocks.push('批次箱数与本托真实可排量不一致,请核对分批或拆托')
|
|
||||||
if (!row.allocations.length || row.allocations.some(allocation => allocation.planPalletId !== row.planPalletId || allocation.customerId !== row.customerId || allocation.batchKey !== context.batchKey || !Number.isInteger(allocation.packageCount) || allocation.packageCount <= 0 || !sources.some(source => source.customerId === allocation.customerId && source.sourceKey === allocation.sourceKey && source.destinationKey === allocation.destinationKey && source.packageCount != null && source.packageCount >= allocation.packageCount))) blocks.push('候选不属于当前批次、客户和真实来源范围')
|
|
||||||
if (row.allocations.reduce((sum, allocation) => sum + allocation.packageCount, 0) !== row.packageCount) blocks.push('逐来源批次分配与实物箱数不一致')
|
|
||||||
return { ...row, key: `${context.batchKey}:${row.customerId}:${row.planPalletId}`, batchKey: context.batchKey, native: candidate, blockReasons: [...new Set(blocks)] }
|
|
||||||
}))
|
|
||||||
if (candidateTotal.value > candidatePageSize.value) rows.value = rows.value.filter(row => row.native)
|
|
||||||
for (const row of rows.value) if (row.native && rows.value.filter(other => other.native?.sourceKey === row.native!.sourceKey).length > 1) row.blockReasons.push('同一实物出现在多条批次候选,请先核对分配范围')
|
|
||||||
if (autoSelect && candidateTotal.value <= candidatePageSize.value) {
|
|
||||||
const eligible = rows.value.filter(row => !reasons(row).length)
|
|
||||||
selected.value = props.batchKeys.length === 1 && physicalCount(eligible) <= capacity.value ? eligible.map(row => row.key) : []
|
|
||||||
selectedRows.value = Object.fromEntries(eligible.filter(row => selected.value.includes(row.key)).map(row => [row.key, clone(row)]))
|
|
||||||
baseline.value = JSON.stringify(selected.value)
|
|
||||||
}
|
|
||||||
} catch (cause) { error.value = getApiErrorDetails(cause, cause instanceof DispatchInputError ? cause.message : '批次可排实物读取失败') }
|
|
||||||
}
|
|
||||||
function changeCandidatePage(page: number) { candidatePageNumber.value = page; void loadCandidatePage() }
|
|
||||||
function changeCandidateSize(size: number) { candidatePageSize.value = size; candidatePageNumber.value = 1; void loadCandidatePage() }
|
|
||||||
function select(row: BatchRow, event: Event) {
|
|
||||||
const input = event.target as HTMLInputElement
|
|
||||||
if (!writable.value || unresolved.value || loading.value || error.value || reasons(row).length) { input.checked = selected.value.includes(row.key); return }
|
|
||||||
if (!input.checked) selected.value = selected.value.filter(key => key !== row.key)
|
|
||||||
else if (!selected.value.includes(row.key)) {
|
|
||||||
if (physicalCount([...chosen.value, row]) > capacity.value) ElMessage.warning('已达到本组计划托位上限,请核对实际托盘')
|
|
||||||
else { selectedRows.value[row.key] = clone(row); selected.value.push(row.key) }
|
|
||||||
}
|
|
||||||
input.checked = selected.value.includes(row.key)
|
|
||||||
}
|
|
||||||
function step(action: Step['action'], body: object) { pending.value!.step = { action, body: clone(body) as Record<string, unknown>, attempted: false, rejected: false }; persist() }
|
|
||||||
function common(draft: DispatchDraft) { return { recordVersion: requireVersion(draft.recordVersion), idempotencyKey: crypto.randomUUID(), draftToken: draft.draftToken } }
|
|
||||||
async function executeStep() {
|
|
||||||
const request = pending.value!, command = request.step!, previouslyAttempted = command.attempted
|
|
||||||
command.attempted = true; persist()
|
|
||||||
try {
|
|
||||||
let value: DispatchDraft | ConvertedDraft
|
|
||||||
if (command.action === 'CREATE') value = await createDispatchDraft(command.body as unknown as { idempotencyKey: string; warehouseId: string })
|
|
||||||
else if (command.action === 'CONTAINER') value = await createDispatchDraftContainer(command.body as unknown as VersionCommand & { draftToken: string; capacity: number })
|
|
||||||
else if (command.action === 'LOCK') value = await lockDispatchDraftPallet(command.body as unknown as DraftSelection)
|
|
||||||
else if (command.action === 'RELEASE') value = await releaseDispatchDraft(command.body as unknown as VersionCommand & { draftToken: string })
|
|
||||||
else value = await convertDispatchDraft(command.body as unknown as ConvertDraft)
|
|
||||||
ensureOwner()
|
|
||||||
if (!value.draftToken || command.body.draftToken && value.draftToken !== command.body.draftToken) throw new DispatchInputError('草稿结果与原请求不一致,请保留原请求')
|
|
||||||
if (command.action === 'CONVERT') {
|
|
||||||
const converted = value as ConvertedDraft
|
|
||||||
if (converted.vehicles.length !== 1 || converted.vehicles[0]?.draftContainerId !== request.containerId) throw new DispatchInputError('整车结果与原装车容器不一致')
|
|
||||||
validateCommandResult(converted.vehicles[0]!.dispatch, { dispatchNo: '', action: 'CREATE', body: { idempotencyKey: request.dispatchKey }, attempted: true, rejected: false, result: null })
|
|
||||||
request.converted = converted
|
|
||||||
} else {
|
|
||||||
const draft = value as DispatchDraft; requireVersion(draft.recordVersion)
|
|
||||||
if (draft.warehouseId !== request.warehouseId) throw new DispatchInputError('草稿起运仓与原批次不一致')
|
|
||||||
if (command.action === 'CONTAINER') {
|
|
||||||
if (draft.containers.length !== 1) throw new DispatchInputError('本次草稿装车容器不唯一,请保留原请求核对')
|
|
||||||
request.containerId = draft.containers[0]!.draftContainerId
|
|
||||||
}
|
|
||||||
if (command.action === 'LOCK') {
|
|
||||||
const selectedSource = command.body.source as DraftSelection['source']
|
|
||||||
const expected = request.rows.find(row => row.native.selection.planPalletId === selectedSource.planPalletId && row.native.selection.sourceType === selectedSource.sourceType && row.native.sourceVersion === selectedSource.sourceVersion)
|
|
||||||
const source = expected && draft.sources.find(row => row.sourceKey === expected.native.sourceKey && row.customerId === expected.customerId)
|
|
||||||
if (!source || !draft.containers.find(row => row.draftContainerId === request.containerId)?.sourceKeys.includes(source.sourceKey)) throw new DispatchInputError('原来源未确认进入本装车组,请核对原请求')
|
|
||||||
const group = requireSelectionGroup(source)
|
|
||||||
assertSelectionGroupVersions([expected!.native], [source])
|
|
||||||
const boundKeys = draft.containers.find(row => row.draftContainerId === request.containerId)!.sourceKeys
|
|
||||||
if (group.sources.some(required => !boundKeys.includes(required.sourceKey))) throw new DispatchInputError('完整选货组尚未原子进入本装车组,请核对原请求')
|
|
||||||
request.lockedKeys.push(...group.sources.map(required => required.sourceKey))
|
|
||||||
}
|
|
||||||
request.draft = draft
|
|
||||||
}
|
|
||||||
request.step = null; persist()
|
|
||||||
} catch (cause) {
|
|
||||||
ensureOwner(); if (!previouslyAttempted && isDefiniteDispatchRejection(cause)) command.rejected = true
|
|
||||||
persist(); throw cause
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function save() {
|
|
||||||
if (saving.value || loading.value || corrupted.value || !canCreate.value) return
|
|
||||||
saveError.value = null
|
|
||||||
try {
|
|
||||||
ensureOwner()
|
|
||||||
if (!pending.value) {
|
|
||||||
if (!writable.value || error.value || result.value || !chosen.value.length || chosen.value.some(row => reasons(row).length || !row.native) || physicalCount(chosen.value) > capacity.value) throw new DispatchInputError('请核对本仓实物资格、来源批次与计划托位')
|
|
||||||
candidatePage.assertCurrent(chosen.value.map(row => row.native!))
|
|
||||||
pending.value = { warehouseId: warehouseId.value, capacity: capacity.value, rows: clone(chosen.value) as ReadyRow[], dispatchKey: crypto.randomUUID(), draft: null, containerId: null, lockedKeys: [], step: null, converted: null, releasing: false }; persist()
|
|
||||||
}
|
|
||||||
saving.value = true
|
|
||||||
const request = pending.value
|
|
||||||
while (!request.converted) {
|
|
||||||
if (!request.step) {
|
|
||||||
if (request.releasing) { step('RELEASE', common(request.draft!)) }
|
|
||||||
else if (!request.draft) step('CREATE', { idempotencyKey: crypto.randomUUID(), warehouseId: request.warehouseId })
|
|
||||||
else if (!request.containerId) step('CONTAINER', { ...common(request.draft), capacity: request.capacity })
|
|
||||||
else {
|
|
||||||
const next = request.rows.find(row => !request.lockedKeys.includes(row.native.sourceKey))
|
|
||||||
if (next) step('LOCK', { ...common(request.draft), draftContainerId: request.containerId, source: next.native.selection })
|
|
||||||
else {
|
|
||||||
const cargo = [...new Set(request.rows.map(row => row.native.sourceKey))].map(key => request.draft!.sources.find(source => source.sourceKey === key))
|
|
||||||
if (cargo.some(source => !source || source.warehouseId !== request.warehouseId || !source.sourceVersion || source.selection.sourceVersion !== source.sourceVersion || request.rows.some(row => row.native.sourceKey === source.sourceKey && row.customerId !== source.customerId))) throw new DispatchInputError('草稿真实来源尚未完整恢复,请保留原请求核对')
|
|
||||||
step('CONVERT', { ...common(request.draft), groups: [{ draftContainerId: request.containerId, dispatch: { idempotencyKey: request.dispatchKey, warehouseId: request.warehouseId, vehicle: null, driver: null, plannedDepartureAt: null, estimatedArrivalAt: null, remark: null, cargo: expandSelectionGroups(cargo as Candidate[]), batchAllocations: request.rows.flatMap(row => row.allocations) } }] } satisfies ConvertDraft)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await executeStep()
|
|
||||||
if (request.releasing) { pending.value = null; persist(); selected.value = []; await load(); return }
|
|
||||||
}
|
|
||||||
// Immutable CREATE proof is persisted before reading current facts; GET failure never reconverts.
|
|
||||||
const proof = request.converted!.vehicles[0]!.dispatch, latest = await getDispatch(proof.dispatchNo)
|
|
||||||
ensureOwner(); validateCurrentDispatch(latest, proof)
|
|
||||||
result.value = latest; pending.value = null; persist(); selected.value = []; baseline.value = '[]'
|
|
||||||
ElMessage.success(`整车排车单 ${latest.dispatchNo} 已创建`); emit('updated')
|
|
||||||
} catch (cause) { saveError.value = getApiErrorDetails(cause, cause instanceof DispatchInputError ? cause.message : '本次整车结果待确认,请核对并重试原请求') }
|
|
||||||
finally { saving.value = false }
|
|
||||||
}
|
|
||||||
async function releaseRejected() {
|
|
||||||
if (saving.value || !pending.value?.step?.rejected || pending.value.converted) return
|
|
||||||
saving.value = true; saveError.value = null
|
|
||||||
try {
|
|
||||||
ensureOwner(); const request = pending.value
|
|
||||||
if (!request.draft) { pending.value = null; persist(); return }
|
|
||||||
const owned = (await listDispatchDrafts()).find(row => row.draftToken === request.draft!.draftToken)
|
|
||||||
ensureOwner()
|
|
||||||
if (!owned || owned.warehouseId !== request.warehouseId) throw new DispatchInputError('原拥有者草稿尚未读回,请保留现场核对')
|
|
||||||
request.draft = owned; request.releasing = true; request.step = null; persist()
|
|
||||||
} catch (cause) { saveError.value = getApiErrorDetails(cause, cause instanceof DispatchInputError ? cause.message : '原草稿版本读取失败') }
|
|
||||||
finally { saving.value = false }
|
|
||||||
if (pending.value?.releasing) await save()
|
|
||||||
else if (!pending.value) await load()
|
|
||||||
}
|
|
||||||
async function remaining() { if (!unresolved.value && !addingBusy.value) { result.value = null; adding.value = false; arrangingRemaining.value = true; await load() } }
|
|
||||||
onMounted(load)
|
|
||||||
onBeforeUnmount(() => { generation++; nativeGeneration++; candidatePage.reset() })
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section class="work-form appointment-native-form" aria-label="按预约批次创建整车排车">
|
|
||||||
<h3>{{ existing.length ? '沿用本批已有排车单' : '按批次选择同仓真实货物' }} <InlineHelp title="排车说明"><p>同一张排车单可装同仓多个客户与目的仓,客户和预约归属逐来源保留。</p></InlineHelp></h3>
|
|
||||||
<p v-if="!readable">读取批次实物需要预约、尾程订单、入仓单和排车列表权限。</p>
|
|
||||||
<LoadErrorState v-if="error" title="批次可排实物读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<p v-if="loading">正在核对批次、客户、起运仓与实物来源…</p>
|
|
||||||
<template v-if="existing.length && !loading && !error && !result && !pending">
|
|
||||||
<WorkExistingDispatchForm :key="JSON.stringify(existing)" :dispatches="existing" :can-write="canWrite" @ready="existingReady = $event" @updated="emit('updated')" @external="path => emit('external', path)" />
|
|
||||||
<el-button v-if="!arrangingRemaining && writable" @click="remaining">核对本批剩余可排实物</el-button>
|
|
||||||
</template>
|
|
||||||
<template v-if="result"><p>已创建整车排车单:{{ result.dispatchNo }}</p><el-button @click="emit('external', detailPath(result.dispatchNo))">继续维护本车</el-button><el-button v-if="canWrite && access.can('platform:overseas-warehouse:dispatch:edit') && result.actions.ADD_CARGO?.allowed === true" @click="adding = true">为本车添加同仓货物</el-button><WorkSharedTripForm v-if="adding" :dispatch-no="result.dispatchNo" :can-write="canWrite" @busy="addingBusy = $event" @updated="emit('updated')" @external="path => emit('external', path)" /><el-button :disabled="addingBusy" @click="remaining">继续核对剩余实物</el-button></template>
|
|
||||||
<template v-else-if="!pending && !corrupted && readable && !loading && !error && (!existing.length || arrangingRemaining && existingReady)">
|
|
||||||
<p v-for="reason in [...new Set(contexts.flatMap(context => context.blockReasons))]" :key="reason" role="alert">{{ reason }}</p>
|
|
||||||
<el-button v-if="batchKeys.length === 1" :disabled="!writable || unresolved" @click="emit('batch', batchKeys[0]!)">按当前批次箱数分批</el-button><p>部分箱数先按本批逐来源数量分批;不对应完整实物时,先在原库存作业拆托。</p>
|
|
||||||
<label>本组计划托位<select v-model.number="capacity" :disabled="!writable || unresolved" class="workbench-input"><option v-for="spec in dispatchVehicleSpecs" :key="spec.value" :value="spec.capacity">{{ spec.label }}</option></select></label>
|
|
||||||
<table class="density-table"><thead><tr><th>选择</th><th>客户</th><th>托盘码</th><th>入库单号</th><th>来源</th><th>箱数</th><th>不可选择原因</th></tr></thead><tbody><tr v-for="(row, index) in rows" :key="`${row.key}:${index}`"><td><input type="checkbox" :checked="selected.includes(row.key)" :disabled="!writable || unresolved || reasons(row).length > 0" @change="select(row, $event)"></td><td>{{ row.native?.customerName || '客户待核实' }}</td><td>{{ row.palletNo || '—' }}</td><td>{{ row.planNo || '—' }}</td><td>{{ row.sourceStage === 'RECEIVED' ? '已收货实物' : '计划托盘' }}</td><td>{{ row.packageCount ?? '待核实' }}</td><td>{{ reasons(row).join(';') || '可选' }}</td></tr></tbody></table><p v-if="!rows.length">当前批次尚无可排实物。</p>
|
|
||||||
<el-pagination aria-label="批次关联候选分页" :current-page="candidatePageNumber" :page-size="candidatePageSize" :page-sizes="[10, 20, 50]" :total="candidateTotal" :disabled="unresolved || loading" layout="total, sizes, prev, pager, next" @update:current-page="changeCandidatePage" @update:page-size="changeCandidateSize" />
|
|
||||||
<p>上方总数为关联计划的候选数;当前页展示其中属于本批次的实物。已选 {{ chosen.length }} 条(含其他页)。</p>
|
|
||||||
<el-button type="primary" :disabled="!writable || !chosen.length" :loading="saving" @click="save">创建整车排车单</el-button>
|
|
||||||
</template>
|
|
||||||
<p v-if="pending" role="status">本次草稿与原请求已保留,请勿改变来源、版本或另建排车单。<el-button :disabled="!canCreate || saving" :loading="saving" @click="save">核对并重试原请求</el-button></p>
|
|
||||||
<LoadErrorState v-if="saveError" title="排车尚未完成" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState><el-button v-if="pending?.step?.rejected && !pending.converted" :loading="saving" @click="releaseRejected">按明确拒绝结果释放本草稿并重新核对</el-button>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkExistingDispatchForm from './WorkExistingDispatchForm.vue'
|
|
||||||
import { getDispatch, type DispatchDetail } from '@/modules/overseas-warehouse'
|
|
||||||
import { resolveBatchWork } from './workApi'
|
|
||||||
import { workDetail, workItem } from './work.test-support'
|
|
||||||
const access = vi.hoisted(() => ({ allowed: true }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => access.allowed }) }))
|
|
||||||
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getDispatch: vi.fn() }))
|
|
||||||
vi.mock('./workApi', async original => ({ ...await original<typeof import('./workApi')>(), resolveBatchWork: vi.fn() }))
|
|
||||||
function detail(no = 'DS/ORIGINAL'): DispatchDetail { return { dispatchNo: no, status: 'ACTIVE', stage: 'BEFORE_LOADING', recordVersion: 0, reviewState: 'DRAFT', reviews: { dispatchReview: { status: 'NOT_SUBMITTED', reason: null, reviewerId: null, reviewedAt: null, reviewRound: 0, basisHash: null, invalidatedReason: null }, loadingReview: { status: 'NOT_SUBMITTED', reason: null, reviewerId: null, reviewedAt: null, reviewRound: 0, basisHash: null, invalidatedReason: null } }, counts: { itemCount: 1, palletCount: 1, packageCount: 12, pickedPackageCount: 0, shippedPackageCount: 0 }, pickingReconciled: false, actions: { EDIT: { allowed: true, blockCode: null, blockReason: null }, ADD_CARGO: { allowed: true, blockCode: null, blockReason: null } }, vehicleInfo: { vehicle: null, driver: null }, dispatchInfo: { route: null, plannedDepartureAt: null, departedAt: null, estimatedArrivalAt: null, fbaAppointments: [], appointmentBatches: [] }, documents: { dispatchNo: no, outbounds: [], deliveries: [], createdAt: '', updatedAt: '', remark: null }, orderDetails: [] } }
|
|
||||||
function render(dispatches: Array<{ batchKey: string; dispatchNo: string; customerId?: string }> = [{ batchKey: 'DISPATCH:9007199254740999', dispatchNo: 'DS/ORIGINAL' }]) { return mount(WorkExistingDispatchForm, { props: { dispatches, canWrite: true }, global: { stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, LoadErrorState: { props: ['message'], template: '<p>{{ message }}</p>' }, ApiErrorMeta: true, WorkSharedTripForm: { name: 'WorkSharedTripForm', props: ['dispatchNo', 'canWrite'], template: '<div data-same-dispatch />' } } } }) }
|
|
||||||
const button = (wrapper: ReturnType<typeof render>, label: string) => wrapper.findAll('button').find(row => row.text() === label)!
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); access.allowed = true; vi.mocked(getDispatch).mockResolvedValue(detail()); vi.mocked(resolveBatchWork).mockResolvedValue({ batchKey: 'DISPATCH:9007199254740999', customerId: 'customer-a', detail: workDetail({ item: workItem({ batchKey: 'DISPATCH:9007199254740999', batchNo: 'DS/ORIGINAL' }) }), candidates: [] }) })
|
|
||||||
it.each(['customer-b', undefined])('rejects a FBA reference outside the exact batch customer: %s', async customerId => {
|
|
||||||
const value = detail(); value.dispatchInfo.appointmentBatches = [{ batchKey: 'FBA_APPOINTMENT:1', batchNo: 'AP-1', customerId: 'customer-a', recordVersion: 0, sources: [] }]; vi.mocked(getDispatch).mockResolvedValue(value)
|
|
||||||
const wrapper = render([{ batchKey: 'FBA_APPOINTMENT:1', dispatchNo: value.dispatchNo, customerId }]); await flushPromises(); expect(wrapper.text()).toContain('排车单与工作批次关联不一致'); expect(wrapper.find('table').exists()).toBe(false); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('reads a shared whole dispatch once and verifies every nested batch and real customer', async () => {
|
|
||||||
const value = detail(); value.dispatchInfo.appointmentBatches = ['a', 'b'].map((customerId, index) => ({ batchKey: `FBA_APPOINTMENT:${index + 1}`, batchNo: `AP-${index + 1}`, customerId, recordVersion: 0, sources: [] })); vi.mocked(getDispatch).mockResolvedValue(value)
|
|
||||||
const wrapper = render(value.dispatchInfo.appointmentBatches.map(row => ({ batchKey: row.batchKey, customerId: row.customerId, dispatchNo: value.dispatchNo }))); await flushPromises()
|
|
||||||
expect(getDispatch).toHaveBeenCalledTimes(1); expect(wrapper.findAll('tbody tr')).toHaveLength(1); expect(wrapper.emitted('ready')?.at(-1)).toEqual([true]); expect(resolveBatchWork).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('resolves the opaque dispatch batch in the work domain and opens the original independent detail', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); expect(resolveBatchWork).toHaveBeenCalledWith('DISPATCH:9007199254740999', undefined)
|
|
||||||
await button(wrapper, '继续维护本车').trigger('click'); expect(wrapper.emitted('external')).toEqual([['/overseas-warehouse/dispatches/DS%2FORIGINAL']])
|
|
||||||
expect(wrapper.text()).not.toContain('9007199254740999'); expect(wrapper.text()).not.toContain('安排车次'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('rejects mismatched authority or returned business identity instead of deriving an internal ID', async () => {
|
|
||||||
vi.mocked(resolveBatchWork).mockResolvedValueOnce({ batchKey: 'DISPATCH:9007199254740999', customerId: 'a', detail: workDetail({ item: workItem({ batchKey: 'DISPATCH:9007199254740999', batchNo: 'DS-OTHER' }) }), candidates: [] })
|
|
||||||
const wrapper = render(); await flushPromises(); expect(wrapper.find('table').exists()).toBe(false); expect(wrapper.text()).toContain('关联不一致'); wrapper.unmount()
|
|
||||||
vi.mocked(getDispatch).mockResolvedValueOnce(detail('WRONG')); const wrong = render(); await flushPromises(); expect(wrong.find('table').exists()).toBe(false); wrong.unmount()
|
|
||||||
})
|
|
||||||
it('opens same-dispatch adding only under the server gate, and keeps already scanned cargo out of the old merge flow', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '为本车添加同仓货物').trigger('click')
|
|
||||||
expect(wrapper.getComponent({ name: 'WorkSharedTripForm' }).props()).toMatchObject({ dispatchNo: 'DS/ORIGINAL', canWrite: true }); wrapper.unmount()
|
|
||||||
const value = detail(); value.stage = 'LOADING'; value.counts.pickedPackageCount = 1; value.actions.ADD_CARGO!.allowed = false; vi.mocked(getDispatch).mockResolvedValueOnce(value)
|
|
||||||
const scanned = render(); await flushPromises(); expect(scanned.text()).not.toContain('为本车添加同仓货物'); expect(scanned.text()).not.toContain('共车'); scanned.unmount()
|
|
||||||
})
|
|
||||||
it('does not read dispatch or batch authority without the actual list permissions', async () => {
|
|
||||||
access.allowed = false; const wrapper = render(); await flushPromises(); expect(getDispatch).not.toHaveBeenCalled(); expect(resolveBatchWork).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import InlineHelp from '@/shared/components/InlineHelp.vue'
|
|
||||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { getDispatch, stageLabel, type DispatchDetail } from '@/modules/overseas-warehouse'
|
|
||||||
import { ApiResponseError, getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import WorkSharedTripForm from './WorkSharedTripForm.vue'
|
|
||||||
import { resolveBatchWork } from './workApi'
|
|
||||||
const props = defineProps<{ dispatches: Array<{ batchKey: string; dispatchNo: string; customerId?: string }>; canWrite: boolean }>()
|
|
||||||
const emit = defineEmits<{ updated: []; external: [path: string]; ready: [valid: boolean] }>()
|
|
||||||
const access = useAccessPreviewStore(), rows = ref<DispatchDetail[]>([]), loading = ref(false), error = ref<ApiErrorDetails | null>(null)
|
|
||||||
const addingNo = ref(''), addingBusy = ref(false)
|
|
||||||
const readable = computed(() => access.can('platform:overseas-warehouse:dispatch:list') && (!props.dispatches.some(row => row.batchKey.startsWith('DISPATCH:')) || access.can('platform:appointment:list')))
|
|
||||||
function path(no: string) { return `/overseas-warehouse/dispatches/${encodeURIComponent(no)}` }
|
|
||||||
function canEdit(row: DispatchDetail) { return props.canWrite && readable.value && access.can('platform:overseas-warehouse:dispatch:edit') && row.status === 'ACTIVE' && row.actions.EDIT?.allowed === true }
|
|
||||||
function canAdd(row: DispatchDetail) { return props.canWrite && readable.value && access.can('platform:overseas-warehouse:dispatch:edit') && row.status === 'ACTIVE' && row.stage === 'BEFORE_LOADING' && row.actions.ADD_CARGO?.allowed === true }
|
|
||||||
let generation = 0
|
|
||||||
async function load() {
|
|
||||||
const current = ++generation; emit('ready', false); rows.value = []; error.value = null
|
|
||||||
if (!readable.value) return
|
|
||||||
loading.value = true
|
|
||||||
try {
|
|
||||||
const references = props.dispatches.map(row => ({ ...row }))
|
|
||||||
const details = await Promise.all([...new Set(references.map(row => row.dispatchNo))].map(async no => {
|
|
||||||
const row = await getDispatch(no)
|
|
||||||
if (row.dispatchNo !== no || row.status === 'CANCELLED') throw new ApiResponseError('排车单与工作批次关联不一致,请刷新核对', 'WORK_DISPATCH_MISMATCH')
|
|
||||||
for (const reference of references.filter(value => value.dispatchNo === no)) {
|
|
||||||
let matches = false
|
|
||||||
if (/^FBA_APPOINTMENT:\d+$/.test(reference.batchKey)) {
|
|
||||||
matches = Boolean(reference.customerId && row.dispatchInfo.appointmentBatches.some(batch => batch.batchKey === reference.batchKey && batch.customerId === reference.customerId))
|
|
||||||
} else if (/^DISPATCH:\d+$/.test(reference.batchKey)) {
|
|
||||||
// The work domain resolves its opaque batch identity; Detail has no internal dispatch ID.
|
|
||||||
const resolution = await resolveBatchWork(reference.batchKey, reference.customerId)
|
|
||||||
matches = resolution.batchKey === reference.batchKey && (resolution.detail
|
|
||||||
? resolution.detail.item.batchKey === reference.batchKey && resolution.detail.item.batchNo === no && (!reference.customerId || resolution.customerId === reference.customerId)
|
|
||||||
: resolution.candidates.length > 0 && resolution.candidates.every(candidate => candidate.batchNo === no) && (!reference.customerId || resolution.candidates.some(candidate => candidate.customerId === reference.customerId)))
|
|
||||||
}
|
|
||||||
if (!matches) throw new ApiResponseError('排车单与工作批次关联不一致,请刷新核对', 'WORK_DISPATCH_MISMATCH')
|
|
||||||
}
|
|
||||||
return row
|
|
||||||
}))
|
|
||||||
if (current !== generation) return
|
|
||||||
rows.value = details; emit('ready', details.length > 0)
|
|
||||||
} catch (cause) { if (current === generation) error.value = getApiErrorDetails(cause, '原排车单读取失败') }
|
|
||||||
finally { if (current === generation) loading.value = false }
|
|
||||||
}
|
|
||||||
function add(row: DispatchDetail) { if (canAdd(row) && !loading.value && !error.value && !addingBusy.value) addingNo.value = row.dispatchNo }
|
|
||||||
function updated() { emit('updated'); void load() }
|
|
||||||
watch(() => props.dispatches, load, { immediate: true, deep: true })
|
|
||||||
onBeforeUnmount(() => { generation++ })
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section aria-label="沿用原整车排车"><h3>沿用原整车排车 <InlineHelp title="排车说明"><p>在原排车单维护车辆、司机和货物;一张排车单就是一趟车。</p></InlineHelp></h3>
|
|
||||||
<p v-if="!readable">查看原排车单及批次关联需要相应列表权限。</p><p v-if="loading">正在核对原排车单与批次…</p>
|
|
||||||
<LoadErrorState v-if="error" title="原排车单读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<table v-if="!loading && !error && readable" class="density-table"><thead><tr><th>操作</th><th>排车单号</th><th>车牌号</th><th>箱数</th><th>阶段</th></tr></thead><tbody><tr v-for="row in rows" :key="row.dispatchNo"><td><el-button v-if="canEdit(row)" :disabled="addingBusy" @click="emit('external', path(row.dispatchNo))">继续维护本车</el-button><el-button v-if="canAdd(row)" :disabled="addingBusy" @click="add(row)">为本车添加同仓货物</el-button><el-button @click="emit('external', path(row.dispatchNo))">查看原排车单</el-button></td><td>{{ row.dispatchNo }}</td><td>{{ row.vehicleInfo.vehicle?.plate || '—' }}</td><td>{{ row.counts.packageCount }}</td><td>{{ stageLabel(row.stage) }}</td></tr></tbody></table>
|
|
||||||
<WorkSharedTripForm v-if="addingNo" :key="addingNo" :dispatch-no="addingNo" :can-write="canWrite" @busy="addingBusy = $event" @updated="updated" @external="value => emit('external', value)" />
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkReceiptPlans from './WorkReceiptPlans.vue'
|
|
||||||
import { getContainerPlanProgress, getContainerInboundPlanPreview, convertLastMileContainerToInboundPlans, type ContainerInboundPlanPreviewDto } from '@/modules/overseas-warehouse'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
const state = vi.hoisted(() => ({ canRead: true }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => state.canRead }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn(), success: vi.fn() }, ElMessageBox: { confirm: vi.fn() } }))
|
|
||||||
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getContainerPlanProgress: vi.fn(), getContainerInboundPlanPreview: vi.fn(), convertLastMileContainerToInboundPlans: vi.fn() }))
|
|
||||||
let guard: LeaveGuard
|
|
||||||
function render() { return mount(WorkReceiptPlans, { props: { containerBookingId: '9007199254740993', canWrite: true }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, LoadErrorState: true, ApiErrorMeta: true } } }) }
|
|
||||||
function button(wrapper: ReturnType<typeof render>, text: string) { return wrapper.findAll('button').find(button => button.text() === text)! }
|
|
||||||
function preview(overrides: Partial<ContainerInboundPlanPreviewDto> = {}) { return { sourceContainerBookingId: '9007199254740993', containerNo: 'TEST-CN', overseasWarehouseName: '接仓仓库', snapshotVersion: 4, snapshotHash: 'snapshot-4', pendingOrderCount: 1, blockedOrderCount: 0, sourcePalletCount: 2, supplementPalletCount: 1, totalPlannedPalletCount: 0, ready: true, groups: [], ...overrides } as ContainerInboundPlanPreviewDto }
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); state.canRead = true; vi.mocked(getContainerPlanProgress).mockResolvedValue({ summary: { containerNo: 'TEST-CN', overseasWarehouseName: '接仓仓库' }, orders: [{ orderId: 'internal-1', customerId: '9007199254740999', planId: 'internal-plan', planNo: 'IP-001', planValid: true, inboundCode: 'IN-001' }, { orderId: 'internal-2', customerId: 'customer-b', planId: null, planNo: null, planValid: false, inboundCode: 'IN-002' }] } as never) })
|
|
||||||
it('opens a real plan in the exact customer scope while leaving missing plans unavailable', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(getContainerPlanProgress).toHaveBeenCalledExactlyOnceWith('9007199254740993')
|
|
||||||
const plans = wrapper.findAll('button').filter(item => item.text() === '查看原接仓记录')
|
|
||||||
await plans[0]!.trigger('click')
|
|
||||||
expect(wrapper.emitted('external')).toEqual([['/overseas-warehouse/inbound-orders/IP-001?customerId=9007199254740999']])
|
|
||||||
expect(plans[1]!.attributes('disabled')).toBeDefined()
|
|
||||||
expect(wrapper.text()).not.toContain('internal-plan'); expect(wrapper.text()).not.toContain('9007199254740999'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not read the container source without its original permission', async () => {
|
|
||||||
state.canRead = false; const wrapper = render(); await flushPromises(); expect(getContainerPlanProgress).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('submits the actual preview snapshot and replays the same request after an unknown result', async () => {
|
|
||||||
vi.mocked(getContainerInboundPlanPreview).mockResolvedValue(preview())
|
|
||||||
vi.mocked(convertLastMileContainerToInboundPlans).mockRejectedValueOnce(new Error('lost response')).mockResolvedValueOnce([])
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '核对本柜入库计划预览').trigger('click'); await flushPromises()
|
|
||||||
await button(wrapper, '确认生成本柜计划').trigger('click'); await flushPromises()
|
|
||||||
const original = vi.mocked(convertLastMileContainerToInboundPlans).mock.calls[0]!
|
|
||||||
expect(original).toEqual([{ sourceContainerBookingId: '9007199254740993', snapshotVersion: 4, snapshotHash: 'snapshot-4' }, expect.any(String)])
|
|
||||||
expect(await guard()).toBe(false)
|
|
||||||
await button(wrapper, '重试本次计划生成').trigger('click'); await flushPromises()
|
|
||||||
expect(vi.mocked(convertLastMileContainerToInboundPlans).mock.calls[1]).toEqual(original)
|
|
||||||
expect(wrapper.emitted('updated')).toHaveLength(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('uses the original resource recovery snapshot and key instead of creating new plans', async () => {
|
|
||||||
vi.mocked(getContainerInboundPlanPreview).mockResolvedValue(preview({ pendingOrderCount: 0, resourceRetry: { idempotencyKey: 'original-key', snapshotVersion: 2, snapshotHash: 'original-snapshot' } }))
|
|
||||||
vi.mocked(convertLastMileContainerToInboundPlans).mockResolvedValue([])
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '核对本柜入库计划预览').trigger('click'); await flushPromises()
|
|
||||||
await button(wrapper, '重试原资源确认').trigger('click'); await flushPromises()
|
|
||||||
expect(convertLastMileContainerToInboundPlans).toHaveBeenCalledWith({ sourceContainerBookingId: '9007199254740993', snapshotVersion: 2, snapshotHash: 'original-snapshot' }, 'original-key'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not submit a blocked preview', async () => {
|
|
||||||
vi.mocked(getContainerInboundPlanPreview).mockResolvedValue(preview({ ready: false, blockedOrderCount: 1 }))
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '核对本柜入库计划预览').trigger('click'); await flushPromises()
|
|
||||||
expect(button(wrapper, '确认生成本柜计划').attributes('disabled')).toBeDefined(); expect(convertLastMileContainerToInboundPlans).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import InlineHelp from '@/shared/components/InlineHelp.vue'
|
|
||||||
import { computed, onMounted, ref } from 'vue'
|
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { getContainerPlanProgress, getContainerInboundPlanPreview, convertLastMileContainerToInboundPlans, type ContainerPlanProgressDetailDto, type ContainerInboundPlanPreviewDto, type ConvertContainerInboundPlanPayload } from '@/modules/overseas-warehouse'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
|
|
||||||
const props = defineProps<{ containerBookingId: string; canWrite: boolean }>()
|
|
||||||
const emit = defineEmits<{ external: [path: string]; updated: [] }>()
|
|
||||||
const access = useAccessPreviewStore(), detail = ref<ContainerPlanProgressDetailDto | null>(null), loading = ref(false), error = ref<ApiErrorDetails | null>(null)
|
|
||||||
const readable = computed(() => access.can('platform:overseas-warehouse:last-mile-order:list'))
|
|
||||||
const writable = computed(() => props.canWrite && readable.value && access.can('platform:overseas-warehouse:inbound-order:create'))
|
|
||||||
const preview = ref<ContainerInboundPlanPreviewDto | null>(null), previewLoading = ref(false), saving = ref(false), previewError = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null)
|
|
||||||
const pending = ref<{ body: ConvertContainerInboundPlanPayload; key: string } | null>(null)
|
|
||||||
useWorkDraft(computed(() => false), computed(() => saving.value || !!pending.value))
|
|
||||||
async function loadPreview() {
|
|
||||||
if (!writable.value || saving.value || pending.value) return
|
|
||||||
previewLoading.value = true; previewError.value = null
|
|
||||||
try { preview.value = await getContainerInboundPlanPreview(props.containerBookingId) }
|
|
||||||
catch (cause) { previewError.value = getApiErrorDetails(cause, '本柜入库计划预览失败') }
|
|
||||||
finally { previewLoading.value = false }
|
|
||||||
}
|
|
||||||
async function createPlans() {
|
|
||||||
if (!writable.value || saving.value || previewLoading.value || previewError.value || !preview.value) return
|
|
||||||
if (!pending.value) {
|
|
||||||
if (!preview.value.ready || (!preview.value.resourceRetry && preview.value.pendingOrderCount <= 0)) return
|
|
||||||
const snapshot = preview.value.resourceRetry || preview.value
|
|
||||||
pending.value = { body: { sourceContainerBookingId: props.containerBookingId, snapshotVersion: snapshot.snapshotVersion, snapshotHash: snapshot.snapshotHash }, key: preview.value.resourceRetry?.idempotencyKey || crypto.randomUUID() }
|
|
||||||
}
|
|
||||||
saving.value = true; saveError.value = null
|
|
||||||
try {
|
|
||||||
await convertLastMileContainerToInboundPlans(pending.value.body, pending.value.key)
|
|
||||||
pending.value = null; preview.value = null; ElMessage.success('本柜入库计划已确认,请查看原接仓记录'); emit('updated'); await load()
|
|
||||||
} catch (cause) {
|
|
||||||
saveError.value = getApiErrorDetails(cause, '入库计划生成结果待确认,请重试原请求')
|
|
||||||
if (rejectedCommand(cause)) { pending.value = null; preview.value = null }
|
|
||||||
} finally { saving.value = false }
|
|
||||||
}
|
|
||||||
async function load() { if (!readable.value) return; loading.value = true; error.value = null; try { detail.value = await getContainerPlanProgress(props.containerBookingId) } catch (cause) { error.value = getApiErrorDetails(cause, '本柜入仓计划读取失败') } finally { loading.value = false } }
|
|
||||||
onMounted(load)
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section aria-label="本柜接仓计划"><h3>选择本柜入仓计划<InlineHelp title="接仓计划说明"><p>实际收货与卸柜由仓库原作业流程登记;此处进入对应客户的原入库单查看。</p></InlineHelp></h3><p v-if="!readable">读取本柜计划需要尾程订单列表权限。</p>
|
|
||||||
<LoadErrorState v-if="error" title="本柜入仓计划读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<template v-if="detail && !error"><p>{{ detail.summary.containerNo || '柜号待核实' }} · {{ detail.summary.overseasWarehouseName || '接仓仓库待核实' }}</p><p v-if="detail.summary.blockingReason">{{ detail.summary.blockingReason }}</p><table class="density-table"><thead><tr><th>操作</th><th>入库单号</th><th>入仓码 / 订单号</th></tr></thead><tbody><tr v-for="row in detail.orders" :key="`${row.customerId}:${row.orderId}`"><td><el-button :disabled="saving || !!pending || !row.planNo || !row.customerId || !row.planValid || !access.can('platform:overseas-warehouse:inbound-order:list')" @click="emit('external', `/overseas-warehouse/inbound-orders/${encodeURIComponent(row.planNo!)}?customerId=${encodeURIComponent(row.customerId)}`)">查看原接仓记录</el-button></td><td>{{ row.planNo || '尚未生成有效计划' }}</td><td>{{ row.inboundCode || row.orderNo || '—' }}</td></tr></tbody></table><p v-if="!detail.orders.length">本柜尚无可读取的入仓来源。</p></template>
|
|
||||||
<el-button v-if="writable && !preview && !pending" :loading="previewLoading" @click="loadPreview">核对本柜入库计划预览</el-button>
|
|
||||||
<LoadErrorState v-if="previewError" title="入库计划预览失败" :message="previewError.message" :loading="previewLoading" @retry="loadPreview"><template #details><ApiErrorMeta :details="previewError" /></template></LoadErrorState>
|
|
||||||
<div v-if="preview && !previewError"><h4>核对本柜计划与托盘</h4><p>{{ preview.containerNo || '柜号待核实' }} · {{ preview.overseasWarehouseName || '接仓仓库待核实' }} · {{ preview.pendingOrderCount }} 票待生成 · {{ preview.blockedOrderCount }} 票待处理</p><p>头程已有 {{ preview.sourcePalletCount }} 托;海外补充 {{ preview.supplementPalletCount }} 托;已保存计划 {{ preview.totalPlannedPalletCount }} 托。</p><table class="density-table"><thead><tr><th>客户</th><th>原票</th><th>目的地</th><th>箱数</th><th>目标托数</th><th>计划状态</th></tr></thead><tbody><tr v-for="row in preview.groups.flatMap(group => group.orders)" :key="`${row.customerId}:${row.orderId}`"><td>{{ row.customerName || '客户名称待核实' }}</td><td>{{ row.inboundCode || row.businessOrderNo || '—' }}</td><td>{{ row.destinationWarehouseName || row.fbaWarehouseCode || (row.destinationType === 'PRIVATE_ADDRESS' ? '客户地址' : '目的地待核实') }}</td><td>{{ row.packageCount }}</td><td>{{ row.targetPalletCount }}</td><td>{{ row.existingPlanNo || ({ READY: '可生成', RESOURCE_PENDING: '资源待确认', PLANNED: '已有计划', BLOCKED: '来源条件未就绪' }[row.readiness]) }}</td></tr></tbody></table><p v-if="!preview.ready">本柜尚不具备生成条件,请在原尾程订单核对阻塞来源。</p><el-button type="primary" :loading="saving" :disabled="!writable || (!pending && (!preview.ready || (!preview.resourceRetry && preview.pendingOrderCount <= 0)))" @click="createPlans">{{ pending ? '重试本次计划生成' : preview.resourceRetry ? '重试原资源确认' : '确认生成本柜计划' }}</el-button></div>
|
|
||||||
<LoadErrorState v-if="saveError" title="入库计划尚未确认" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -1,512 +0,0 @@
|
|||||||
import { DatePickerStub, TimePickerStub } from './temporal-picker.test-support'
|
|
||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import { ElMessageBox } from 'element-plus'
|
|
||||||
import { createAppointmentForm, appointmentPayload } from '@/modules/overseas-warehouse'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
import WorkReceivingPanel from './WorkReceivingPanel.vue'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
import * as api from './receivingApi'
|
|
||||||
import { getCargoVerification, saveCargoVerification, type CargoVerificationContext } from './cargoVerificationApi'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
const access = vi.hoisted(() => ({ denied: [] as string[] }))
|
|
||||||
vi.mock('@/core/auth/auth', () => ({ useAuthStore: () => ({ user: { id: 'owner-current', name: '当前本人' } }) }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: (permission: string) => !access.denied.includes(permission) }) }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn() }, ElMessageBox: { confirm: vi.fn().mockResolvedValue(true) } }))
|
|
||||||
vi.mock('./cargoVerificationApi', () => ({ getCargoVerification: vi.fn(), saveCargoVerification: vi.fn() }))
|
|
||||||
vi.mock('./receivingApi', async original => ({ ...await original<typeof import('./receivingApi')>(), getReceivingContext: vi.fn(), getReceivingGroup: vi.fn(), proposeReceivingChange: vi.fn(), resolveReceivingChange: vi.fn(), bookReceiving: vi.fn(), changeReceivingGroup: vi.fn(), refreshReceivingCargo: vi.fn(), saveReceivingPlan: vi.fn(), getReceivingExecutionScope: vi.fn() }))
|
|
||||||
let guard: LeaveGuard
|
|
||||||
const detail = () => appointmentPayload({ ...createAppointmentForm(), appointmentStatus: 'SUCCESS', confirmationNo: 'EXT-OLD', appointmentAt: '2026-10-20T10:00:00' })
|
|
||||||
function context(): api.ReceivingContext {
|
|
||||||
const batch = batchContext().appointment
|
|
||||||
batch.items = batch.items.map(item => ({ ...item, sourceVersion: 'source-v3', cargoVerificationVersion: 2 }))
|
|
||||||
return { batch, executionScope: { version: 'execution-v1', members: batch.items.map(item => ({ member: { batchKey: batch.batchKey!, customerId: item.customerId }, completed: false, canRebook: true, reason: null })) }, agreements: [], pendingChanges: [], plans: [], allowedActions: ['PROPOSE_CUSTOMER_CHANGE', 'BOOK_RECEIVING', 'PLAN_RECEIVING', 'REFRESH_CARGO'], blockReasons: [], transport: { version: 'transport-v1', vehicles: [], blockReasons: [] } }
|
|
||||||
}
|
|
||||||
function members(): api.ReceivingMember[] { const c = context(); return c.batch.items.map(item => ({ batchKey: c.batch.batchKey!, appointmentNo: c.batch.appointmentNo, batchVersion: c.batch.version, customerId: item.customerId, customerName: null, sources: [{ sourceKey: item.sourceKey, inboundCode: item.inboundCode || null, destinationKey: item.destinationKey!, packageCount: item.packageCount!, sourceVersion: item.sourceVersion!, verificationVersion: item.cargoVerificationVersion! }] })) }
|
|
||||||
function agreement(status = 'ACTIVE'): api.ReceivingAgreement { return { agreementKey: 'GROUP-1', version: 4, status, destinationKey: 'FBA:ONT8', details: detail(), timezone: 'America/Los_Angeles', members: members(), warehouseEvidence: '原仓库确认' } }
|
|
||||||
function pendingChange(): api.ReceivingPending { return { changeKey: 'CHANGE-1', version: 1, status: 'WAITING', intent: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-a', quantities: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', retainedPackages: 0, expectedSourceVersion: 'source-v3', expectedVerificationVersion: 2 }], laterDate: null, ownerId: 'owner-related', nextFollowupDate: '2026-10-21', reason: '本客户后送', transportVersion: 'transport-v1' }, originalMembers: [members()[0]!], originalAgreements: [agreement()], followup: { ownerId: 'owner-related', ownerName: '已核实负责人', nextFollowupDate: '2026-10-21' } } }
|
|
||||||
function result(status = 'APPLIED'): api.ReceivingResult { return { changeKey: null, status, batches: [context().batch], agreements: [], steps: [{ step: 'BOOK_RECEIVING', status: 'SUCCESS', targetKey: 'GROUP-1', message: '已保存真实预约' }], nextActions: ['REVIEW_TRANSPORT'] } }
|
|
||||||
function render() { return mount(WorkReceivingPanel, { props: { batchKey: 'FBA_APPOINTMENT:1', canWrite: true, owners: [{ id: 'owner-related', name: '关联负责人' }] }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: {
|
|
||||||
ElDatePicker: DatePickerStub, ElTimePicker: TimePickerStub,
|
|
||||||
ElButton: { props: ['disabled', 'nativeType'], template: '<button :disabled="disabled" :type="nativeType || \'button\'"><slot /></button>' },
|
|
||||||
FbaAppointmentFields: { name: 'FbaAppointmentFields', props: ['model', 'disabled'], template: '<div data-booking-fields />' },
|
|
||||||
LoadErrorState: { props: ['message', 'showRetry'], template: '<section role="alert">{{ message }}<button v-if="showRetry !== false" @click="$emit(\'retry\')">重试读取</button></section>' }, ApiErrorMeta: true,
|
|
||||||
} } }) }
|
|
||||||
function button(wrapper: ReturnType<typeof render>, label: string) { return wrapper.findAll('button').find(row => row.text() === label)! }
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); access.denied = []; vi.mocked(api.getReceivingExecutionScope).mockImplementation(async members => ({ version: 'execution-v1', members: members.map(member => ({ member, completed: false, canRebook: true, reason: null })) })); vi.mocked(api.getReceivingContext).mockResolvedValue(context()); vi.mocked(api.proposeReceivingChange).mockResolvedValue(result('WAITING')); vi.mocked(api.resolveReceivingChange).mockResolvedValue(result()); vi.mocked(api.bookReceiving).mockResolvedValue(result()); vi.mocked(api.refreshReceivingCargo).mockResolvedValue({ ...result(), steps: [], nextActions: [] }); vi.mocked(api.saveReceivingPlan).mockResolvedValue({ ...result(), steps: [], nextActions: [] }); vi.mocked(api.changeReceivingGroup).mockResolvedValue(result()); vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: agreement(), eligibleMembers: members(), excludedMembers: [], transport: context().transport, executionScope: context().executionScope }) })
|
|
||||||
async function prepareAdjustment(wrapper: ReturnType<typeof render>, quantity = 0) {
|
|
||||||
await flushPromises(); await button(wrapper, '调整本客户先送 / 后送').trigger('click'); await flushPromises()
|
|
||||||
await wrapper.get('[aria-label="本次先送箱数"]').setValue(quantity)
|
|
||||||
await wrapper.get('[aria-label="调整负责人"]').setValue('owner-related')
|
|
||||||
await wrapper.get('[aria-label="调整原因"]').setValue('本客户后送')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
}
|
|
||||||
it('allows zero retained quantity for one customer and only persists a waiting change with all original versions', async () => {
|
|
||||||
const wrapper = render(); await prepareAdjustment(wrapper)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.proposeReceivingChange).toHaveBeenCalledWith(expect.objectContaining({ intent: expect.objectContaining({ batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-a', ownerId: 'owner-related', laterDate: null, transportVersion: 'transport-v1', quantities: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', retainedPackages: 0, expectedSourceVersion: 'source-v3', expectedVerificationVersion: 2 }] }) }))
|
|
||||||
expect(wrapper.text()).toContain('原安排尚未改变'); expect(api.resolveReceivingChange).not.toHaveBeenCalled(); expect(api.bookReceiving).not.toHaveBeenCalled()
|
|
||||||
expect(wrapper.emitted('updated')).toHaveLength(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('rejects unchanged, fractional or excessive retained quantities without creating empty later batches', async () => {
|
|
||||||
const wrapper = render(); await prepareAdjustment(wrapper, 70)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises(); expect(wrapper.text()).toContain('本次先送量未改变')
|
|
||||||
for (const quantity of [71, -1, 0.5]) { await wrapper.get('[aria-label="本次先送箱数"]').setValue(quantity); await wrapper.get('form').trigger('submit'); await flushPromises() }
|
|
||||||
expect(api.proposeReceivingChange).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('locks unknown outcomes and retries the identical change command without applying or recreating cargo', async () => {
|
|
||||||
vi.mocked(api.proposeReceivingChange).mockRejectedValueOnce(new Error('network timeout'))
|
|
||||||
const wrapper = render(); await prepareAdjustment(wrapper, 30); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const first = vi.mocked(api.proposeReceivingChange).mock.calls[0]![0]
|
|
||||||
expect(await guard()).toBe(false); expect(wrapper.get('fieldset').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.proposeReceivingChange).toHaveBeenNthCalledWith(2, first); expect(api.resolveReceivingChange).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('resumes persisted waiting input, requires warehouse evidence and sends the current change and transport versions', async () => {
|
|
||||||
const c = context(); c.pendingChanges = [pendingChange()]; c.transport.version = 'transport-v2'; c.allowedActions = []
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '继续本次变化').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('本次先送 0 箱'); expect(wrapper.text()).toContain('EXT-OLD')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.resolveReceivingChange).not.toHaveBeenCalled()
|
|
||||||
await wrapper.get('[aria-label="仓库回复依据"]').setValue('仓库同意该客户全部后送,其他客户确认保留')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.resolveReceivingChange).toHaveBeenCalledWith('CHANGE-1', expect.objectContaining({ decision: 'CONFIRM', version: 1, transportVersion: 'transport-v2' }))
|
|
||||||
expect(api.proposeReceivingChange).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('withdraws only the persisted change without claiming a cancellation or requiring confirmation evidence', async () => {
|
|
||||||
const c = context(); c.pendingChanges = [pendingChange()]; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
vi.mocked(api.resolveReceivingChange).mockResolvedValue(result('WITHDRAWN'))
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '继续本次变化').trigger('click'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await button(wrapper, '撤回变化并保留原安排').trigger('click'); await flushPromises()
|
|
||||||
expect(api.resolveReceivingChange).toHaveBeenCalledWith('CHANGE-1', expect.objectContaining({ decision: 'WITHDRAW', warehouseEvidence: null }))
|
|
||||||
expect(wrapper.text()).toContain('已撤回变化,原安排保留'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('rebooks only eligible cancelled-group members and submits one shared booking with a new command identity', async () => {
|
|
||||||
const c = context(); c.agreements = [agreement('CANCELLED')]; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: c.agreements[0]!, eligibleMembers: [members()[0]!], excludedMembers: [{ member: members()[1]!, reason: '已另行预约', currentAgreementKey: 'GROUP-OTHER' }], transport: c.transport, executionScope: c.executionScope })
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('已另行预约'); expect(wrapper.text()).not.toContain('GROUP-OTHER')
|
|
||||||
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'EXT-NEW', appointmentAt: '2026-10-23T11:00:00' })
|
|
||||||
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仓库确认当前剩余客户货量'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const request = vi.mocked(api.bookReceiving).mock.calls[0]![0]
|
|
||||||
expect(request.cancelledAgreementKey).toBe('GROUP-1'); expect(request.cancelledAgreementVersion).toBe(4)
|
|
||||||
expect(request.bookings).toHaveLength(1); expect(request.bookings[0]!.members).toEqual([{ batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-a' }])
|
|
||||||
expect(request.bookings[0]!.details.confirmationNo).toBe('EXT-NEW'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('preserves per-customer booking input on an old-number conflict and requires renewed scope confirmation', async () => {
|
|
||||||
vi.mocked(api.bookReceiving).mockRejectedValueOnce(new ApiResponseError('当前目的仓约号已使用', 'A0409', 409))
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
|
|
||||||
const model = wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model')
|
|
||||||
Object.assign(model, { confirmationNo: 'EXT-IN-USE', appointmentAt: '2026-10-23T11:00:00' })
|
|
||||||
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('明确覆盖'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(model.confirmationNo).toBe('EXT-IN-USE'); expect(wrapper.text()).toContain('当前目的仓约号已使用')
|
|
||||||
expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined(); expect(wrapper.emitted('updated')).toBeUndefined()
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('requires explicit whole-scope cancellation confirmation and uses the group version and delete permission', async () => {
|
|
||||||
const c = context(); c.agreements = [agreement()]; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
access.denied = ['platform:overseas-warehouse:inbound-order:fba-appointment']
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '核对整份取消范围').trigger('click'); await flushPromises()
|
|
||||||
await wrapper.get('[aria-label="整份回复依据"]').setValue('仓库确认整份取消'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(ElMessageBox.confirm).toHaveBeenCalled()
|
|
||||||
expect(api.changeReceivingGroup).toHaveBeenCalledWith('GROUP-1', expect.objectContaining({ action: 'CANCEL', version: 4, details: null, transportVersion: 'transport-v1' })); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps a successful result when refresh fails and retries only reads', async () => {
|
|
||||||
const wrapper = render(); await prepareAdjustment(wrapper)
|
|
||||||
vi.mocked(api.getReceivingContext).mockRejectedValueOnce(new Error('读取暂不可用'))
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('原安排尚未改变'); expect(wrapper.find('form').exists()).toBe(false)
|
|
||||||
await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises()
|
|
||||||
expect(api.proposeReceivingChange).toHaveBeenCalledTimes(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not expose internal customer IDs or replace unknown cargo with zero or permit read-only writes', async () => {
|
|
||||||
const c = context(); c.batch.items[0]!.packageCount = null; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).not.toContain('customer-a'); expect(wrapper.text()).toContain('箱数待核实')
|
|
||||||
await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('货物数量或来源资料待核实'); expect(wrapper.find('[data-booking-fields]').exists()).toBe(false)
|
|
||||||
expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.setProps({ canWrite: false }); await wrapper.get('form').trigger('submit'); expect(api.bookReceiving).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('sends independent confirmations as distinct bookings while preserving original batch identities', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
|
|
||||||
await wrapper.findAll('label').find(label => label.text().includes('所选客户分别登记预约'))!.get('input').setValue(true)
|
|
||||||
await flushPromises()
|
|
||||||
wrapper.findAllComponents({ name: 'FbaAppointmentFields' }).forEach((fields, index) => Object.assign(fields.props('model'), { confirmationNo: `EXT-${index}`, appointmentAt: `2026-10-${22 + index}T10:00:00` }))
|
|
||||||
for (const textarea of wrapper.findAll('[aria-label="预约覆盖依据"]')) await textarea.setValue('本客户仓库明确确认')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const request = vi.mocked(api.bookReceiving).mock.calls[0]![0]
|
|
||||||
expect(request.bookings.map(row => row.members)).toEqual(members().map(({ batchKey, batchVersion, customerId }) => [{ batchKey, batchVersion, customerId }]))
|
|
||||||
expect(request.bookings.map(row => row.details.confirmationNo)).toEqual(['EXT-0', 'EXT-1'])
|
|
||||||
expect(request.cancelledAgreementKey).toBeNull(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not apply existing booking inputs to different members after a range conflict', async () => {
|
|
||||||
const original = context(); original.agreements = [agreement('CANCELLED')]
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(original)
|
|
||||||
vi.mocked(api.getReceivingGroup).mockResolvedValueOnce({ agreement: original.agreements[0]!, eligibleMembers: members(), excludedMembers: [], transport: original.transport, executionScope: original.executionScope }).mockResolvedValue({ agreement: original.agreements[0]!, eligibleMembers: [members()[1]!], excludedMembers: [{ member: members()[0]!, reason: '已另行预约', currentAgreementKey: 'OTHER' }], transport: original.transport, executionScope: original.executionScope })
|
|
||||||
vi.mocked(api.bookReceiving).mockRejectedValueOnce(new ApiResponseError('范围版本变化', 'A0409', 409))
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
|
|
||||||
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'OLD-DRAFT', appointmentAt: '2026-10-22T10:00:00' })
|
|
||||||
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('原范围依据'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('原输入不会自动套用给其他客户')
|
|
||||||
expect(wrapper.find('[data-booking-fields]').exists()).toBe(false)
|
|
||||||
expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined()
|
|
||||||
expect(api.bookReceiving).toHaveBeenCalledTimes(1); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('treats unchanged whole-group rescheduling as unchanged rather than a new successful mutation', async () => {
|
|
||||||
const c = context(); c.agreements = [agreement()]; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
vi.mocked(api.changeReceivingGroup).mockResolvedValue({ ...result('UNCHANGED'), steps: [] })
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '核对整份改期范围').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model').confirmationNo).toBe('EXT-OLD')
|
|
||||||
await wrapper.get('[aria-label="整份回复依据"]').setValue('核对无变化'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.changeReceivingGroup).toHaveBeenCalledWith('GROUP-1', expect.objectContaining({ action: 'RESCHEDULE', details: detail() }))
|
|
||||||
expect(wrapper.text()).toContain('安排没有变化'); expect(wrapper.text()).not.toContain('已保存真实预约'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('uses only the eligible B/D cross-batch transport scope after A booked separately', async () => {
|
|
||||||
const a = { ...members()[0]!, batchKey: 'FBA_APPOINTMENT:10', appointmentNo: 'AP-A' }
|
|
||||||
const b = { ...members()[1]!, batchKey: 'FBA_APPOINTMENT:20', appointmentNo: 'AP-B' }
|
|
||||||
const d = { ...members()[1]!, batchKey: 'FBA_APPOINTMENT:30', appointmentNo: 'AP-D', customerId: 'customer-d' }
|
|
||||||
const cancelled = { ...agreement('CANCELLED'), members: [a, b, d] }
|
|
||||||
const c = context(); c.agreements = [cancelled]; c.transport.version = 'old-A-B-D'
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: cancelled, eligibleMembers: [b, d], excludedMembers: [{ member: a, reason: '已另行预约', currentAgreementKey: 'OTHER-A' }], transport: { version: 'current-B-D', vehicles: [], blockReasons: ['无关客户已完成运输'] }, executionScope: { version: 'execution-B-D', members: [b, d].map(member => ({ member, completed: false, canRebook: true, reason: null })) } })
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
|
|
||||||
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'NEW-B-D', appointmentAt: '2026-10-22T10:00:00' })
|
|
||||||
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅覆盖B/D'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const request = vi.mocked(api.bookReceiving).mock.calls[0]![0]
|
|
||||||
expect(api.getReceivingExecutionScope).toHaveBeenCalledWith([{ batchKey: b.batchKey, customerId: b.customerId }, { batchKey: d.batchKey, customerId: d.customerId }]); expect(request.executionVersion).toBe('execution-v1'); expect(request).not.toHaveProperty('transportVersion')
|
|
||||||
expect(request.bookings[0]!.members.map(member => member.batchKey)).toEqual(['FBA_APPOINTMENT:20', 'FBA_APPOINTMENT:30'])
|
|
||||||
expect(request.bookings[0]!.members.some(member => member.customerId === a.customerId)).toBe(false); wrapper.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('uses verified owner candidates and renders authoritative pending followup names instead of account IDs', async () => {
|
|
||||||
const c = context(); c.pendingChanges = [pendingChange()]
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('负责人 已核实负责人'); expect(wrapper.text()).not.toContain('owner-related')
|
|
||||||
await button(wrapper, '调整本客户先送 / 后送').trigger('click'); await flushPromises()
|
|
||||||
const owner = wrapper.get('[aria-label="调整负责人"]')
|
|
||||||
expect(owner.element.tagName).toBe('SELECT')
|
|
||||||
expect(owner.findAll('option').map(option => option.text())).toEqual(['请选择负责人', '关联负责人', '当前本人'])
|
|
||||||
await wrapper.get('[aria-label="本次先送箱数"]').setValue(0)
|
|
||||||
await owner.setValue('not-an-account'); await wrapper.get('[aria-label="调整原因"]').setValue('后送')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.proposeReceivingChange).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('请选择有效负责人')
|
|
||||||
await owner.setValue('owner-current'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.proposeReceivingChange).toHaveBeenCalledWith(expect.objectContaining({ intent: expect.objectContaining({ ownerId: 'owner-current' }) }))
|
|
||||||
expect(vi.mocked(api.proposeReceivingChange).mock.calls[0]![0].intent).not.toHaveProperty('owner')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('books unfinished B using execution eligibility even when completed A blocks the shared transport and lacks cargo details', async () => {
|
|
||||||
const c = context()
|
|
||||||
c.executionScope.members[0] = { member: c.executionScope.members[0]!.member, completed: true, canRebook: false, reason: '本客户已完成,不再重约' }
|
|
||||||
c.batch.items[0]!.packageCount = null
|
|
||||||
c.transport.blockReasons = ['已完成客户禁止调整车辆']
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('本客户已完成,不再重约'); expect(wrapper.text()).not.toContain('货物数量或来源资料待核实')
|
|
||||||
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'ONLY-B', appointmentAt: '2026-10-23T11:00:00' })
|
|
||||||
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅当前未完成客户'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const command = vi.mocked(api.bookReceiving).mock.calls[0]![0]
|
|
||||||
expect(command.executionVersion).toBe('execution-v1'); expect(command).not.toHaveProperty('transportVersion')
|
|
||||||
expect(command.bookings[0]!.members.map(member => member.customerId)).toEqual(['customer-b'])
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('does not offer members missing execution eligibility or marked completed even if canRebook is true', async () => {
|
|
||||||
const c = context(); c.executionScope.members = [{ ...c.executionScope.members[0]!, completed: true, canRebook: true }]
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.find('[data-booking-fields]').exists()).toBe(false)
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.bookReceiving).not.toHaveBeenCalled(); expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined()
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
function mixedPlans(): api.ReceivingContext {
|
|
||||||
const c = context()
|
|
||||||
c.batch.plannedDate = '2026-10-20'; c.batch.confirmationNo = 'A-CONFIRMED'; c.batch.appointmentStatus = 'SUCCESS'
|
|
||||||
c.agreements = [{ ...agreement(), members: [members()[0]!] }]
|
|
||||||
c.batch.items.push({ ...c.batch.items[1]!, id: 'item-d', customerId: 'customer-d', sourceKey: 'ORDER:D', inboundCode: 'IN-D' })
|
|
||||||
c.executionScope.members.push({ member: { batchKey: c.batch.batchKey!, customerId: 'customer-d' }, completed: false, canRebook: true, reason: null })
|
|
||||||
c.plans = [{ batchKey: c.batch.batchKey!, customerId: 'customer-b', timezone: 'America/Los_Angeles', details: appointmentPayload({ ...createAppointmentForm(), plannedDate: '2026-10-24', appointmentRemark: '等待仓库' }) }]
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
async function enterBPlan(wrapper: ReturnType<typeof render>) {
|
|
||||||
await flushPromises()
|
|
||||||
const buttons = wrapper.findAll('button').filter(row => row.text() === '保存目标 / 未约成')
|
|
||||||
expect(buttons[0]!.attributes('disabled')).toBeDefined()
|
|
||||||
await buttons[1]!.trigger('click'); await flushPromises()
|
|
||||||
}
|
|
||||||
it('saves only B pending plan in the same stable batch where A is independently confirmed and D is still unbooked', async () => {
|
|
||||||
const c = mixedPlans(); vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await enterBPlan(wrapper)
|
|
||||||
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('2026-10-24')
|
|
||||||
expect(wrapper.findAll('[aria-label="客户计划状态"] option').map(row => row.attributes('value'))).toEqual(['PENDING', 'FAILED'])
|
|
||||||
await wrapper.get('[aria-label="客户计划日期"]').setValue('2026-10-26'); await wrapper.get('[aria-label="客户计划备注"]').setValue('乙等待回复')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ member: { batchKey: c.batch.batchKey, batchVersion: 3, customerId: 'customer-b' }, executionVersion: 'execution-v1', details: expect.objectContaining({ appointmentStatus: 'PENDING', plannedDate: '2026-10-26', appointmentRemark: '乙等待回复', confirmationNo: null, appointmentAt: null, appointmentEndAt: null }) }))
|
|
||||||
expect(api.bookReceiving).not.toHaveBeenCalled(); expect(api.proposeReceivingChange).not.toHaveBeenCalled(); expect(api.changeReceivingGroup).not.toHaveBeenCalled()
|
|
||||||
expect(c.agreements[0]!.details.confirmationNo).toBe('EXT-OLD'); expect(wrapper.emitted('updated')).toHaveLength(1)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('requires a failed-plan reason and allows an explicitly cleared date without inheriting A or the old header date', async () => {
|
|
||||||
const c = mixedPlans(); c.plans[0]!.details.plannedDate = null; vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await enterBPlan(wrapper)
|
|
||||||
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('')
|
|
||||||
await wrapper.get('[aria-label="客户计划状态"]').setValue('FAILED'); await wrapper.get('[aria-label="客户计划备注"]').setValue('')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('请填写未约成的原因')
|
|
||||||
await wrapper.get('[aria-label="客户计划备注"]').setValue('仓库暂未提供时段'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ details: expect.objectContaining({ plannedDate: null, plannedAt: null, plannedEndAt: null, appointmentStatus: 'FAILED', appointmentRemark: '仓库暂未提供时段', confirmationNo: null, appointmentAt: null, appointmentEndAt: null }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps customer plan drafts after a version conflict and resubmits explicitly with current batch and execution versions', async () => {
|
|
||||||
const c = mixedPlans(); vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
vi.mocked(api.saveReceivingPlan).mockRejectedValueOnce(new ApiResponseError('批次版本变化', 'A0409', 409))
|
|
||||||
const wrapper = render(); await enterBPlan(wrapper)
|
|
||||||
await wrapper.get('[aria-label="客户计划日期"]').setValue('2026-10-28'); await wrapper.get('[aria-label="客户计划备注"]').setValue('保留乙的输入')
|
|
||||||
const fresh = structuredClone(c); fresh.batch.version = 4; fresh.executionScope.version = 'execution-v2'; fresh.plans[0]!.details.plannedDate = '2026-10-25'
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(fresh)
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const first = vi.mocked(api.saveReceivingPlan).mock.calls[0]![0]
|
|
||||||
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('2026-10-28')
|
|
||||||
expect(button(wrapper, '保存本客户计划').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const second = vi.mocked(api.saveReceivingPlan).mock.calls[1]![0]
|
|
||||||
expect(second.details).toEqual(first.details); expect(second.member.batchVersion).toBe(4); expect(second.executionVersion).toBe('execution-v2'); expect(second.idempotencyKey).not.toBe(first.idempotencyKey)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('retries the identical unknown customer plan and shows unchanged without creating a confirmation', async () => {
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
|
|
||||||
vi.mocked(api.saveReceivingPlan).mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce({ ...result('UNCHANGED'), steps: [], nextActions: [] })
|
|
||||||
const wrapper = render(); await enterBPlan(wrapper)
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const first = vi.mocked(api.saveReceivingPlan).mock.calls[0]![0]
|
|
||||||
expect(await guard()).toBe(false); expect(wrapper.get('fieldset').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).toHaveBeenNthCalledWith(2, first); expect(wrapper.text()).toContain('安排没有变化'); expect(api.bookReceiving).not.toHaveBeenCalled()
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('blocks plans for confirmed, waiting-change, completed and unauthorized customers', async () => {
|
|
||||||
const c = mixedPlans(); c.pendingChanges = [{ ...pendingChange(), intent: { ...pendingChange().intent, customerId: 'customer-b' } }]
|
|
||||||
c.executionScope.members.find(row => row.member.customerId === 'customer-d')!.completed = true
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.findAll('button').filter(row => row.text() === '保存目标 / 未约成').every(row => row.attributes('disabled') !== undefined)).toBe(true)
|
|
||||||
wrapper.unmount()
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
|
|
||||||
const readonly = render(); await enterBPlan(readonly); await readonly.setProps({ canWrite: false })
|
|
||||||
await readonly.get('[aria-label="确认当前范围"]').setValue(true); await readonly.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).not.toHaveBeenCalled(); readonly.unmount()
|
|
||||||
})
|
|
||||||
it('starts D plan empty without copying confirmed A or another customer plan and clears an existing B date explicitly', async () => {
|
|
||||||
const c = mixedPlans(); vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
await wrapper.findAll('button').filter(row => row.text() === '保存目标 / 未约成')[2]!.trigger('click'); await flushPromises()
|
|
||||||
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('')
|
|
||||||
await button(wrapper, '返回范围概览').trigger('click'); await flushPromises(); await enterBPlan(wrapper)
|
|
||||||
await wrapper.get('[aria-label="客户计划日期"]').setValue('')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ member: expect.objectContaining({ customerId: 'customer-b' }), details: expect.objectContaining({ plannedDate: null }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('preserves cross-day planned windows and explicit DST offsets in the customer plan without confirmation fields', async () => {
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
|
|
||||||
const wrapper = render(); await enterBPlan(wrapper)
|
|
||||||
await wrapper.get('[aria-label="客户计划日期"]').setValue('2026-10-31')
|
|
||||||
await wrapper.get('[aria-label="客户计划开始"]').setValue('2026-10-31T23:30:00')
|
|
||||||
await wrapper.get('[aria-label="客户计划结束"]').setValue('2026-11-01T01:30:00')
|
|
||||||
await wrapper.get('[aria-label="客户计划开始时差"]').setValue('-07:00')
|
|
||||||
await wrapper.get('[aria-label="客户计划结束时差"]').setValue('-08:00')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ details: expect.objectContaining({ plannedDate: '2026-10-31', plannedAt: expect.stringContaining('2026-10-31T23:30'), plannedEndAt: expect.stringContaining('2026-11-01T01:30'), startOffset: '-07:00', endOffset: '-08:00', appointmentAt: null, appointmentEndAt: null }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('blocks dated plans without authoritative timezone but permits undated failure notes without a browser timezone', async () => {
|
|
||||||
const c = mixedPlans(); c.plans[0]!.timezone = null
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await enterBPlan(wrapper)
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('目的仓时区待核实,请先补齐')
|
|
||||||
await wrapper.get('[aria-label="客户计划日期"]').setValue(''); await wrapper.get('[aria-label="客户计划状态"]').setValue('FAILED')
|
|
||||||
await wrapper.get('[aria-label="客户计划备注"]').setValue('待核实仓库地点')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).toHaveBeenCalledWith(expect.objectContaining({ details: expect.objectContaining({ plannedDate: null, appointmentStatus: 'FAILED', startOffset: null, endOffset: null }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('preserves a DST-rejected plan for correction and never copies it into a formal booking', async () => {
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
|
|
||||||
vi.mocked(api.saveReceivingPlan).mockRejectedValueOnce(new ApiResponseError('当地时刻存在歧义,请明确时差', 'A0400', 400))
|
|
||||||
const wrapper = render(); await enterBPlan(wrapper)
|
|
||||||
await wrapper.get('[aria-label="客户计划日期"]').setValue('2026-11-01'); await wrapper.get('[aria-label="客户计划开始"]').setValue('2026-11-01T01:30:00')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('当地时刻存在歧义')
|
|
||||||
expect((wrapper.get('[aria-label="客户计划开始"]').element as HTMLInputElement).value).toContain('2026-11-01T01:30')
|
|
||||||
expect(button(wrapper, '保存本客户计划').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('[aria-label="客户计划开始时差"]').setValue('-08:00'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).toHaveBeenCalledTimes(2); expect(api.bookReceiving).not.toHaveBeenCalled()
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('inherits unconfirmed legacy header plans only without active independent coverage and strips stale confirmation fields', async () => {
|
|
||||||
for (const status of ['PENDING', 'FAILED'] as const) {
|
|
||||||
const c = context(); Object.assign(c.batch, { timezone: 'America/Los_Angeles', plannedDate: '2026-10-27', plannedAt: '2026-10-27T10:00:00', appointmentStatus: status, appointmentRemark: '原联系原因', confirmationNo: 'STALE', appointmentAt: '2026-10-20T09:00:00' })
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '保存目标 / 未约成').trigger('click'); await flushPromises()
|
|
||||||
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('2026-10-27')
|
|
||||||
expect((wrapper.get('[aria-label="客户计划备注"]').element as HTMLTextAreaElement).value).toBe('原联系原因')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.saveReceivingPlan).toHaveBeenLastCalledWith(expect.objectContaining({ details: expect.objectContaining({ appointmentStatus: status, plannedDate: '2026-10-27', confirmationNo: null, appointmentAt: null, appointmentEndAt: null, startOffset: null, endOffset: null }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
it('never inherits cancelled targets and keeps an explicit empty customer plan ahead of a pending header', async () => {
|
|
||||||
for (const ownPlan of [false, true]) {
|
|
||||||
const c = context(); Object.assign(c.batch, { appointmentStatus: ownPlan ? 'PENDING' : 'CANCELLED', plannedDate: '2026-10-27', appointmentRemark: '旧批原因' })
|
|
||||||
if (ownPlan) c.plans = [{ batchKey: c.batch.batchKey!, customerId: 'customer-a', timezone: c.batch.timezone || null, details: appointmentPayload(createAppointmentForm()) }]
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '保存目标 / 未约成').trigger('click'); await flushPromises()
|
|
||||||
expect((wrapper.get('[aria-label="客户计划日期"]').element as HTMLInputElement).value).toBe('')
|
|
||||||
expect((wrapper.get('[aria-label="客户计划备注"]').element as HTMLTextAreaElement).value).toBe('')
|
|
||||||
wrapper.unmount()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
it('selects only A for independent rebooking from a cancelled group sharing one stable batch with B and D', async () => {
|
|
||||||
const c = mixedPlans(); c.agreements = [{ ...agreement('CANCELLED'), members: [...members(), { ...members()[1]!, customerId: 'customer-d', customerName: '丁' }] }]
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: c.agreements[0]!, eligibleMembers: c.agreements[0]!.members, excludedMembers: [], transport: c.transport, executionScope: c.executionScope })
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
|
|
||||||
await wrapper.get('[aria-label="选择预约客户 2"]').setValue(false); await wrapper.get('[aria-label="选择预约客户 3"]').setValue(false)
|
|
||||||
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'A-ONLY', appointmentAt: '2026-10-24T10:00:00' })
|
|
||||||
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅甲取得确认'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const request = vi.mocked(api.bookReceiving).mock.calls[0]![0]
|
|
||||||
expect(request.bookings).toHaveLength(1); expect(request.bookings[0]!.members).toEqual([{ batchKey: c.batch.batchKey!, batchVersion: 3, customerId: 'customer-a' }])
|
|
||||||
expect(request.executionVersion).toBe(c.executionScope.version); expect(request.cancelledAgreementKey).toBe('GROUP-1')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('keeps independent booking fields matched to the selected customer and blocks an empty selection', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
|
|
||||||
await wrapper.findAll('label').find(label => label.text().includes('所选客户分别登记预约'))!.get('input').setValue(true)
|
|
||||||
wrapper.findAllComponents({ name: 'FbaAppointmentFields' }).forEach((fields, index) => Object.assign(fields.props('model'), { confirmationNo: `FOR-${index}`, appointmentAt: '2026-10-24T10:00:00' }))
|
|
||||||
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(false)
|
|
||||||
expect(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model').confirmationNo).toBe('FOR-1')
|
|
||||||
await wrapper.get('[aria-label="选择预约客户 2"]').setValue(false)
|
|
||||||
expect(wrapper.get('[aria-label="确认当前范围"]').attributes('disabled')).toBeDefined(); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.bookReceiving).not.toHaveBeenCalled()
|
|
||||||
await wrapper.get('[aria-label="选择预约客户 2"]').setValue(true); await flushPromises(); await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅乙确认')
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(vi.mocked(api.bookReceiving).mock.calls[0]![0].bookings[0]).toEqual(expect.objectContaining({ members: [expect.objectContaining({ customerId: 'customer-b' })], details: expect.objectContaining({ confirmationNo: 'FOR-1' }) }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('reads an exact cross-batch subset execution token without changing the visible batch or cancelled-group versions', async () => {
|
|
||||||
const c = context(); const a = members()[0]!, b = { ...members()[1]!, batchKey: 'FBA_APPOINTMENT:2', batchVersion: 7, appointmentNo: 'AP-B' }
|
|
||||||
c.agreements = [{ ...agreement('CANCELLED'), members: [a, b] }]
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
vi.mocked(api.getReceivingGroup).mockResolvedValue({ agreement: c.agreements[0]!, eligibleMembers: [a, b], excludedMembers: [], transport: c.transport, executionScope: { ...c.executionScope, version: 'whole-A-B' } })
|
|
||||||
vi.mocked(api.getReceivingExecutionScope).mockImplementation(async selected => ({ version: selected.length === 1 ? 'only-B-current' : 'whole-A-B-current', members: selected.map(member => ({ member, completed: false, canRebook: true, reason: null })) }))
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '重新预约这组货物').trigger('click'); await flushPromises()
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(false); await flushPromises()
|
|
||||||
expect((wrapper.get('[aria-label="确认当前范围"]').element as HTMLInputElement).checked).toBe(false)
|
|
||||||
expect(api.getReceivingExecutionScope).toHaveBeenLastCalledWith([{ batchKey: b.batchKey, customerId: b.customerId }])
|
|
||||||
Object.assign(wrapper.getComponent({ name: 'FbaAppointmentFields' }).props('model'), { confirmationNo: 'B-ONLY', appointmentAt: '2026-10-24T10:00:00' })
|
|
||||||
await wrapper.get('[aria-label="预约覆盖依据"]').setValue('仅乙当前批确认'); await wrapper.get('[aria-label="确认当前范围"]').setValue(true)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.bookReceiving).toHaveBeenCalledWith(expect.objectContaining({ executionVersion: 'only-B-current', cancelledAgreementVersion: 4, bookings: [expect.objectContaining({ members: [{ batchKey: b.batchKey, batchVersion: 7, customerId: b.customerId }] })] }))
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('blocks submission after a selected execution-scope read failure and retries only that read', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
|
|
||||||
vi.mocked(api.getReceivingExecutionScope).mockRejectedValueOnce(new Error('执行资格暂不可用'))
|
|
||||||
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(false); await flushPromises()
|
|
||||||
expect(wrapper.get('[aria-label="确认当前范围"]').attributes('disabled')).toBeDefined(); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.bookReceiving).not.toHaveBeenCalled(); expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined()
|
|
||||||
await button(wrapper, '重试读取').trigger('click'); await flushPromises()
|
|
||||||
expect(api.getReceivingExecutionScope).toHaveBeenLastCalledWith([{ batchKey: 'FBA_APPOINTMENT:1', customerId: 'customer-b' }])
|
|
||||||
expect((wrapper.get('[aria-label="确认当前范围"]').element as HTMLInputElement).checked).toBe(false)
|
|
||||||
expect(api.bookReceiving).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('shows authoritative subset blockers and ignores a late response for a previous selection', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '登记当前未覆盖货物的正式预约').trigger('click'); await flushPromises()
|
|
||||||
let resolveOld!: (scope: api.ReceivingExecutionScope) => void
|
|
||||||
vi.mocked(api.getReceivingExecutionScope).mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve }))
|
|
||||||
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(false)
|
|
||||||
vi.mocked(api.getReceivingExecutionScope).mockImplementationOnce(async selected => ({ version: 'new-blocked', members: selected.map(member => ({ member, completed: true, canRebook: false, reason: '本客户已执行,不能重约' })) }))
|
|
||||||
await wrapper.get('[aria-label="选择预约客户 1"]').setValue(true); await flushPromises()
|
|
||||||
resolveOld({ version: 'stale-allowed', members: [{ member: { batchKey: 'FBA_APPOINTMENT:1', customerId: 'customer-b' }, completed: false, canRebook: true, reason: null }] }); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('本客户已执行,不能重约')
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.bookReceiving).not.toHaveBeenCalled(); expect(button(wrapper, '保存本次正式预约').attributes('disabled')).toBeDefined(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
|
|
||||||
function verifiedCargo(): CargoVerificationContext {
|
|
||||||
return { source: { sourceKey: 'BOOKING:2', customerId: 'customer-b', orderId: null, inboundCode: 'IN-B', bookingNo: null, containerNo: null, originWarehouseId: 'origin-1', originWarehouseName: '本仓', destinationKey: 'FBA:ONT8', destinationWarehouseCode: 'ONT8', packages: 40, sourceVersion: 'source-latest', canFollowup: true, blockReasons: [] }, verification: { version: 2, sourceVersion: 'source-latest', destinationKey: 'FBA:ONT8', sourcePackages: 40, packageCount: 40, shipmentReferences: ['FBA-NEW-B'], remark: null, operatorName: '核实人员', verifiedAt: '2026-10-16T10:00:00Z' }, allocatedPackages: 30, unknownAllocationCount: 0, effectivePackages: 40, availablePackages: 10, sourceChanged: false, allowedActions: ['VERIFY_CARGO'], blockReasons: [] }
|
|
||||||
}
|
|
||||||
async function enterRefresh(wrapper: ReturnType<typeof render>) {
|
|
||||||
await flushPromises(); await wrapper.findAll('button').filter(row => row.text() === '核对并采用本客户最新货物资料')[1]!.trigger('click'); await flushPromises()
|
|
||||||
}
|
|
||||||
it('explicitly adopts only B latest source and verification snapshots beside independently confirmed A without changing quantities or saving verification', async () => {
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans()); vi.mocked(getCargoVerification).mockResolvedValue(verifiedCargo())
|
|
||||||
const wrapper = render(); await enterRefresh(wrapper)
|
|
||||||
expect(getCargoVerification).toHaveBeenCalledExactlyOnceWith({ sourceKey: 'BOOKING:2', customerId: 'customer-b', destinationKey: 'FBA:ONT8' })
|
|
||||||
expect(wrapper.text()).toContain('本批 30 箱'); expect(wrapper.text()).toContain('最新核实 40 箱'); expect(wrapper.text()).toContain('FBA-NEW-B')
|
|
||||||
expect(api.refreshReceivingCargo).not.toHaveBeenCalled()
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.refreshReceivingCargo).toHaveBeenCalledWith(expect.objectContaining({ member: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-b' }, executionVersion: 'execution-v1', sources: [{ sourceKey: 'BOOKING:2', destinationKey: 'FBA:ONT8', expectedSourceVersion: 'source-latest', expectedVerificationVersion: 2 }] }))
|
|
||||||
expect(saveCargoVerification).not.toHaveBeenCalled(); expect(api.proposeReceivingChange).not.toHaveBeenCalled(); expect(api.bookReceiving).not.toHaveBeenCalled()
|
|
||||||
await button(wrapper, '继续本客户目标 / 未约成').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.find('[aria-label="客户计划日期"]').exists()).toBe(true)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('fails closed for unknown, changed, overallocated, mismatched or unavailable latest cargo', async () => {
|
|
||||||
const cases: Array<Partial<CargoVerificationContext>> = [
|
|
||||||
{ sourceChanged: true }, { effectivePackages: null, availablePackages: null }, { unknownAllocationCount: 1 }, { allocatedPackages: 41 },
|
|
||||||
{ source: { ...verifiedCargo().source, customerId: 'customer-other' } }, { source: { ...verifiedCargo().source, destinationKey: 'FBA:OTHER' } },
|
|
||||||
{ source: { ...verifiedCargo().source, sourceVersion: null } }, { verification: { ...verifiedCargo().verification!, sourceVersion: 'stale' } }, { blockReasons: ['来源暂不可用'] },
|
|
||||||
]
|
|
||||||
for (const change of cases) {
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans()); vi.mocked(getCargoVerification).mockResolvedValue({ ...verifiedCargo(), ...change })
|
|
||||||
const wrapper = render(); await enterRefresh(wrapper)
|
|
||||||
expect(button(wrapper, '确认采用本客户最新资料').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises(); expect(api.refreshReceivingCargo).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
}
|
|
||||||
vi.mocked(getCargoVerification).mockRejectedValueOnce(new Error('核实来源读取失败'))
|
|
||||||
const wrapper = render(); await enterRefresh(wrapper)
|
|
||||||
expect(button(wrapper, '确认采用本客户最新资料').attributes('disabled')).toBeDefined(); expect(wrapper.text()).toContain('最新货物核实资料读取失败'); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('refreshes rejected adoption versions for explicit reconfirmation and retries unknown adoption with the identical key', async () => {
|
|
||||||
const c = mixedPlans(); vi.mocked(api.getReceivingContext).mockResolvedValue(c); vi.mocked(getCargoVerification).mockResolvedValue(verifiedCargo())
|
|
||||||
vi.mocked(api.refreshReceivingCargo).mockRejectedValueOnce(new ApiResponseError('资料版本变化', 'A0409', 409)).mockRejectedValueOnce(new Error('timeout'))
|
|
||||||
const wrapper = render(); await enterRefresh(wrapper)
|
|
||||||
const fresh = structuredClone(c); fresh.batch.version = 4; fresh.executionScope.version = 'exec-new'
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(fresh); vi.mocked(getCargoVerification).mockResolvedValue({ ...verifiedCargo(), verification: { ...verifiedCargo().verification!, version: 3 } })
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(button(wrapper, '确认采用本客户最新资料').attributes('disabled')).toBeDefined()
|
|
||||||
await wrapper.get('[aria-label="确认当前范围"]').setValue(true); await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
const second = vi.mocked(api.refreshReceivingCargo).mock.calls[1]![0]
|
|
||||||
expect(second.member.batchVersion).toBe(4); expect(second.sources[0]!.expectedVerificationVersion).toBe(3); expect(second.executionVersion).toBe('exec-new'); expect(await guard()).toBe(false)
|
|
||||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
|
||||||
expect(api.refreshReceivingCargo).toHaveBeenNthCalledWith(3, second); expect(saveCargoVerification).not.toHaveBeenCalled(); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('requires original source read permissions and blocks adoption for confirmed or waiting-change customers', async () => {
|
|
||||||
const c = mixedPlans(); c.pendingChanges = [{ ...pendingChange(), intent: { ...pendingChange().intent, customerId: 'customer-b' } }]
|
|
||||||
vi.mocked(api.getReceivingContext).mockResolvedValue(c)
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const buttons = wrapper.findAll('button').filter(row => row.text() === '核对并采用本客户最新货物资料')
|
|
||||||
expect(buttons[0]!.attributes('disabled')).toBeDefined(); expect(buttons[1]!.attributes('disabled')).toBeDefined(); wrapper.unmount()
|
|
||||||
access.denied = ['platform:overseas-warehouse:last-mile-order:list']; vi.mocked(api.getReceivingContext).mockResolvedValue(mixedPlans())
|
|
||||||
const denied = render(); await enterRefresh(denied)
|
|
||||||
expect(getCargoVerification).not.toHaveBeenCalled(); expect(api.refreshReceivingCargo).not.toHaveBeenCalled(); denied.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,305 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import './appointmentNativeForms.css'
|
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import InlineHelp from '@/shared/components/InlineHelp.vue'
|
|
||||||
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
|
|
||||||
import { ElMessageBox } from 'element-plus'
|
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { createAppointmentForm, appointmentPayload, appointmentFormError, FbaAppointmentFields } from '@/modules/overseas-warehouse'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { getCargoVerification, type CargoVerificationContext } from './cargoVerificationApi'
|
|
||||||
import ReceivingScope from './ReceivingScope.vue'
|
|
||||||
import { rejectedCommand, useWorkDraft } from './useWorkDraft'
|
|
||||||
import { refreshReceivingCargo, type ReceivingCargoRefresh, getReceivingExecutionScope, type ReceivingExecutionScope, saveReceivingPlan, type ReceivingPlan, getReceivingContext, getReceivingGroup, proposeReceivingChange, resolveReceivingChange, bookReceiving, changeReceivingGroup, type ReceivingContext, type ReceivingGroup, type ReceivingMember, type ReceivingPending, type ReceivingResult, type ReceivingPropose, type ReceivingResolve, type ReceivingBook, type ReceivingGroupChange } from './receivingApi'
|
|
||||||
|
|
||||||
const props = defineProps<{ batchKey: string; canWrite: boolean; initialCustomerId?: string; owners?: Array<{ id: string; name: string }> }>()
|
|
||||||
const emit = defineEmits<{ updated: []; appointment: [number: string]; batch: [key: string]; external: [path: string] }>()
|
|
||||||
const auth = useAuthStore()
|
|
||||||
const owners = computed(() => [...new Map([...(props.owners || []), ...(auth.user ? [{ id: auth.user.id, name: auth.user.name }] : [])].filter(person => person.id).map(person => [person.id, person])).values()])
|
|
||||||
const access = useAccessPreviewStore(), context = ref<ReceivingContext | null>(null), group = ref<ReceivingGroup | null>(null)
|
|
||||||
const loading = ref(false), saving = ref(false), error = ref<ApiErrorDetails | null>(null), saveError = ref<ApiErrorDetails | null>(null), result = ref<ReceivingResult | null>(null)
|
|
||||||
const confirming = ref(false)
|
|
||||||
const mode = ref<'refresh' | 'plan' | 'overview' | 'customer' | 'resolve' | 'book' | 'reschedule' | 'cancel'>('overview')
|
|
||||||
const customer = ref(''), change = ref<ReceivingPending | null>(null), groupKey = ref<string | null>(null)
|
|
||||||
const adjustment = reactive({ retained: {} as Record<string, number | string>, laterDate: '', ownerId: '', followup: '', reason: '' })
|
|
||||||
const evidence = ref(''), separate = ref(false), confirmedScope = ref(false)
|
|
||||||
const bookingForms = ref<Array<ReturnType<typeof createAppointmentForm>>>([]), bookingEvidence = ref<string[]>([])
|
|
||||||
const bookingMemberKeys = ref<string[]>([]), selectedMemberKeys = ref<string[]>([])
|
|
||||||
const selectedExecution = ref<ReceivingExecutionScope | null>(null), scopeLoading = ref(false), scopeError = ref<ApiErrorDetails | null>(null)
|
|
||||||
const cargoContexts = ref<CargoVerificationContext[]>([]), cargoLoading = ref(false), cargoError = ref<ApiErrorDetails | null>(null)
|
|
||||||
let cargoGeneration = 0
|
|
||||||
let scopeGeneration = 0
|
|
||||||
let initializedGroup: string | null = null
|
|
||||||
const planForm = reactive(createAppointmentForm())
|
|
||||||
const groupForm = reactive(createAppointmentForm())
|
|
||||||
const state = () => JSON.stringify({ selectedMemberKeys: selectedMemberKeys.value, planForm, adjustment, evidence: evidence.value, separate: separate.value, bookingForms: bookingForms.value, bookingEvidence: bookingEvidence.value, groupForm })
|
|
||||||
const baseline = ref(state())
|
|
||||||
type Command = { kind: 'refresh'; request: ReceivingCargoRefresh } | { kind: 'plan'; request: ReceivingPlan } | { kind: 'propose'; request: ReceivingPropose } | { kind: 'resolve'; key: string; request: ReceivingResolve } | { kind: 'book'; request: ReceivingBook } | { kind: 'group'; key: string; request: ReceivingGroupChange }
|
|
||||||
const pending = ref<Command | null>(null)
|
|
||||||
const canLeave = useWorkDraft(computed(() => state() !== baseline.value), computed(() => saving.value || confirming.value || !!pending.value))
|
|
||||||
const readable = computed(() => access.can('platform:appointment:list'))
|
|
||||||
const edit = computed(() => props.canWrite && access.can('platform:overseas-warehouse:inbound-order:fba-appointment'))
|
|
||||||
const remove = computed(() => props.canWrite && access.can('platform:appointment:delete'))
|
|
||||||
const formWritable = computed(() => mode.value === 'cancel' ? remove.value : ['customer', 'resolve'].includes(mode.value) ? edit.value && remove.value : edit.value)
|
|
||||||
const locked = computed(() => loading.value || saving.value || confirming.value || !!error.value || !!pending.value)
|
|
||||||
const sourceKey = (source: { sourceKey: string; destinationKey: string }) => JSON.stringify([source.sourceKey, source.destinationKey])
|
|
||||||
const customerItems = computed(() => context.value?.batch.items.filter(item => item.customerId === customer.value) || [])
|
|
||||||
const customers = computed(() => [...new Set(context.value?.batch.items.map(item => item.customerId) || [])])
|
|
||||||
function customerName(id: string) { return context.value?.agreements.flatMap(row => row.members).find(member => member.customerId === id)?.customerName || context.value?.pendingChanges.flatMap(row => row.originalMembers).find(member => member.customerId === id)?.customerName || null }
|
|
||||||
const eligibleCustomers = computed(() => customers.value.filter(id => context.value?.executionScope.members.some(row => row.member.batchKey === context.value?.batch.batchKey && row.member.customerId === id && row.canRebook && !row.completed)))
|
|
||||||
const uncoveredCustomers = computed(() => eligibleCustomers.value.filter(id => !context.value!.agreements.some(a => a.status === 'ACTIVE' && a.members.some(m => m.batchKey === props.batchKey && m.customerId === id)) && !context.value!.pendingChanges.some(c => c.status === 'WAITING' && c.intent.batchKey === props.batchKey && c.intent.customerId === id)))
|
|
||||||
const refreshReadable = computed(() => readable.value && access.can('platform:overseas-warehouse:last-mile-order:list'))
|
|
||||||
const refreshEligible = (id: string) => refreshReadable.value && !!context.value?.allowedActions.includes('REFRESH_CARGO') && uncoveredCustomers.value.includes(id)
|
|
||||||
const planEligible = (id: string) => !!context.value?.allowedActions.includes('PLAN_RECEIVING') && uncoveredCustomers.value.includes(id)
|
|
||||||
const customerPlan = (id: string) => context.value?.plans.find(plan => plan.batchKey === props.batchKey && plan.customerId === id)
|
|
||||||
const planTimezone = computed(() => { const saved = customerPlan(customer.value); return saved ? saved.timezone : context.value?.batch.timezone })
|
|
||||||
const cargoIncomplete = computed(() => !!context.value?.batch.items.filter(item => eligibleCustomers.value.includes(item.customerId)).some(item => item.packageCount == null || !item.destinationKey || !item.sourceVersion))
|
|
||||||
const bookMembers = computed<ReceivingMember[]>(() => {
|
|
||||||
if (group.value) return group.value.eligibleMembers
|
|
||||||
const batch = context.value?.batch
|
|
||||||
if (!batch?.batchKey || cargoIncomplete.value) return []
|
|
||||||
return eligibleCustomers.value.filter(id => !context.value!.agreements.some(a => a.status === 'ACTIVE' && a.members.some(m => m.batchKey === batch.batchKey && m.customerId === id)) && !context.value!.pendingChanges.some(c => c.status === 'WAITING' && c.intent.customerId === id)).map(id => ({ batchKey: batch.batchKey!, appointmentNo: batch.appointmentNo, batchVersion: batch.version, customerId: id, customerName: customerName(id), sources: batch.items.filter(item => item.customerId === id).map(item => ({ sourceKey: item.sourceKey, inboundCode: item.inboundCode || null, destinationKey: item.destinationKey!, packageCount: item.packageCount!, sourceVersion: item.sourceVersion!, verificationVersion: item.cargoVerificationVersion ?? null })) }))
|
|
||||||
})
|
|
||||||
const cargoProblems = computed(() => {
|
|
||||||
const problems: string[] = []
|
|
||||||
if (!customerItems.value.length || customerItems.value.length > 100 || cargoContexts.value.length !== customerItems.value.length) return ['本客户来源范围未完整读取']
|
|
||||||
if (new Set(customerItems.value.map(item => JSON.stringify([item.sourceKey, item.destinationKey]))).size !== customerItems.value.length) problems.push('本客户存在重复来源,请核对原批次')
|
|
||||||
customerItems.value.forEach((item, index) => {
|
|
||||||
const row = cargoContexts.value[index]!, source = row.source, record = row.verification
|
|
||||||
if (source.sourceKey !== item.sourceKey || source.customerId !== customer.value || source.destinationKey !== item.destinationKey || source.originWarehouseId !== context.value?.batch.originWarehouseId || record && record.destinationKey !== item.destinationKey) problems.push('货物身份、起运仓或目的地与本批不一致')
|
|
||||||
if (row.sourceChanged || record && record.sourceVersion !== source.sourceVersion) problems.push('原货源已变化,请先重新核实资料')
|
|
||||||
if (!source.sourceVersion || record && (!Number.isSafeInteger(record.version) || record.version < 1)) problems.push('最新货物资料版本不完整')
|
|
||||||
if (item.packageCount == null || item.packageCount <= 0 || row.effectivePackages == null || !Number.isSafeInteger(row.effectivePackages) || row.effectivePackages <= 0 || row.availablePackages == null || row.availablePackages < 0 || row.unknownAllocationCount !== 0 || !Number.isSafeInteger(row.allocatedPackages) || row.allocatedPackages < 0) problems.push('本批箱数、最新核实量或分配量待核实')
|
|
||||||
if (row.effectivePackages != null && (row.allocatedPackages > row.effectivePackages || (item.packageCount ?? 0) > row.effectivePackages)) problems.push('已分配量或本批箱数超过最新核实量')
|
|
||||||
problems.push(...row.blockReasons, ...source.blockReasons)
|
|
||||||
})
|
|
||||||
return [...new Set(problems)]
|
|
||||||
})
|
|
||||||
const memberKey = (member: Pick<ReceivingMember, 'batchKey' | 'customerId'>) => JSON.stringify([member.batchKey, member.customerId])
|
|
||||||
const selectedBookMembers = computed(() => bookMembers.value.filter(member => selectedMemberKeys.value.includes(memberKey(member))))
|
|
||||||
const bookingRows = computed(() => !selectedBookMembers.value.length ? [] : separate.value ? selectedBookMembers.value.map(member => ({ member, index: bookMembers.value.findIndex(row => memberKey(row) === memberKey(member)) })) : [{ member: null, index: 0 }])
|
|
||||||
const selectedExecutionAllowed = computed(() => !!selectedExecution.value?.version && selectedBookMembers.value.every(member => selectedExecution.value!.members.some(row => memberKey(row.member) === memberKey(member) && row.canRebook && !row.completed)))
|
|
||||||
const bookingScopeChanged = computed(() => JSON.stringify(bookingMemberKeys.value) !== JSON.stringify(bookMembers.value.map(memberKey)))
|
|
||||||
const currentTrips = computed(() => [...new Set((group.value?.transport || context.value?.transport)?.vehicles.map(vehicle => vehicle.tripNo).filter((number): number is string => !!number) || [])])
|
|
||||||
const laterBatch = computed(() => result.value?.batches.find(batch => result.value?.steps.some(step => step.step === 'ALLOCATE_CARGO' && step.status === 'SUCCESS' && step.targetKey === batch.batchKey)))
|
|
||||||
const canSubmit = computed(() => {
|
|
||||||
if (loading.value || error.value || saving.value || confirming.value || result.value || !context.value) return false
|
|
||||||
if (pending.value) return pending.value.kind === 'group' && pending.value.request.action === 'CANCEL' ? remove.value : pending.value.kind === 'propose' || pending.value.kind === 'resolve' ? edit.value && remove.value : edit.value
|
|
||||||
if (!confirmedScope.value) return false
|
|
||||||
if (mode.value === 'refresh') return edit.value && refreshEligible(customer.value) && !cargoLoading.value && !cargoError.value && !cargoProblems.value.length
|
|
||||||
if (mode.value === 'plan') return edit.value && planEligible(customer.value)
|
|
||||||
if (mode.value === 'customer') return edit.value && remove.value && context.value.allowedActions.includes('PROPOSE_CUSTOMER_CHANGE')
|
|
||||||
if (mode.value === 'resolve') return edit.value && remove.value && change.value?.status === 'WAITING'
|
|
||||||
if (mode.value === 'cancel') return remove.value && group.value?.agreement.status === 'ACTIVE' && !group.value.transport.blockReasons.length
|
|
||||||
if (mode.value === 'reschedule') return edit.value && group.value?.agreement.status === 'ACTIVE' && !group.value.transport.blockReasons.length
|
|
||||||
return mode.value === 'book' && edit.value && !!selectedBookMembers.value.length && !bookingScopeChanged.value && !scopeLoading.value && !scopeError.value && selectedExecutionAllowed.value && (group.value ? group.value.agreement.status === 'CANCELLED' : context.value.allowedActions.includes('BOOK_RECEIVING'))
|
|
||||||
})
|
|
||||||
async function load() {
|
|
||||||
if (!readable.value) return
|
|
||||||
loading.value = true; error.value = null
|
|
||||||
try {
|
|
||||||
const next = await getReceivingContext(props.batchKey)
|
|
||||||
const nextGroup = groupKey.value ? await getReceivingGroup(groupKey.value) : null
|
|
||||||
context.value = next; group.value = nextGroup
|
|
||||||
if (nextGroup && initializedGroup !== nextGroup.agreement.agreementKey) {
|
|
||||||
Object.assign(groupForm, createAppointmentForm(), Object.fromEntries(Object.entries(nextGroup.agreement.details).map(([key, value]) => [key, value ?? ''])))
|
|
||||||
if (mode.value === 'book') initializeBookings()
|
|
||||||
initializedGroup = nextGroup.agreement.agreementKey; baseline.value = state()
|
|
||||||
}
|
|
||||||
if (change.value) change.value = next.pendingChanges.find(row => row.changeKey === change.value?.changeKey) || null
|
|
||||||
if (mode.value === 'book' && !result.value) await refreshSelectedScope()
|
|
||||||
if (mode.value === 'refresh' && !result.value) await loadCargo()
|
|
||||||
} catch (cause) { error.value = getApiErrorDetails(cause, '预约覆盖范围读取失败') }
|
|
||||||
finally { loading.value = false }
|
|
||||||
}
|
|
||||||
function resetForm() { ++cargoGeneration; cargoLoading.value = false; cargoContexts.value = []; cargoError.value = null; ++scopeGeneration; selectedExecution.value = null; scopeLoading.value = false; scopeError.value = null; evidence.value = ''; confirmedScope.value = false; result.value = null; saveError.value = null; separate.value = false }
|
|
||||||
async function overview() { if (!await canLeave()) return; mode.value = 'overview'; groupKey.value = null; group.value = null; change.value = null; resetForm(); baseline.value = state(); await load() }
|
|
||||||
async function adjust(id: string) {
|
|
||||||
if (locked.value || !await canLeave()) return
|
|
||||||
resetForm(); groupKey.value = null; group.value = null; customer.value = id; mode.value = 'customer'
|
|
||||||
adjustment.retained = Object.fromEntries(customerItems.value.filter(item => item.destinationKey).map(item => [sourceKey({ sourceKey: item.sourceKey, destinationKey: item.destinationKey! }), item.packageCount == null ? '' : item.packageCount]))
|
|
||||||
adjustment.laterDate = ''; adjustment.ownerId = owners.value[0]?.id || ''; adjustment.followup = ''; adjustment.reason = ''; baseline.value = state()
|
|
||||||
}
|
|
||||||
async function openCargoRefresh(id: string) {
|
|
||||||
if (locked.value || !refreshEligible(id) || !await canLeave()) return
|
|
||||||
resetForm(); groupKey.value = null; group.value = null; customer.value = id; mode.value = 'refresh'; baseline.value = state(); await loadCargo()
|
|
||||||
}
|
|
||||||
async function loadCargo() {
|
|
||||||
const generation = ++cargoGeneration; confirmedScope.value = false; cargoContexts.value = []; cargoError.value = null; cargoLoading.value = false
|
|
||||||
if (!refreshReadable.value || pending.value) return
|
|
||||||
if (!customerItems.value.length || customerItems.value.length > 100 || customerItems.value.some(item => !item.destinationKey)) { cargoError.value = { message: '本客户来源或目的地不完整,不能采用资料' }; return }
|
|
||||||
cargoLoading.value = true
|
|
||||||
try {
|
|
||||||
const rows = await Promise.all(customerItems.value.map(item => getCargoVerification({ sourceKey: item.sourceKey, customerId: customer.value, destinationKey: item.destinationKey! })))
|
|
||||||
if (generation === cargoGeneration) cargoContexts.value = rows
|
|
||||||
} catch (cause) { if (generation === cargoGeneration) cargoError.value = getApiErrorDetails(cause, '最新货物核实资料读取失败') }
|
|
||||||
finally { if (generation === cargoGeneration) cargoLoading.value = false }
|
|
||||||
}
|
|
||||||
async function openPlan(id: string) {
|
|
||||||
if (locked.value || !planEligible(id) || !await canLeave()) return
|
|
||||||
resetForm(); groupKey.value = null; group.value = null; customer.value = id; mode.value = 'plan'
|
|
||||||
const saved = customerPlan(id)
|
|
||||||
const header = context.value!.batch
|
|
||||||
const inherited = !context.value!.agreements.some(agreement => agreement.status === 'ACTIVE') && ['PENDING', 'FAILED'].includes(header.appointmentStatus || '') ? createAppointmentForm(header) : createAppointmentForm()
|
|
||||||
Object.assign(planForm, createAppointmentForm(), saved ? Object.fromEntries(Object.entries(saved.details).map(([key, value]) => [key, value ?? ''])) : { ...inherited, confirmationNo: '', appointmentAt: '', appointmentEndAt: '', startOffset: '', endOffset: '' })
|
|
||||||
baseline.value = state()
|
|
||||||
}
|
|
||||||
async function resume(pendingChange: ReceivingPending) { if (locked.value || !await canLeave()) return; resetForm(); change.value = pendingChange; mode.value = 'resolve'; baseline.value = state() }
|
|
||||||
function initializeBookings() { bookingMemberKeys.value = bookMembers.value.map(memberKey); selectedMemberKeys.value = [...bookingMemberKeys.value]; bookingForms.value = bookMembers.value.map(() => ({ ...createAppointmentForm(), appointmentStatus: 'SUCCESS' })); bookingEvidence.value = bookMembers.value.map(() => ''); confirmedScope.value = false; baseline.value = state() }
|
|
||||||
async function resetBookingScope() { if (await canLeave()) { initializeBookings(); await refreshSelectedScope() } }
|
|
||||||
async function openGroup(key: string, next: 'book' | 'reschedule' | 'cancel') {
|
|
||||||
if (locked.value || !await canLeave()) return
|
|
||||||
resetForm(); groupKey.value = key; group.value = null; initializedGroup = null; mode.value = next; await load()
|
|
||||||
baseline.value = state()
|
|
||||||
}
|
|
||||||
async function newBooking() { if (locked.value || !await canLeave()) return; resetForm(); groupKey.value = null; group.value = null; mode.value = 'book'; initializeBookings(); await refreshSelectedScope() }
|
|
||||||
async function refreshSelectedScope() {
|
|
||||||
const generation = ++scopeGeneration
|
|
||||||
confirmedScope.value = false; selectedExecution.value = null; scopeError.value = null; scopeLoading.value = false
|
|
||||||
if (mode.value !== 'book' || !readable.value || !selectedBookMembers.value.length || bookingScopeChanged.value) return
|
|
||||||
const members = selectedBookMembers.value.map(({ batchKey, customerId }) => ({ batchKey, customerId }))
|
|
||||||
scopeLoading.value = true
|
|
||||||
try {
|
|
||||||
const scope = await getReceivingExecutionScope(members)
|
|
||||||
if (generation === scopeGeneration) selectedExecution.value = scope
|
|
||||||
} catch (cause) { if (generation === scopeGeneration) scopeError.value = getApiErrorDetails(cause, '所选客户执行资格读取失败') }
|
|
||||||
finally { if (generation === scopeGeneration) scopeLoading.value = false }
|
|
||||||
}
|
|
||||||
onBeforeUnmount(() => { ++scopeGeneration; ++cargoGeneration })
|
|
||||||
function validation(message: string): never { throw new Error(message) }
|
|
||||||
function confirmedDetails(form: ReturnType<typeof createAppointmentForm>) { const invalid = appointmentFormError(form); if (invalid) validation(invalid); if (form.appointmentStatus !== 'SUCCESS') validation('此处登记仓库正式确认;尚未确认请使用本客户的“保存目标 / 未约成”入口'); return appointmentPayload(form) }
|
|
||||||
function buildCommand(decision: 'CONFIRM' | 'WITHDRAW'): Command {
|
|
||||||
const current = context.value!, idempotencyKey = crypto.randomUUID()
|
|
||||||
if (mode.value === 'refresh') {
|
|
||||||
return { kind: 'refresh', request: { idempotencyKey, member: { batchKey: props.batchKey, batchVersion: current.batch.version, customerId: customer.value }, executionVersion: current.executionScope.version, sources: cargoContexts.value.map(row => ({ sourceKey: row.source.sourceKey, destinationKey: row.source.destinationKey, expectedSourceVersion: row.source.sourceVersion!, expectedVerificationVersion: row.verification?.version ?? null })) } }
|
|
||||||
}
|
|
||||||
if (mode.value === 'plan') {
|
|
||||||
if (!['PENDING', 'FAILED'].includes(planForm.appointmentStatus)) validation('客户计划只能保存等待确认或未约成')
|
|
||||||
if (planForm.confirmationNo || planForm.appointmentAt || planForm.appointmentEndAt) validation('客户计划不能写入正式确认')
|
|
||||||
if ((planForm.plannedDate || planForm.plannedAt || planForm.plannedEndAt) && !planTimezone.value) validation('目的仓时区待核实,请先补齐;日期未定时可保存联系结果')
|
|
||||||
if (planForm.plannedEndAt && !planForm.plannedAt) validation('填写结束时段前请填写计划开始时段')
|
|
||||||
if (planForm.startOffset && !planForm.plannedAt || planForm.endOffset && !planForm.plannedEndAt) validation('仅填写对应计划时段时才可填写时差;仅日期或未定日期请清空时差')
|
|
||||||
for (const offset of [planForm.startOffset, planForm.endOffset]) if (offset.trim() && !/^[+-](?:0\d|1[0-7]):[0-5]\d$|^[+-]18:00$/.test(offset.trim())) validation('计划时差请按 +08:00 或 -07:00 格式填写')
|
|
||||||
const invalid = appointmentFormError(planForm); if (invalid) validation(invalid)
|
|
||||||
return { kind: 'plan', request: { idempotencyKey, member: { batchKey: props.batchKey, batchVersion: current.batch.version, customerId: customer.value }, details: appointmentPayload(planForm), executionVersion: current.executionScope.version } }
|
|
||||||
}
|
|
||||||
if (mode.value === 'customer') {
|
|
||||||
if (!owners.value.some(person => person.id === adjustment.ownerId) || !adjustment.reason.trim()) validation('请选择有效负责人并填写调整原因')
|
|
||||||
const quantities = customerItems.value.map(item => {
|
|
||||||
if (!item.destinationKey || !item.sourceVersion || item.packageCount == null) validation('本票数量或来源版本待核实,请先核实货物')
|
|
||||||
const raw = adjustment.retained[sourceKey({ sourceKey: item.sourceKey, destinationKey: item.destinationKey! })]
|
|
||||||
if (raw === '' || raw == null) validation('请填写每票本次先送箱数,全部移出可填 0')
|
|
||||||
const retainedPackages = Number(raw)
|
|
||||||
if (!Number.isSafeInteger(retainedPackages) || retainedPackages < 0 || retainedPackages > item.packageCount!) validation('先送箱数须为 0 至本票当前箱数之间的整数')
|
|
||||||
return { sourceKey: item.sourceKey, destinationKey: item.destinationKey!, retainedPackages, expectedSourceVersion: item.sourceVersion!, expectedVerificationVersion: item.cargoVerificationVersion ?? null }
|
|
||||||
})
|
|
||||||
if (quantities.every((q, index) => q.retainedPackages === customerItems.value[index]!.packageCount)) validation('本次先送量未改变,无需提交调整')
|
|
||||||
return { kind: 'propose', request: { idempotencyKey, intent: { batchKey: props.batchKey, batchVersion: current.batch.version, customerId: customer.value, quantities, laterDate: adjustment.laterDate || null, ownerId: adjustment.ownerId, nextFollowupDate: adjustment.followup || null, reason: adjustment.reason.trim(), transportVersion: current.transport.version } } }
|
|
||||||
}
|
|
||||||
if (mode.value === 'resolve') {
|
|
||||||
if (!change.value) validation('待确认记录已变化,请刷新后核对')
|
|
||||||
if (decision === 'CONFIRM' && !evidence.value.trim()) validation('请填写仓库同意本次保留量和移出量的回复依据')
|
|
||||||
return { kind: 'resolve', key: change.value!.changeKey, request: { idempotencyKey, version: change.value!.version, decision, warehouseEvidence: evidence.value.trim() || null, transportVersion: current.transport.version } }
|
|
||||||
}
|
|
||||||
if (mode.value === 'book') {
|
|
||||||
const selected = selectedBookMembers.value
|
|
||||||
const groups = separate.value ? selected.map(member => [member]) : [selected]
|
|
||||||
return { kind: 'book', request: { idempotencyKey, cancelledAgreementKey: group.value?.agreement.agreementKey || null, cancelledAgreementVersion: group.value?.agreement.version ?? null, executionVersion: selectedExecution.value!.version, bookings: groups.map((members, index) => {
|
|
||||||
const formIndex = bookingRows.value[index]!.index
|
|
||||||
const note = bookingEvidence.value[formIndex]?.trim(); if (!note) validation('请逐份填写仓库确认覆盖客户和货量的依据')
|
|
||||||
return { members: members.map(({ batchKey, batchVersion, customerId }) => ({ batchKey, batchVersion, customerId })), details: confirmedDetails(bookingForms.value[formIndex]!), warehouseEvidence: note! }
|
|
||||||
}) } }
|
|
||||||
}
|
|
||||||
if (!group.value || !evidence.value.trim()) validation('请核对共同预约范围并填写仓库回复依据')
|
|
||||||
return { kind: 'group', key: group.value!.agreement.agreementKey, request: { idempotencyKey, version: group.value!.agreement.version, action: mode.value === 'cancel' ? 'CANCEL' : 'RESCHEDULE', details: mode.value === 'cancel' ? null : confirmedDetails(groupForm), warehouseEvidence: evidence.value.trim(), transportVersion: group.value!.transport.version } }
|
|
||||||
}
|
|
||||||
async function save(decision: 'CONFIRM' | 'WITHDRAW' = 'CONFIRM') {
|
|
||||||
if (!canSubmit.value) return
|
|
||||||
if (!pending.value) {
|
|
||||||
try {
|
|
||||||
const command = buildCommand(decision)
|
|
||||||
if (command.kind === 'group' && command.request.action === 'CANCEL') {
|
|
||||||
confirming.value = true
|
|
||||||
try { await ElMessageBox.confirm('确认取消当前展示的整份预约?货物需求与批次保留,车辆需重新核对。', '取消整份预约', { customClass: 'admin-density-confirm admin-workbench is-dialog', confirmButtonText: '确认取消', cancelButtonText: '返回核对' }) } catch { return } finally { confirming.value = false }
|
|
||||||
}
|
|
||||||
pending.value = command
|
|
||||||
} catch (cause) { saveError.value = { message: cause instanceof Error ? cause.message : '请核对本次范围' }; return }
|
|
||||||
}
|
|
||||||
saving.value = true; saveError.value = null
|
|
||||||
try {
|
|
||||||
const command = pending.value
|
|
||||||
result.value = command.kind === 'refresh' ? await refreshReceivingCargo(command.request) : command.kind === 'plan' ? await saveReceivingPlan(command.request) : command.kind === 'propose' ? await proposeReceivingChange(command.request) : command.kind === 'resolve' ? await resolveReceivingChange(command.key, command.request) : command.kind === 'book' ? await bookReceiving(command.request) : await changeReceivingGroup(command.key, command.request)
|
|
||||||
pending.value = null; baseline.value = state(); confirmedScope.value = false; emit('updated'); await load()
|
|
||||||
} catch (cause) { saveError.value = getApiErrorDetails(cause, '结果待确认,请重试本次提交'); if (rejectedCommand(cause)) { pending.value = null; confirmedScope.value = false; await load() } }
|
|
||||||
finally { saving.value = false }
|
|
||||||
}
|
|
||||||
async function openBatch(key: string) { if (await canLeave()) emit('batch', key) }
|
|
||||||
onMounted(async () => { await load(); if (props.initialCustomerId && customers.value.includes(props.initialCustomerId)) await adjust(props.initialCustomerId) })
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section class="work-form" aria-label="客户调整与共同预约">
|
|
||||||
<h3>{{ context?.batch.appointmentNo || '预约批次' }} · 客户调整与共同预约</h3>
|
|
||||||
<p v-if="!readable">当前账号没有预约列表读取权限。</p>
|
|
||||||
<LoadErrorState v-if="error" title="预约覆盖范围读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<p v-if="loading">正在核对货物、预约覆盖与车辆…</p>
|
|
||||||
<template v-if="context">
|
|
||||||
<el-button v-if="mode !== 'overview' || result" :disabled="locked" @click="overview">返回范围概览</el-button>
|
|
||||||
<p v-for="reason in context.blockReasons" :key="reason" role="status">{{ reason }}</p>
|
|
||||||
<section v-if="result" aria-label="本次处理结果">
|
|
||||||
<h4>{{ result.status === 'WAITING' ? '已保存待确认,原安排尚未改变' : result.status === 'UNCHANGED' ? '安排没有变化' : result.status === 'WITHDRAWN' ? '已撤回变化,原安排保留' : '本次处理已保存' }}</h4>
|
|
||||||
<p v-for="(step, index) in result.steps" :key="index">{{ step.message }}</p>
|
|
||||||
<p v-if="result.nextActions.includes('REVIEW_TRANSPORT')">下一步:核对当前收货时段及车辆安排;本次保存不代表可以发车。</p>
|
|
||||||
<el-button v-if="result.nextActions.includes('BOOK_LATER_BATCH') && laterBatch" :type="result.nextActions[0] === 'BOOK_LATER_BATCH' ? 'primary' : 'default'" :disabled="locked" @click="emit('appointment', laterBatch.appointmentNo)">继续给后送批次约仓</el-button>
|
|
||||||
<template v-if="result.nextActions.includes('REVIEW_TRANSPORT')"><el-button v-for="(number, index) in currentTrips" :key="number" :type="index === 0 && result.nextActions[0] === 'REVIEW_TRANSPORT' ? 'primary' : 'default'" :disabled="locked || !access.can('platform:fleet:trip:list')" @click="emit('external', `/overseas-master-data/trips/${encodeURIComponent(number)}`)">核对本车发车安排 · {{ number }}</el-button></template>
|
|
||||||
<el-button v-if="result.status === 'WAITING' && context.pendingChanges.find(row => row.changeKey === result?.changeKey)" type="primary" :disabled="locked" @click="resume(context.pendingChanges.find(row => row.changeKey === result?.changeKey)!)">继续登记仓库回复</el-button>
|
|
||||||
<template v-if="mode === 'refresh'"><p>本客户资料已处理,可继续保存本客户计划或登记正式预约。</p><el-button :disabled="locked || !planEligible(customer)" @click="openPlan(customer)">继续本客户目标 / 未约成</el-button><el-button :disabled="locked || !edit || !context.allowedActions.includes('BOOK_RECEIVING')" @click="newBooking">核对未确认客户并登记正式预约</el-button></template><p v-if="mode === 'plan'">本客户计划已处理。可返回范围概览核对客户计划,或在本客户事项继续记录回复与跟进。</p><div v-for="batch in (['plan', 'refresh'].includes(mode) ? [] : result.batches).filter(row => row.items.some(item => item.packageCount == null || item.packageCount > 0))" :key="batch.batchKey"><p>{{ batch.appointmentNo }} · {{ batch.plannedDate || '日期未定' }}</p><el-button v-if="batch.batchKey" :disabled="locked" @click="openBatch(batch.batchKey)">查看本批当前去向</el-button><el-button :disabled="locked" @click="emit('appointment', batch.appointmentNo)">继续本批预约</el-button></div>
|
|
||||||
<el-button v-for="(agreement, index) in result.agreements.filter(row => row.status === 'CANCELLED')" :key="agreement.agreementKey" :type="index === 0 && result.nextActions[0] === 'REBOOK_GROUP' ? 'primary' : 'default'" :disabled="locked" @click="openGroup(agreement.agreementKey, 'book')">重新预约这组货物</el-button>
|
|
||||||
</section>
|
|
||||||
<template v-else-if="mode === 'overview'">
|
|
||||||
<h4>各客户计划与货物调整</h4><p>先保存待确认变化,收到仓库明确回复后再生效;本次先送量允许为 0。</p>
|
|
||||||
<div v-for="(id, index) in customers" :key="id"><b>{{ customerName(id) || '—' }} · 客户范围 {{ index + 1 }}</b><p v-for="item in context.batch.items.filter(row => row.customerId === id)" :key="item.id">{{ item.inboundCode || '原票业务号未提供' }} · {{ item.packageCount ?? '箱数待核实' }}<span v-if="item.packageCount != null"> 箱</span></p><p v-if="customerPlan(id)">本客户计划:{{ customerPlan(id)!.details.plannedDate || '日期未定' }} · {{ customerPlan(id)!.details.appointmentStatus === 'FAILED' ? '未约成' : '等待确认' }} · {{ customerPlan(id)!.details.appointmentRemark || '—' }}</p><el-button :disabled="locked || !edit || !refreshEligible(id)" @click="openCargoRefresh(id)">核对并采用本客户最新货物资料</el-button><el-button :disabled="locked || !edit || !planEligible(id)" @click="openPlan(id)">保存目标 / 未约成</el-button><el-button :disabled="locked || !edit || !remove || !context.allowedActions.includes('PROPOSE_CUSTOMER_CHANGE')" @click="adjust(id)">调整本客户先送 / 后送</el-button></div>
|
|
||||||
<h4>待仓库回复</h4><div v-for="pendingChange in context.pendingChanges.filter(row => row.status === 'WAITING')" :key="pendingChange.changeKey"><p>{{ pendingChange.intent.reason }} · 负责人 {{ pendingChange.followup.ownerName || '—' }} · 跟进 {{ pendingChange.followup.nextFollowupDate || '待安排' }}</p><el-button :disabled="locked" @click="resume(pendingChange)">继续本次变化</el-button></div>
|
|
||||||
<h4>整份预约范围</h4><div v-for="agreement in context.agreements" :key="agreement.agreementKey"><p>{{ agreement.details.confirmationNo || '约号未提供' }} · {{ agreement.status === 'ACTIVE' ? '有效' : agreement.status === 'CANCELLED' ? '已取消' : '历史' }} · {{ agreement.details.appointmentAt || '时段未定' }} → {{ agreement.details.appointmentEndAt || '结束未定' }} · {{ agreement.timezone || '时区待核实' }}</p><ReceivingScope :members="agreement.members" /><el-button v-if="agreement.status === 'ACTIVE'" :disabled="locked" @click="openGroup(agreement.agreementKey, 'reschedule')">核对整份改期范围</el-button><el-button v-if="agreement.status === 'ACTIVE'" :disabled="locked" @click="openGroup(agreement.agreementKey, 'cancel')">核对整份取消范围</el-button><el-button v-if="agreement.status === 'CANCELLED'" :disabled="locked" @click="openGroup(agreement.agreementKey, 'book')">重新预约这组货物</el-button></div>
|
|
||||||
<ReceivingScope :members="[]" :transport="context.transport" />
|
|
||||||
<el-button :disabled="locked || !edit || !context.allowedActions.includes('BOOK_RECEIVING')" @click="newBooking">登记当前未覆盖货物的正式预约</el-button>
|
|
||||||
</template>
|
|
||||||
<form v-else class="density-form appointment-native-form" @submit.prevent="save()">
|
|
||||||
<fieldset :disabled="locked || !formWritable">
|
|
||||||
<template v-if="mode === 'refresh'">
|
|
||||||
<h4>{{ customerName(customer) || '—' }} · 核对本客户最新货物资料</h4><p>采用后仅更新本客户的资料快照,本批箱数和其他客户的确认保持不变;保存核实资料不会自动执行采用。</p>
|
|
||||||
<p v-if="cargoLoading">正在读取本客户各票最新核实资料…</p>
|
|
||||||
<LoadErrorState v-if="cargoError" title="最新货物核实资料读取失败" :message="cargoError.message" :loading="cargoLoading" @retry="loadCargo" />
|
|
||||||
<div v-for="(row, index) in cargoContexts" :key="index"><b>{{ row.source.inboundCode || row.source.bookingNo || '—' }}</b><p>本批 {{ customerItems[index]?.packageCount ?? '待核实' }} 箱 · 最新核实 {{ row.verification?.packageCount ?? '待核实' }} 箱 · 当前有效 {{ row.effectivePackages ?? '待核实' }} 箱 · 已分配 {{ row.allocatedPackages }} 箱</p><p>最新货件号:{{ row.verification?.shipmentReferences.join('、') || '—' }}</p></div>
|
|
||||||
<p v-for="problem in cargoProblems" :key="problem" role="status">{{ problem }}</p>
|
|
||||||
<el-button :disabled="locked || cargoLoading" @click="loadCargo">重新读取最新资料</el-button>
|
|
||||||
</template>
|
|
||||||
<template v-if="mode === 'plan'">
|
|
||||||
<h4>{{ customerName(customer) || '—' }} · 本客户普通计划<InlineHelp title="客户计划说明"><p>目标日期可留空;清空日期和时段会清除本客户目标,不取消货物需求。负责人及下次跟进请在本客户事项的“记录回复与跟进”维护。</p></InlineHelp></h4>
|
|
||||||
<p v-for="item in customerItems" :key="item.id">{{ item.inboundCode || '—' }} · {{ item.packageCount ?? '箱数待核实' }}</p>
|
|
||||||
<p>{{ planTimezone || '目的仓时区待核实' }} · 只保存本客户计划,其他客户的确认保持不变。</p>
|
|
||||||
<p v-if="!planEligible(customer)" role="status">本客户资格已变化,暂不能保存普通计划,请返回范围概览核对。</p>
|
|
||||||
<label>目标送仓日期<el-date-picker v-model="planForm.plannedDate" type="date" aria-label="客户计划日期" :disabled="locked || !formWritable" format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable /></label>
|
|
||||||
<label>计划开始时段<el-date-picker v-model="planForm.plannedAt" @change="planForm.startOffset = ''" type="datetime" aria-label="客户计划开始" :disabled="locked || !formWritable" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss" clearable /></label>
|
|
||||||
<label>计划结束时段<el-date-picker v-model="planForm.plannedEndAt" @change="planForm.endOffset = ''" type="datetime" aria-label="客户计划结束" :disabled="locked || !formWritable" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss" clearable /></label>
|
|
||||||
<details><summary>计划时段的夏令时信息</summary><p>当地时钟回拨导致时刻重复时,请按仓库确认填写对应时差。跳时期间不存在的当地时刻不可用,请选择有效时间。</p><label>计划开始时差<input v-model="planForm.startOffset" aria-label="客户计划开始时差" placeholder="如 -07:00" class="workbench-input"></label><label>计划结束时差<input v-model="planForm.endOffset" aria-label="客户计划结束时差" placeholder="如 -08:00" class="workbench-input"></label></details>
|
|
||||||
<label>本次联系结果<select v-model="planForm.appointmentStatus" aria-label="客户计划状态" class="workbench-input"><option value="PENDING">等待对方确认</option><option value="FAILED">未约成</option></select></label>
|
|
||||||
<label>{{ planForm.appointmentStatus === 'FAILED' ? '未约成原因' : '联系备注' }}<textarea v-model="planForm.appointmentRemark" maxlength="1000" aria-label="客户计划备注" class="workbench-input" /></label>
|
|
||||||
|
|
||||||
</template>
|
|
||||||
<template v-if="mode === 'customer'"><h4>仅本客户调整,其他客户保持原安排</h4><div v-for="item in customerItems" :key="item.id"><p>{{ item.inboundCode || '原票业务号未提供' }} · 当前 {{ item.packageCount ?? '待核实' }} 箱</p><label v-if="item.destinationKey">本次先送箱数<input v-model="adjustment.retained[sourceKey({ sourceKey: item.sourceKey, destinationKey: item.destinationKey })]" type="number" min="0" :max="item.packageCount ?? undefined" step="1" aria-label="本次先送箱数" class="workbench-input"></label></div><label>后送目标日期<el-date-picker v-model="adjustment.laterDate" type="date" :disabled="locked || !formWritable" format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable /></label><label>负责人<select v-model="adjustment.ownerId" required aria-label="调整负责人" class="workbench-input"><option value="" disabled>请选择负责人</option><option v-for="person in owners" :key="person.id" :value="person.id">{{ person.name }}</option></select></label><label>下一次跟进日期<el-date-picker v-model="adjustment.followup" type="date" :disabled="locked || !formWritable" format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable /></label><label>调整原因<textarea v-model="adjustment.reason" maxlength="1000" aria-label="调整原因" class="workbench-input" /></label><p>保存仅登记待确认变化,原箱数与原确认仍保留,相关发车暂受阻。</p></template>
|
|
||||||
<template v-if="mode === 'resolve' && change"><h4>仓库回复:本次客户调整</h4><ReceivingScope :members="change.originalMembers" :transport="context.transport" /><p v-for="(quantity, index) in change.intent.quantities" :key="sourceKey(quantity)">货物 {{ index + 1 }} · 本次先送 {{ quantity.retainedPackages }} 箱</p><p>负责人 {{ change.followup.ownerName || '—' }} · 跟进 {{ change.followup.nextFollowupDate || '待安排' }}</p><p>后送日期 {{ change.intent.laterDate || '未定' }} · {{ change.intent.reason }}</p><p v-for="agreement in change.originalAgreements" :key="agreement.agreementKey">原约号 {{ agreement.details.confirmationNo || '—' }} · {{ agreement.details.appointmentAt || '时段未定' }} · {{ agreement.timezone || '时区待核实' }}</p><label>仓库同意保留量和移出量的回复依据<textarea v-model="evidence" maxlength="1000" aria-label="仓库回复依据" class="workbench-input" /></label></template>
|
|
||||||
<template v-if="group"><h4>{{ mode === 'book' ? '整组重约当前范围' : '整份预约当前范围' }}</h4><ReceivingScope :members="mode === 'book' ? selectedBookMembers : group.agreement.members" :transport="group.transport" /><div v-for="(excluded, index) in group.excludedMembers" :key="`${excluded.member.batchKey}:${excluded.member.customerId}`" role="status">排除范围 {{ index + 1 }} · {{ excluded.member.appointmentNo }}:{{ excluded.reason }}</div></template>
|
|
||||||
<template v-if="mode === 'book'"><p>未取得确认时,可先按客户保存目标或未约成原因。</p><el-button v-for="member in bookMembers.filter(row => row.batchKey === batchKey && planEligible(row.customerId))" :key="member.customerId" :disabled="locked || !edit" @click="openPlan(member.customerId)">{{ member.customerName || member.sources.map(source => source.inboundCode || '—').join('、') }} · 保存目标 / 未约成</el-button><p v-if="!group && cargoIncomplete" role="status">货物数量或来源资料待核实,当前不能登记正式预约。</p><p v-if="bookingScopeChanged" role="status">当前成员范围已变化,请核对上方范围后重新填写预约,原输入不会自动套用给其他客户。<el-button :disabled="locked" @click="resetBookingScope">按当前范围重新填写</el-button></p><template v-if="!group"><p v-for="(excluded, index) in context.executionScope.members.filter(row => row.completed || !row.canRebook)" :key="`${excluded.member.batchKey}:${excluded.member.customerId}`" role="status">排除客户范围 {{ index + 1 }}:{{ excluded.reason || (excluded.completed ? '已完成' : '当前不可重新预约') }}</p></template><ReceivingScope v-if="!group" :members="selectedBookMembers" :transport="context.transport" /><LoadErrorState v-if="scopeError" title="所选客户执行资格读取失败" :message="scopeError.message" :loading="scopeLoading" @retry="refreshSelectedScope" /><p v-if="scopeLoading">正在核对所选客户执行资格…</p><p v-if="!scopeLoading && !scopeError && selectedBookMembers.length && !selectedExecutionAllowed" role="status">所选客户执行资格不完整或不可办理,请核对后重新选择。</p><p v-for="(eligibility, index) in selectedExecution?.members.filter(row => row.completed || !row.canRebook) || []" :key="index" role="status">所选范围 {{ index + 1 }}:{{ eligibility.reason || '当前不可重新预约' }}</p><div aria-label="本次预约客户"><h4>选择本次取得确认的客户</h4><label v-for="(member, index) in bookMembers" :key="memberKey(member)"><input v-model="selectedMemberKeys" @change="refreshSelectedScope" :value="memberKey(member)" type="checkbox" :aria-label="`选择预约客户 ${index + 1}`">{{ member.appointmentNo }} · {{ member.customerName || member.sources.map(source => source.inboundCode || '—').join('、') }}</label><p v-if="!selectedBookMembers.length">请至少选择一个客户。</p></div><label><input v-model="separate" type="checkbox">所选客户分别登记预约</label><p>共同预约须由仓库明确确认覆盖当前全部所选客户和货量;重复填写同一约号不能代替共同预约。</p><template v-for="(row, index) in (bookingScopeChanged ? [] : bookingRows)" :key="index"><h4>{{ separate ? `${row.member?.appointmentNo} · ${row.member?.customerName || '—'} · 客户范围 ${index + 1}` : '一份共同预约' }}</h4><FbaAppointmentFields :model="bookingForms[row.index]!" :timezone="group?.agreement.timezone || context.batch.timezone" :disabled="locked || !edit" /><label>仓库确认覆盖依据<textarea v-model="bookingEvidence[row.index]" maxlength="1000" aria-label="预约覆盖依据" class="workbench-input" /></label></template></template>
|
|
||||||
<template v-if="mode === 'reschedule' || mode === 'cancel'"><FbaAppointmentFields v-if="mode === 'reschedule'" :model="groupForm" :timezone="group?.agreement.timezone" :disabled="locked || !edit" /><p v-else>整份取消会清除活动确认及失效目标,保留历史、批次数量和车辆关系;后续仍须重新约仓并核对车辆。</p><label>仓库回复依据<textarea v-model="evidence" maxlength="1000" aria-label="整份回复依据" class="workbench-input" /></label></template>
|
|
||||||
<label><input v-model="confirmedScope" type="checkbox" :disabled="mode === 'book' && (scopeLoading || !!scopeError || !selectedExecutionAllowed) || mode === 'refresh' && (cargoLoading || !!cargoError || !!cargoProblems.length)" aria-label="确认当前范围">已核对上述客户货物、当前预约与车辆范围</label>
|
|
||||||
</fieldset>
|
|
||||||
<div class="density-actions density-actions--footer appointment-form-actions"><el-button type="primary" native-type="submit" :disabled="!canSubmit" :loading="saving">{{ pending ? '重试本次提交' : mode === 'refresh' ? '确认采用本客户最新资料' : mode === 'plan' ? '保存本客户计划' : mode === 'customer' ? '保存待仓库确认' : mode === 'resolve' ? '确认回复并应用本次调整' : mode === 'cancel' ? '确认整份取消' : mode === 'reschedule' ? '保存整份改期' : '保存本次正式预约' }}</el-button></div>
|
|
||||||
<el-button v-if="mode === 'resolve' && !pending" :disabled="!canSubmit" @click="save('WITHDRAW')">撤回变化并保留原安排</el-button>
|
|
||||||
</form>
|
|
||||||
<LoadErrorState v-if="saveError" title="本次提交尚未完成" :message="saveError.message" :show-retry="false"><template #details><ApiErrorMeta :details="saveError" /></template></LoadErrorState>
|
|
||||||
</template>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import { flushPromises, mount } from '@vue/test-utils'
|
|
||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import WorkSharedTripForm from './WorkSharedTripForm.vue'
|
|
||||||
import { getDispatch, useDispatchCommandRecovery, type CommandResult, type DispatchDetail } from '@/modules/overseas-warehouse'
|
|
||||||
import type { LeaveGuard } from './useWorkDraft'
|
|
||||||
const access = vi.hoisted(() => ({ allowed: true }))
|
|
||||||
const identity = vi.hoisted(() => ({ id: '' }))
|
|
||||||
vi.mock('@/core/access/accessPreview', () => ({ useAccessPreviewStore: () => ({ can: () => access.allowed }) }))
|
|
||||||
vi.mock('@/core/auth/auth', () => ({ useAuthStore: () => ({ user: identity }) }))
|
|
||||||
vi.mock('@/modules/overseas-warehouse', async original => ({ ...await original<typeof import('@/modules/overseas-warehouse')>(), getDispatch: vi.fn() }))
|
|
||||||
vi.mock('element-plus', () => ({ ElMessage: { warning: vi.fn() } }))
|
|
||||||
let guard: LeaveGuard
|
|
||||||
function render() { return mount(WorkSharedTripForm, { props: { dispatchNo: 'DS-60', canWrite: true }, global: { provide: { 'appointment-work-leave-guard': (value: LeaveGuard) => { guard = value; return () => undefined } }, stubs: { ElButton: { props: ['disabled'], template: '<button :disabled="disabled"><slot /></button>' }, DispatchWorkflowDialog: { name: 'DispatchWorkflowDialog', props: ['modelValue', 'dispatchNo', 'action'], template: '<div data-add-cargo />' }, LoadErrorState: { props: ['message'], template: '<p role="alert">{{ message }}<button @click="$emit(\'retry\')">重试</button></p>' }, ApiErrorMeta: true } } }) }
|
|
||||||
function detail(no = 'DS-60', allowed = true) { return { dispatchNo: no, status: 'ACTIVE', stage: 'BEFORE_LOADING', recordVersion: 0, counts: { packageCount: 60 }, vehicleInfo: { vehicle: null, driver: null }, actions: { ADD_CARGO: { allowed, blockCode: allowed ? null : 'PICKED', blockReason: allowed ? null : '货物已开始真实拣货' } } } as DispatchDetail }
|
|
||||||
const button = (wrapper: ReturnType<typeof render>, label: string) => wrapper.findAll('button').find(row => row.text() === label)!
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); sessionStorage.clear(); identity.id = crypto.randomUUID(); access.allowed = true; vi.mocked(getDispatch).mockResolvedValue(detail()) })
|
|
||||||
it('opens the native add-cargo workflow for the same dispatch instead of asking for another customer dispatch', async () => {
|
|
||||||
const wrapper = render(); await flushPromises(); expect(getDispatch).toHaveBeenCalledExactlyOnceWith('DS-60'); expect(wrapper.find('input').exists()).toBe(false)
|
|
||||||
expect(wrapper.text()).toContain('60 箱'); await button(wrapper, '选择同仓未安排货物').trigger('click')
|
|
||||||
const dialog = wrapper.getComponent({ name: 'DispatchWorkflowDialog' }); expect(dialog.props()).toMatchObject({ modelValue: true, dispatchNo: 'DS-60', action: 'ADD_CARGO' }); expect(await guard()).toBe(false)
|
|
||||||
dialog.vm.$emit('saved'); await flushPromises(); expect(wrapper.emitted('updated')).toHaveLength(1); expect(await guard()).toBe(true); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('honors native stage/gate and permissions and rejects a different returned business number', async () => {
|
|
||||||
vi.mocked(getDispatch).mockResolvedValueOnce({ ...detail('DS-60', false), stage: 'LOADING' }); const scanned = render(); await flushPromises(); expect(button(scanned, '选择同仓未安排货物').attributes('disabled')).toBeDefined(); expect(scanned.text()).toContain('货物已开始真实拣货'); scanned.unmount()
|
|
||||||
vi.mocked(getDispatch).mockResolvedValueOnce(detail('WRONG')); const wrong = render(); await flushPromises(); expect(wrong.get('[role="alert"]').text()).toContain('原排车单不一致'); wrong.unmount()
|
|
||||||
access.allowed = false; const count = vi.mocked(getDispatch).mock.calls.length, denied = render(); await flushPromises(); expect(getDispatch).toHaveBeenCalledTimes(count); denied.unmount()
|
|
||||||
})
|
|
||||||
it('retains an unknown original add command after the overlay closes and offers recovery without a new key', async () => {
|
|
||||||
const recovery = useDispatchCommandRecovery(() => identity.id); recovery.begin('DS-60', 'ADD_CARGO', { recordVersion: 0, idempotencyKey: 'original-key', cargo: [], batchAllocations: [] })
|
|
||||||
const wrapper = render(); await flushPromises(); expect(button(wrapper, '选择同仓未安排货物').attributes('disabled')).toBeDefined(); expect(await guard()).toBe(false)
|
|
||||||
await button(wrapper, '核对原加货请求').trigger('click'); expect(wrapper.getComponent({ name: 'DispatchWorkflowDialog' }).props('modelValue')).toBe(true)
|
|
||||||
expect(recovery.pending.value?.body.idempotencyKey).toBe('original-key'); wrapper.getComponent({ name: 'DispatchWorkflowDialog' }).vm.$emit('update:modelValue', false); await flushPromises(); expect(await guard()).toBe(false); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('retries lookup as a read and keeps the original detail navigation', async () => {
|
|
||||||
vi.mocked(getDispatch).mockRejectedValueOnce(new Error('lookup failed')); const wrapper = render(); await flushPromises(); await wrapper.get('[role="alert"] button').trigger('click'); await flushPromises(); expect(getDispatch).toHaveBeenCalledTimes(2)
|
|
||||||
await button(wrapper, '查看原排车单').trigger('click'); expect(wrapper.emitted('external')).toEqual([['/overseas-warehouse/dispatches/DS-60']]); wrapper.unmount()
|
|
||||||
})
|
|
||||||
it.each([false, true])('refreshes the original add-cargo gate after a rejection and preserves its message when GET fails: %s', async readFails => {
|
|
||||||
const wrapper = render(); await flushPromises(); await button(wrapper, '选择同仓未安排货物').trigger('click')
|
|
||||||
if (readFails) vi.mocked(getDispatch).mockRejectedValueOnce(new Error('read unavailable'))
|
|
||||||
else vi.mocked(getDispatch).mockResolvedValueOnce(detail('DS-60', false))
|
|
||||||
const dialog = wrapper.getComponent({ name: 'DispatchWorkflowDialog' })
|
|
||||||
dialog.vm.$emit('rejected', { message: '来源已变化,请重新核对', code: 'A0409' })
|
|
||||||
dialog.vm.$emit('update:modelValue', false); await flushPromises()
|
|
||||||
expect(getDispatch).toHaveBeenCalledTimes(2)
|
|
||||||
expect(wrapper.emitted('updated')).toHaveLength(1)
|
|
||||||
expect(wrapper.text()).toContain('来源已变化,请重新核对')
|
|
||||||
expect(button(wrapper, '选择同仓未安排货物').attributes('disabled')).toBeDefined()
|
|
||||||
expect(wrapper.text()).not.toContain('原排车请求尚未核对')
|
|
||||||
if (!readFails) expect(wrapper.text()).toContain('货物已开始真实拣货')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('offers read refresh for proven add-cargo success while retaining the exact original command', async () => {
|
|
||||||
const recovery = useDispatchCommandRecovery(() => identity.id)
|
|
||||||
recovery.begin('DS-60', 'ADD_CARGO', { recordVersion: 0, idempotencyKey: 'known-key', cargo: [], batchAllocations: [] })
|
|
||||||
recovery.pending.value!.attempted = true
|
|
||||||
const completed: CommandResult = {
|
|
||||||
dispatchNo: 'DS-60', action: 'ADD_CARGO', idempotencyKey: 'known-key', recordVersion: 1, status: 'ACTIVE', stage: 'BEFORE_LOADING',
|
|
||||||
occurredAt: '2026-10-20T00:00:00Z', effect: 'APPLIED', counts: { itemCount: 1, palletCount: 1, packageCount: 60, pickedPackageCount: 0, shippedPackageCount: 0 },
|
|
||||||
replayed: false, alreadyArranged: false, result: { dispatchNo: 'DS-60', changedItemIds: [] },
|
|
||||||
}
|
|
||||||
recovery.pending.value!.result = completed
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('操作已完成,页面资料待刷新')
|
|
||||||
expect(wrapper.text()).not.toContain('原排车请求尚未核对')
|
|
||||||
await button(wrapper, '刷新加货资料').trigger('click')
|
|
||||||
expect(wrapper.getComponent({ name: 'DispatchWorkflowDialog' }).props('modelValue')).toBe(true)
|
|
||||||
expect(recovery.pending.value!.body.idempotencyKey).toBe('known-key')
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
it('clears a prior add-cargo rejection after the corrected original-dispatch workflow succeeds', async () => {
|
|
||||||
const wrapper = render(); await flushPromises()
|
|
||||||
const dialog = wrapper.getComponent({ name: 'DispatchWorkflowDialog' })
|
|
||||||
dialog.vm.$emit('rejected', { message: '来源版本需重新核对', code: 'A0409' }); await flushPromises()
|
|
||||||
expect(wrapper.text()).toContain('来源版本需重新核对')
|
|
||||||
dialog.vm.$emit('saved'); await flushPromises()
|
|
||||||
expect(wrapper.text()).not.toContain('来源版本需重新核对')
|
|
||||||
expect(wrapper.emitted('updated')).toHaveLength(2)
|
|
||||||
wrapper.unmount()
|
|
||||||
})
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
|
||||||
import { DispatchWorkflowDialog, DispatchInputError, getDispatch, useDispatchCommandRecovery, type DispatchDetail } from '@/modules/overseas-warehouse'
|
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
|
||||||
import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|
||||||
import { useWorkDraft } from './useWorkDraft'
|
|
||||||
const props = defineProps<{ dispatchNo: string; canWrite: boolean }>()
|
|
||||||
const emit = defineEmits<{ updated: []; busy: [value: boolean]; external: [path: string] }>()
|
|
||||||
const access = useAccessPreviewStore(), auth = useAuthStore(), recovery = useDispatchCommandRecovery(() => auth.user?.id || '')
|
|
||||||
const detail = ref<DispatchDetail | null>(null), open = ref(false), loading = ref(false), error = ref<ApiErrorDetails | null>(null)
|
|
||||||
const rejectionError = ref<ApiErrorDetails | null>(null)
|
|
||||||
const readable = computed(() => access.can('platform:overseas-warehouse:dispatch:list'))
|
|
||||||
const allowed = computed(() => props.canWrite && readable.value && access.can('platform:overseas-warehouse:dispatch:edit') && detail.value?.status === 'ACTIVE' && detail.value.stage === 'BEFORE_LOADING' && detail.value.actions.ADD_CARGO?.allowed === true)
|
|
||||||
const busy = computed(() => loading.value || open.value || Boolean(recovery.pending.value))
|
|
||||||
watch(busy, value => emit('busy', value), { immediate: true })
|
|
||||||
useWorkDraft(computed(() => false), busy)
|
|
||||||
let generation = 0
|
|
||||||
async function load() {
|
|
||||||
const current = ++generation; detail.value = null; error.value = null
|
|
||||||
if (!readable.value) return
|
|
||||||
loading.value = true
|
|
||||||
try {
|
|
||||||
const value = await getDispatch(props.dispatchNo)
|
|
||||||
if (current !== generation) return
|
|
||||||
if (value.dispatchNo !== props.dispatchNo) throw new DispatchInputError('读取结果与原排车单不一致,请重新核对')
|
|
||||||
detail.value = value
|
|
||||||
} catch (cause) { if (current === generation) error.value = getApiErrorDetails(cause, cause instanceof DispatchInputError ? cause.message : '本车加货资格读取失败') }
|
|
||||||
finally { if (current === generation) loading.value = false }
|
|
||||||
}
|
|
||||||
function prepare() { if (allowed.value && !loading.value && !recovery.pending.value) { rejectionError.value = null; open.value = true } }
|
|
||||||
function recover() {
|
|
||||||
if (recovery.pending.value?.dispatchNo === props.dispatchNo && recovery.pending.value.action === 'ADD_CARGO') open.value = true
|
|
||||||
}
|
|
||||||
function saved() { open.value = false; rejectionError.value = null; emit('updated'); void load() }
|
|
||||||
function rejected(details: ApiErrorDetails) { rejectionError.value = details; emit('updated'); void load() }
|
|
||||||
watch(() => props.dispatchNo, load, { immediate: true })
|
|
||||||
onBeforeUnmount(() => { generation++; emit('busy', false) })
|
|
||||||
</script>
|
|
||||||
<template>
|
|
||||||
<section class="work-form" aria-label="为原排车添加同仓货物">
|
|
||||||
<h4>为原排车添加同仓货物</h4><p>本车 {{ dispatchNo }}。只选择尚未安排的真实货物加入本车,不合并另一张排车单或搬迁已扫码货物。</p>
|
|
||||||
<p>箱数无法对应完整实物时,先在原库存作业完成拆托;预约分批不代替实物拆托。</p>
|
|
||||||
<LoadErrorState v-if="error" title="本车加货资格读取失败" :message="error.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="error" /></template></LoadErrorState>
|
|
||||||
<LoadErrorState v-if="rejectionError" title="本车加货未完成" :message="rejectionError.message" :show-retry="false"><template #details><ApiErrorMeta :details="rejectionError" /></template></LoadErrorState>
|
|
||||||
<p v-if="detail">{{ detail.vehicleInfo.vehicle?.plate || '车辆待维护' }} · {{ detail.counts.packageCount }} 箱</p>
|
|
||||||
<p v-if="detail && !allowed">{{ detail.actions.ADD_CARGO?.blockReason || '当前阶段或权限不允许加货,请从原排车单继续作业。' }}</p>
|
|
||||||
<p v-if="recovery.pending.value">{{ recovery.pending.value.result ? '原排车操作已完成,页面资料待刷新,不能另发加货命令。' : '原排车请求尚未核对,不能另发加货命令。' }}<el-button v-if="recovery.pending.value.dispatchNo === dispatchNo && recovery.pending.value.action === 'ADD_CARGO'" @click="recover">{{ recovery.pending.value.result ? '刷新加货资料' : '核对原加货请求' }}</el-button></p>
|
|
||||||
<el-button :disabled="!allowed || busy" :loading="loading" @click="prepare">选择同仓未安排货物</el-button><el-button v-if="readable" :disabled="busy" @click="emit('external', `/overseas-warehouse/dispatches/${encodeURIComponent(dispatchNo)}`)">查看原排车单</el-button>
|
|
||||||
<DispatchWorkflowDialog v-model="open" :dispatch-no="dispatchNo" action="ADD_CARGO" @saved="saved" @rejected="rejected" />
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
@@ -19,7 +19,7 @@ export interface PickupCalendarEntry {
|
|||||||
destinationPortName: string | null
|
destinationPortName: string | null
|
||||||
destinationWarehouseCode: string | null
|
destinationWarehouseCode: string | null
|
||||||
fleetSupplierName: string | null
|
fleetSupplierName: string | null
|
||||||
pickupAppointmentAt: string | null
|
pickupAppointmentAt: string
|
||||||
actualPickupAt: string | null
|
actualPickupAt: string | null
|
||||||
}
|
}
|
||||||
export interface PickupCalendar {
|
export interface PickupCalendar {
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
/* Native work-command fields share the existing input theme, with local form layout. */
|
|
||||||
.appointment-native-form {
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.appointment-native-form > fieldset {
|
|
||||||
display: grid;
|
|
||||||
min-width: 0;
|
|
||||||
gap: var(--admin-space-5);
|
|
||||||
margin: var(--admin-space-3) 0;
|
|
||||||
padding: 0;
|
|
||||||
border: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.appointment-native-form > fieldset > .el-button { justify-self: start; }
|
|
||||||
|
|
||||||
.appointment-native-form label:has(> :is(input, select, textarea, .el-date-editor)) {
|
|
||||||
display: grid;
|
|
||||||
min-width: 0;
|
|
||||||
gap: var(--admin-space-2);
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
.appointment-native-form label > :is(.workbench-input, .el-date-editor) {
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.appointment-native-form label > textarea {
|
|
||||||
resize: vertical;
|
|
||||||
}
|
|
||||||
|
|
||||||
.appointment-native-form label:has(> input[type='checkbox']) {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.appointment-native-form .appointment-form-actions {
|
|
||||||
position: sticky;
|
|
||||||
z-index: 1;
|
|
||||||
bottom: 0;
|
|
||||||
padding-block: var(--admin-space-3);
|
|
||||||
border-top: 1px solid var(--workbench-border);
|
|
||||||
background: var(--workbench-surface);
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import type { FbaAppointmentBatchContext } from './batchApi'
|
|
||||||
export function batchContext(number = 'AP-001', key = 'FBA_APPOINTMENT:1'): FbaAppointmentBatchContext {
|
|
||||||
const appointment: FbaAppointmentBatchContext['appointment'] = { id: '1', appointmentNo: number, batchKey: key, version: 3, appointmentStatus: 'PENDING', originWarehouseId: 'origin-1', fbaWarehouseCode: 'ONT8', selectedCount: 2, replacementAppointmentNos: [], replacementBatchKeys: [], items: [
|
|
||||||
{ id: 'item-1', customerId: 'customer-a', sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', inboundCode: 'IN-A', fbaWarehouseCode: 'ONT8', packageCount: 70, shipmentReferences: ['FBA-A'] },
|
|
||||||
{ id: 'item-2', customerId: 'customer-b', sourceKey: 'BOOKING:2', destinationKey: 'FBA:ONT8', inboundCode: 'IN-B', fbaWarehouseCode: 'ONT8', packageCount: 30, shipmentReferences: ['FBA-B'] },
|
|
||||||
] }
|
|
||||||
return { appointment, originalSourceRefs: appointment.items.map(item => ({ customerId: item.customerId, sourceKey: item.sourceKey, destinationKey: item.destinationKey! })), currentBatches: [appointment], sources: [
|
|
||||||
{ customerId: 'customer-a', sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', packageCount: 70, originalPackages: 100, sourceVersion: 'source-a-v2', cargoVerificationVersion: 4, shipmentReferences: ['FBA-A'] },
|
|
||||||
{ customerId: 'customer-b', sourceKey: 'BOOKING:2', destinationKey: 'FBA:ONT8', packageCount: 30, originalPackages: null, sourceVersion: null, cargoVerificationVersion: 2, shipmentReferences: ['FBA-B'] },
|
|
||||||
], allowedActions: ['VERIFY_CARGO', 'SPLIT', 'MERGE'], blockReasons: [] }
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import { http } from '@/shared/api/http'
|
|
||||||
import { allocationKey, getAppointmentBatch, mergeBatchSources, repartitionAppointments, splitBatch, type RepartitionFbaAppointmentsRequest } from './batchApi'
|
|
||||||
import { batchContext } from './batch.test-support'
|
|
||||||
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn(), post: vi.fn() }, unwrapApiResponse: <T>(value: { data: T }) => value.data }))
|
|
||||||
beforeEach(() => vi.clearAllMocks())
|
|
||||||
it('reads the immutable batch key and submits the actual repartition contract including nullable versions', async () => {
|
|
||||||
const context = batchContext(); vi.mocked(http.get).mockResolvedValue({ data: context })
|
|
||||||
expect(await getAppointmentBatch(context.appointment.batchKey!)).toEqual(context)
|
|
||||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-planning/batches/FBA_APPOINTMENT%3A1')
|
|
||||||
const split = splitBatch(context, { [allocationKey(context.sources[0]!)]: 20 })
|
|
||||||
const request: RepartitionFbaAppointmentsRequest = { originals: [{ appointmentNo: 'AP-001', version: 3 }], batches: split.map(allocations => ({ allocations, plannedDate: null, remark: null })), reason: '分两次送仓', idempotencyKey: 'same-request' }
|
|
||||||
vi.mocked(http.post).mockResolvedValue({ data: { replacedBatchKeys: ['FBA_APPOINTMENT:1'], replacedAppointmentNos: ['AP-001'], appointments: [] } })
|
|
||||||
expect((await repartitionAppointments(request)).replacedBatchKeys).toEqual(['FBA_APPOINTMENT:1'])
|
|
||||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-planning/appointments/repartition', request)
|
|
||||||
expect(request.batches[0]!.allocations.find(row => row.customerId === 'customer-b')).toMatchObject({ expectedSourceVersion: null, expectedVerificationVersion: 2, packageCount: 30 })
|
|
||||||
})
|
|
||||||
it('conserves each source separately, omits zero allocations and preserves all customers and snapshot versions', () => {
|
|
||||||
const context = batchContext()
|
|
||||||
const [remaining, moved] = splitBatch(context, { [allocationKey(context.sources[0]!)]: 70 })
|
|
||||||
expect(remaining).toEqual([{ customerId: 'customer-b', sourceKey: 'BOOKING:2', packageCount: 30, expectedSourceVersion: null, expectedVerificationVersion: 2 }])
|
|
||||||
expect(moved).toEqual([{ customerId: 'customer-a', sourceKey: 'ORDER:1', packageCount: 70, expectedSourceVersion: 'source-a-v2', expectedVerificationVersion: 4 }])
|
|
||||||
expect(() => splitBatch(context, { [allocationKey(context.sources[0]!)]: 71 })).toThrow('每票')
|
|
||||||
expect(() => splitBatch(context, {})).toThrow('两批')
|
|
||||||
expect(() => splitBatch(context, { [allocationKey(context.sources[0]!)]: 70, [allocationKey(context.sources[1]!)]: 30 })).toThrow('两批')
|
|
||||||
})
|
|
||||||
it('merges only the same origin and destination, preserving per-source amounts and detecting stale verification', () => {
|
|
||||||
const first = batchContext(), second = batchContext('AP-002', 'FBA_APPOINTMENT:2')
|
|
||||||
second.sources = [{ ...first.sources[0]!, packageCount: 10 }]
|
|
||||||
const merged = mergeBatchSources([first, second]); expect(merged.map(row => row.packageCount)).toEqual([80, 30])
|
|
||||||
second.sources[0]!.cargoVerificationVersion = 9
|
|
||||||
expect(() => mergeBatchSources([first, second])).toThrow('核实版本')
|
|
||||||
second.appointment.originWarehouseId = 'another-origin'
|
|
||||||
expect(() => mergeBatchSources([first, second])).toThrow('同一起运仓')
|
|
||||||
})
|
|
||||||
it('does not turn unknown quantities or superseded snapshots into allocatable cargo', () => {
|
|
||||||
const context = batchContext(); context.sources[0]!.packageCount = null
|
|
||||||
expect(() => splitBatch(context, {})).toThrow('核实每个来源')
|
|
||||||
context.appointment.replacementBatchKeys = ['FBA_APPOINTMENT:3']
|
|
||||||
expect(() => mergeBatchSources([context])).toThrow('已被替代')
|
|
||||||
})
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
|
||||||
import type { FbaAppointmentDto } from '@/modules/overseas-warehouse'
|
|
||||||
export interface BatchSourceAllocation {
|
|
||||||
customerId: string; sourceKey: string; destinationKey: string; packageCount: number | null
|
|
||||||
originalPackages: number | null; sourceVersion: string | null; cargoVerificationVersion: number | null; shipmentReferences: string[]
|
|
||||||
}
|
|
||||||
export interface FbaAppointmentBatchContext { appointment: FbaAppointmentDto; originalSourceRefs: Array<{ customerId: string; sourceKey: string; destinationKey: string }>; currentBatches: FbaAppointmentDto[]; sources: BatchSourceAllocation[]; allowedActions: Array<'VERIFY_CARGO' | 'SPLIT' | 'MERGE'>; blockReasons: string[] }
|
|
||||||
export interface BatchAllocation { customerId: string; sourceKey: string; packageCount: number; expectedSourceVersion: string | null; expectedVerificationVersion: number | null }
|
|
||||||
export interface RepartitionFbaAppointmentsRequest {
|
|
||||||
originals: Array<{ appointmentNo: string; version: number }>
|
|
||||||
batches: Array<{ plannedDate: string | null; remark: string | null; allocations: BatchAllocation[] }>
|
|
||||||
reason: string; idempotencyKey: string
|
|
||||||
}
|
|
||||||
export interface RepartitionFbaAppointmentsResponse { replacedBatchKeys: string[]; replacedAppointmentNos: string[]; appointments: FbaAppointmentDto[] }
|
|
||||||
const base = '/platform/v1/last-leg/appointment-planning'
|
|
||||||
export async function getAppointmentBatch(batchKey: string) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<FbaAppointmentBatchContext>, ApiEnvelope<FbaAppointmentBatchContext>>(`${base}/batches/${encodeURIComponent(batchKey)}`))
|
|
||||||
}
|
|
||||||
export async function repartitionAppointments(request: RepartitionFbaAppointmentsRequest) {
|
|
||||||
return unwrapApiResponse(await http.post<ApiEnvelope<RepartitionFbaAppointmentsResponse>, ApiEnvelope<RepartitionFbaAppointmentsResponse>>(`${base}/appointments/repartition`, request))
|
|
||||||
}
|
|
||||||
export const allocationKey = (source: Pick<BatchSourceAllocation, 'customerId' | 'sourceKey' | 'destinationKey'>) => JSON.stringify([source.customerId, source.sourceKey, source.destinationKey])
|
|
||||||
export function mergeBatchSources(contexts: FbaAppointmentBatchContext[]): BatchSourceAllocation[] {
|
|
||||||
const first = contexts[0]
|
|
||||||
if (!first) throw new Error('请先选择批次')
|
|
||||||
const rows = new Map<string, BatchSourceAllocation>()
|
|
||||||
const seen = new Set<string>()
|
|
||||||
for (const context of contexts) {
|
|
||||||
const appointment = context.appointment
|
|
||||||
if (seen.has(appointment.appointmentNo)) throw new Error('同一批次不能重复选择')
|
|
||||||
seen.add(appointment.appointmentNo)
|
|
||||||
if (appointment.originWarehouseId !== first.appointment.originWarehouseId || appointment.fbaWarehouseCode !== first.appointment.fbaWarehouseCode) throw new Error('只允许同一起运仓、同一目的仓的批次合并')
|
|
||||||
if (appointment.replacementBatchKeys?.length || appointment.replacementAppointmentNos?.length) throw new Error('原批次已被替代,请选择当前有效批次')
|
|
||||||
if (!context.sources.length) throw new Error('批次缺少真实货物来源,请核对后再操作')
|
|
||||||
for (const source of context.sources) {
|
|
||||||
if (source.packageCount == null || !Number.isSafeInteger(Number(source.packageCount)) || Number(source.packageCount) < 1) throw new Error('请先核实每个来源的本批箱数')
|
|
||||||
const key = allocationKey(source), previous = rows.get(key)
|
|
||||||
if (previous && (previous.sourceVersion !== source.sourceVersion || previous.cargoVerificationVersion !== source.cargoVerificationVersion || JSON.stringify(previous.shipmentReferences) !== JSON.stringify(source.shipmentReferences))) throw new Error('同一来源的核实版本或货件资料不一致,请重新读取批次')
|
|
||||||
const count = Number(source.packageCount) + (previous?.packageCount || 0)
|
|
||||||
if (!Number.isSafeInteger(count)) throw new Error('来源箱数超出可处理范围')
|
|
||||||
rows.set(key, { ...source, packageCount: count })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return [...rows.values()]
|
|
||||||
}
|
|
||||||
export function allocation(source: BatchSourceAllocation, packages: number): BatchAllocation {
|
|
||||||
return { customerId: source.customerId, sourceKey: source.sourceKey, packageCount: packages, expectedSourceVersion: source.sourceVersion, expectedVerificationVersion: source.cargoVerificationVersion }
|
|
||||||
}
|
|
||||||
export function splitBatch(context: FbaAppointmentBatchContext, moved: Record<string, number | string>): [BatchAllocation[], BatchAllocation[]] {
|
|
||||||
const remaining: BatchAllocation[] = [], next: BatchAllocation[] = []
|
|
||||||
for (const source of mergeBatchSources([context])) {
|
|
||||||
const quantity = Number(moved[allocationKey(source)] ?? 0), total = Number(source.packageCount)
|
|
||||||
if (!Number.isSafeInteger(quantity) || quantity < 0 || quantity > total) throw new Error('每票分出箱数须为0至本批箱数之间的整数')
|
|
||||||
if (quantity > 0) next.push(allocation(source, quantity))
|
|
||||||
if (quantity < total) remaining.push(allocation(source, total - quantity))
|
|
||||||
}
|
|
||||||
if (!remaining.length || !next.length) throw new Error('两批都须保留至少一箱货物')
|
|
||||||
return [remaining, next]
|
|
||||||
}
|
|
||||||
@@ -2,17 +2,12 @@ import { describe, expect, it } from 'vitest'
|
|||||||
import { addDays, calendarDates, calendarRange, moveCalendar } from './calendar'
|
import { addDays, calendarDates, calendarRange, moveCalendar } from './calendar'
|
||||||
|
|
||||||
describe('appointment calendar', () => {
|
describe('appointment calendar', () => {
|
||||||
it.each([
|
it('shows six complete Monday-first weeks across year boundaries', () => {
|
||||||
['2026-10-19', '2026-09-28', '2026-11-02', 35],
|
const dates = calendarDates('2027-01-15', 'month')
|
||||||
['2027-01-15', '2026-12-28', '2027-02-01', 35],
|
expect(dates).toHaveLength(42)
|
||||||
['2027-02-15', '2027-02-01', '2027-03-01', 28],
|
expect(dates[0]).toBe('2026-12-28')
|
||||||
['2026-08-15', '2026-07-27', '2026-09-07', 42],
|
expect(dates.at(-1)).toBe('2027-02-07')
|
||||||
] as const)('shows only the complete weeks needed for %s', (anchor, from, to, count) => {
|
expect(calendarRange('2027-01-15', 'month').to).toBe('2027-02-08')
|
||||||
const dates = calendarDates(anchor, 'month')
|
|
||||||
expect(dates).toHaveLength(count)
|
|
||||||
expect(dates[0]).toBe(from)
|
|
||||||
expect(dates.at(-1)).toBe(addDays(to, -1))
|
|
||||||
expect(calendarRange(anchor, 'month')).toEqual({ from, to })
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('moves by a week in week mode instead of following the prototype month-navigation bug', () => {
|
it('moves by a week in week mode instead of following the prototype month-navigation bug', () => {
|
||||||
|
|||||||
@@ -29,19 +29,16 @@ export function addDays(value: string, days: number): string {
|
|||||||
|
|
||||||
export function calendarRange(anchor: string, mode: CalendarMode): { from: string; to: string } {
|
export function calendarRange(anchor: string, mode: CalendarMode): { from: string; to: string } {
|
||||||
const date = parseDate(anchor)
|
const date = parseDate(anchor)
|
||||||
const nextMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1, 12)
|
|
||||||
if (mode === 'month') date.setDate(1)
|
if (mode === 'month') date.setDate(1)
|
||||||
date.setDate(date.getDate() - (date.getDay() + 6) % 7)
|
date.setDate(date.getDate() - (date.getDay() + 6) % 7)
|
||||||
const from = dateKey(date)
|
const from = dateKey(date)
|
||||||
// 月视图只补齐月末所在周,不追加整周的下月日期;结束日期仍为开区间。
|
// A half-open interval also works directly with database timestamps.
|
||||||
return { from, to: mode === 'month' ? addDays(dateKey(nextMonth), (8 - nextMonth.getDay()) % 7) : addDays(from, 7) }
|
return { from, to: addDays(from, mode === 'month' ? 42 : 7) }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function calendarDates(anchor: string, mode: CalendarMode): string[] {
|
export function calendarDates(anchor: string, mode: CalendarMode): string[] {
|
||||||
const { from, to } = calendarRange(anchor, mode)
|
const { from } = calendarRange(anchor, mode)
|
||||||
const dates: string[] = []
|
return Array.from({ length: mode === 'month' ? 42 : 7 }, (_, index) => addDays(from, index))
|
||||||
for (let date = from; date < to; date = addDays(date, 1)) dates.push(date)
|
|
||||||
return dates
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function moveCalendar(anchor: string, mode: CalendarMode, offset: number): string {
|
export function moveCalendar(anchor: string, mode: CalendarMode, offset: number): string {
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
|
||||||
import type { PlanningSource } from './planningApi'
|
|
||||||
export interface CargoVerification { version: number; sourceVersion: string | null; destinationKey: string; sourcePackages: number | null; packageCount: number | null; shipmentReferences: string[]; remark: string | null; operatorName: string | null; verifiedAt: string }
|
|
||||||
export interface CargoVerificationContext { source: PlanningSource; verification: CargoVerification | null; allocatedPackages: number; unknownAllocationCount: number; effectivePackages: number | null; availablePackages: number | null; sourceChanged: boolean; allowedActions: string[]; blockReasons: string[] }
|
|
||||||
export interface CargoVerificationSource { sourceKey: string; customerId: string; destinationKey?: string }
|
|
||||||
export interface SaveCargoVerification { destinationKey: string; expectedSourceVersion: string | null; expectedVersion: number; packageCount: number | null; shipmentReferences: string[]; remark: string | null; idempotencyKey: string }
|
|
||||||
const path = (key: string) => `/platform/v1/last-leg/appointment-planning/sources/${encodeURIComponent(key)}/cargo-verification`
|
|
||||||
export async function getCargoVerification(source: CargoVerificationSource) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<CargoVerificationContext>, ApiEnvelope<CargoVerificationContext>>(path(source.sourceKey), { params: { customerId: source.customerId, destinationKey: source.destinationKey } }))
|
|
||||||
}
|
|
||||||
export async function saveCargoVerification(source: CargoVerificationSource, body: SaveCargoVerification) {
|
|
||||||
return unwrapApiResponse(await http.post<ApiEnvelope<CargoVerification>, ApiEnvelope<CargoVerification>>(path(source.sourceKey), body, { params: { customerId: source.customerId } }))
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { appointmentReturnTarget, appointmentReturnQuery } from './workNavigation'
|
|
||||||
export { default as TripAppointmentPanel } from './TripAppointmentPanel.vue'
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { expect, it, vi } from 'vitest'
|
import { expect, it, vi } from 'vitest'
|
||||||
import { http } from '@/shared/api/http'
|
import { http } from '@/shared/api/http'
|
||||||
import { listPlanningCargo, listPlanningDestinations, listPlanningContainers, resolvePlanningOrder } from './planningApi'
|
import { listPlanningCargo, listPlanningContainers } from './planningApi'
|
||||||
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn() }, unwrapApiResponse: <T>(value: { data: T }) => value.data }))
|
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn() }, unwrapApiResponse: <T>(value: { data: T }) => value.data }))
|
||||||
|
|
||||||
it('uses the gateway planning route and preserves stable source IDs and null predictions', async () => {
|
it('uses the gateway planning route and preserves stable source IDs and null predictions', async () => {
|
||||||
@@ -20,19 +20,3 @@ it('keeps basic container listing on its own endpoint rather than requiring impa
|
|||||||
expect(http.get).toHaveBeenCalledExactlyOnceWith('/platform/v1/last-leg/appointment-planning/containers', { params: { page: 1, size: 20 }, signal: undefined })
|
expect(http.get).toHaveBeenCalledExactlyOnceWith('/platform/v1/last-leg/appointment-planning/containers', { params: { page: 1, size: 20 }, signal: undefined })
|
||||||
expect(result.total).toBe(0)
|
expect(result.total).toBe(0)
|
||||||
})
|
})
|
||||||
it('uses authoritative destination options and sends the selected destination to server pagination', async () => {
|
|
||||||
vi.mocked(http.get).mockClear()
|
|
||||||
vi.mocked(http.get).mockResolvedValueOnce({data:['ABE4','ONT8']})
|
|
||||||
expect(await listPlanningDestinations()).toEqual(['ABE4','ONT8'])
|
|
||||||
expect(http.get).toHaveBeenCalledExactlyOnceWith('/platform/v1/last-leg/appointment-planning/cargo/destinations',{signal:undefined})
|
|
||||||
vi.mocked(http.get).mockResolvedValueOnce({data:{records:[],page:2,size:20,total:0,pages:0}})
|
|
||||||
await listPlanningCargo({page:2,size:20,keyword:'IN-A',destination:'ONT8'})
|
|
||||||
expect(http.get).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-planning/cargo',{params:{page:2,size:20,keyword:'IN-A',destination:'ONT8'},signal:undefined})
|
|
||||||
})
|
|
||||||
it('resolves an order through the real canonical-source endpoint without fabricating an ORDER alias', async () => {
|
|
||||||
vi.mocked(http.get).mockClear()
|
|
||||||
vi.mocked(http.get).mockResolvedValue({data:{source:{sourceKey:'BOOKING:B-1'},coverage:{appointments:[]}}})
|
|
||||||
const query = {orderId:'9007199254740993',customerId:'customer-a',destinationKey:'FBA:ONT8'}
|
|
||||||
expect((await resolvePlanningOrder(query)).source.sourceKey).toBe('BOOKING:B-1')
|
|
||||||
expect(http.get).toHaveBeenCalledExactlyOnceWith('/platform/v1/last-leg/appointment-planning/sources/resolve-order',{params:query})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export interface PlanningCargo {
|
|||||||
mixedDestinations: boolean
|
mixedDestinations: boolean
|
||||||
}
|
}
|
||||||
export interface PlanningCargoPage { records: PlanningCargo[]; page: number; size: number; total: number; pages: number }
|
export interface PlanningCargoPage { records: PlanningCargo[]; page: number; size: number; total: number; pages: number }
|
||||||
export async function listPlanningCargo(query: { page: number; size: number; keyword?: string; destination?: string }, signal?: AbortSignal) {
|
export async function listPlanningCargo(query: { page: number; size: number; keyword?: string }, signal?: AbortSignal) {
|
||||||
const response = await http.get<ApiEnvelope<PlanningCargoPage>, ApiEnvelope<PlanningCargoPage>>(
|
const response = await http.get<ApiEnvelope<PlanningCargoPage>, ApiEnvelope<PlanningCargoPage>>(
|
||||||
'/platform/v1/last-leg/appointment-planning/cargo', { params: query, signal },
|
'/platform/v1/last-leg/appointment-planning/cargo', { params: query, signal },
|
||||||
)
|
)
|
||||||
@@ -39,12 +39,6 @@ export async function listPlanningCargo(query: { page: number; size: number; key
|
|||||||
return { ...page, page: Number(page.page), size: Number(page.size), total: Number(page.total), pages: Number(page.pages) }
|
return { ...page, page: Number(page.page), size: Number(page.size), total: Number(page.total), pages: Number(page.pages) }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listPlanningDestinations(signal?: AbortSignal) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<string[]>, ApiEnvelope<string[]>>(
|
|
||||||
'/platform/v1/last-leg/appointment-planning/cargo/destinations', { signal },
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
export type FollowupStage = 'DRAYAGE_CONTACT' | 'TERMINAL_APPOINTMENT' | 'WAREHOUSE_RECEIVING' | 'FBA_RECEIVING'
|
export type FollowupStage = 'DRAYAGE_CONTACT' | 'TERMINAL_APPOINTMENT' | 'WAREHOUSE_RECEIVING' | 'FBA_RECEIVING'
|
||||||
export interface FollowupRecord { stage: FollowupStage; version: number; contactedParty: string | null; result: string; nextAction: string | null; followupDate: string | null; operatorName: string | null; createdAt: string }
|
export interface FollowupRecord { stage: FollowupStage; version: number; contactedParty: string | null; result: string; nextAction: string | null; followupDate: string | null; operatorName: string | null; createdAt: string }
|
||||||
export interface FollowupHistory { history: { records: FollowupRecord[]; page: number; size: number; total: number; pages: number }; versions: Record<FollowupStage, number> }
|
export interface FollowupHistory { history: { records: FollowupRecord[]; page: number; size: number; total: number; pages: number }; versions: Record<FollowupStage, number> }
|
||||||
@@ -71,12 +65,6 @@ export interface AppointmentCoverage {
|
|||||||
appointments: Array<{ appointmentNo: string; confirmationNo: string | null; status: string; confirmedAt: string | null; confirmedEndAt: string | null; timezone: string | null }>;
|
appointments: Array<{ appointmentNo: string; confirmationNo: string | null; status: string; confirmedAt: string | null; confirmedEndAt: string | null; timezone: string | null }>;
|
||||||
}
|
}
|
||||||
export interface ResolvedPlanningSource { source: PlanningSource; coverage: AppointmentCoverage }
|
export interface ResolvedPlanningSource { source: PlanningSource; coverage: AppointmentCoverage }
|
||||||
export type PlanningSourceLookup = { sourceKey: string; customerId: string; destinationKey?: string } | { orderId: string; customerId: string; destinationKey?: string }
|
|
||||||
export async function resolvePlanningOrder(query: { orderId: string; customerId: string; destinationKey?: string }) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<ResolvedPlanningSource>, ApiEnvelope<ResolvedPlanningSource>>(
|
|
||||||
'/platform/v1/last-leg/appointment-planning/sources/resolve-order', { params: query },
|
|
||||||
))
|
|
||||||
}
|
|
||||||
export interface ExternalAppointmentCandidate extends ResolvedPlanningSource { customerName: string | null; tripNo: string }
|
export interface ExternalAppointmentCandidate extends ResolvedPlanningSource { customerName: string | null; tripNo: string }
|
||||||
export async function listExternalAppointmentCandidates(query: { page: number; size: number; keyword?: string }, signal?: AbortSignal) {
|
export async function listExternalAppointmentCandidates(query: { page: number; size: number; keyword?: string }, signal?: AbortSignal) {
|
||||||
const result = unwrapApiResponse(await http.get<ApiEnvelope<{ records: ExternalAppointmentCandidate[]; total: number }>, ApiEnvelope<{ records: ExternalAppointmentCandidate[]; total: number }>>(
|
const result = unwrapApiResponse(await http.get<ApiEnvelope<{ records: ExternalAppointmentCandidate[]; total: number }>, ApiEnvelope<{ records: ExternalAppointmentCandidate[]; total: number }>>(
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import { http } from '@/shared/api/http'
|
|
||||||
import { refreshReceivingCargo, getReceivingExecutionScope, saveReceivingPlan, getReceivingContext, getReceivingGroup, proposeReceivingChange, resolveReceivingChange, bookReceiving, changeReceivingGroup } from './receivingApi'
|
|
||||||
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn(), post: vi.fn() }, unwrapApiResponse: <T>(value: { data: T }) => value.data }))
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); vi.mocked(http.get).mockResolvedValue({ data: {} }); vi.mocked(http.post).mockResolvedValue({ data: {} }) })
|
|
||||||
it('uses the producer receiving paths and encodes opaque stable identities', async () => {
|
|
||||||
await getReceivingContext('FBA_APPOINTMENT:1'); await getReceivingGroup('GROUP/1')
|
|
||||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/appointment-receiving/batches/FBA_APPOINTMENT%3A1')
|
|
||||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/appointment-receiving/agreements/GROUP%2F1')
|
|
||||||
const propose = { idempotencyKey: 'unchanged-key', intent: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 3, customerId: 'customer-a', quantities: [{ sourceKey: 'ORDER:1', destinationKey: 'FBA:ONT8', retainedPackages: 0, expectedSourceVersion: 'v1', expectedVerificationVersion: 1 }], laterDate: null, ownerId: 'account-owner', nextFollowupDate: null, reason: '全部后送', transportVersion: 'scope-v1' } }
|
|
||||||
await proposeReceivingChange(propose)
|
|
||||||
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/changes', propose)
|
|
||||||
const resolve = { idempotencyKey: 'resolve-key', version: 0, decision: 'CONFIRM' as const, warehouseEvidence: '明确回复', transportVersion: 'scope-v2' }
|
|
||||||
await resolveReceivingChange('CH/1', resolve)
|
|
||||||
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/changes/CH%2F1/resolve', resolve)
|
|
||||||
const book = { idempotencyKey: 'book-key', bookings: [], cancelledAgreementKey: 'GROUP/1', cancelledAgreementVersion: 2, executionVersion: 'scope-v2' }
|
|
||||||
await bookReceiving(book)
|
|
||||||
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/bookings', book)
|
|
||||||
const cancel = { idempotencyKey: 'cancel-key', version: 3, action: 'CANCEL' as const, details: null, warehouseEvidence: '取消依据', transportVersion: 'scope-v3' }
|
|
||||||
await changeReceivingGroup('GROUP/1', cancel)
|
|
||||||
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/agreements/GROUP%2F1/cancel', cancel)
|
|
||||||
await changeReceivingGroup('GROUP/1', { ...cancel, action: 'RESCHEDULE' })
|
|
||||||
expect(http.post).toHaveBeenLastCalledWith('/platform/v1/last-leg/appointment-receiving/agreements/GROUP%2F1/reschedule', expect.objectContaining({ action: 'RESCHEDULE' }))
|
|
||||||
})
|
|
||||||
|
|
||||||
it('posts a customer-scoped ordinary plan with execution version and no formal confirmation', async () => {
|
|
||||||
const request = { idempotencyKey: 'plan-1', member: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 4, customerId: 'customer-b' }, executionVersion: 'exec-2', details: { plannedDate: null, plannedAt: null, plannedEndAt: null, appointmentStatus: 'FAILED' as const, appointmentRemark: '没有时段', confirmationNo: null, appointmentAt: null, appointmentEndAt: null, startOffset: null, endOffset: null } }
|
|
||||||
await saveReceivingPlan(request)
|
|
||||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-receiving/plans', request)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('reads execution eligibility for the explicitly selected members without including guessed versions', async () => {
|
|
||||||
const members = [{ batchKey: 'FBA_APPOINTMENT:2', customerId: 'customer-b' }]
|
|
||||||
const scope = { version: 'only-B', members: [] }
|
|
||||||
vi.mocked(http.post).mockResolvedValueOnce({ data: scope })
|
|
||||||
expect(await getReceivingExecutionScope(members)).toEqual(scope)
|
|
||||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-receiving/execution-scope', { members })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('adopts latest customer cargo versions without including quantity mutations or confirmation fields', async () => {
|
|
||||||
const request = { idempotencyKey: 'adopt-b', member: { batchKey: 'FBA_APPOINTMENT:1', batchVersion: 4, customerId: 'customer-b' }, executionVersion: 'exec-current', sources: [{ sourceKey: 'BOOKING:2', destinationKey: 'FBA:ONT8', expectedSourceVersion: 'latest', expectedVerificationVersion: 2 }] }
|
|
||||||
await refreshReceivingCargo(request)
|
|
||||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-receiving/cargo-refresh', request)
|
|
||||||
})
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
|
||||||
import type { FbaAppointmentDetailsPayload, FbaAppointmentDto } from '@/modules/overseas-warehouse'
|
|
||||||
|
|
||||||
export interface ReceivingSource { sourceKey: string; destinationKey: string; packageCount: number; sourceVersion: string; verificationVersion: number | null; inboundCode: string | null }
|
|
||||||
export interface ReceivingMember { batchKey: string; appointmentNo: string; batchVersion: number; customerId: string; sources: ReceivingSource[]; customerName: string | null }
|
|
||||||
export interface ReceivingAgreement { agreementKey: string; version: number; status: string; destinationKey: string; details: FbaAppointmentDetailsPayload; timezone: string | null; members: ReceivingMember[]; warehouseEvidence: string }
|
|
||||||
export interface ReceivingTransport { version: string; vehicles: Array<{ tripNo: string | null; version: number | null; dispatchNo: string | null; customerId: string; batchKey: string; status: string; packageCount: number }>; blockReasons: string[] }
|
|
||||||
export interface ReceivingQuantity { sourceKey: string; destinationKey: string; retainedPackages: number; expectedSourceVersion: string; expectedVerificationVersion: number | null }
|
|
||||||
export interface ReceivingIntent { batchKey: string; batchVersion: number; customerId: string; quantities: ReceivingQuantity[]; laterDate: string | null; ownerId: string; nextFollowupDate: string | null; reason: string; transportVersion: string }
|
|
||||||
export interface ReceivingExecutionScope { version: string; members: Array<{ member: { batchKey: string; customerId: string }; completed: boolean; canRebook: boolean; reason: string | null }> }
|
|
||||||
export interface ReceivingPending { changeKey: string; version: number; status: string; intent: ReceivingIntent; originalMembers: ReceivingMember[]; originalAgreements: ReceivingAgreement[]; followup: { ownerId: string; ownerName: string | null; nextFollowupDate: string | null } }
|
|
||||||
export interface ReceivingCustomerPlan { batchKey: string; customerId: string; details: FbaAppointmentDetailsPayload; timezone: string | null }
|
|
||||||
export interface ReceivingCargoRefresh { idempotencyKey: string; member: Pick<ReceivingMember, 'batchKey' | 'batchVersion' | 'customerId'>; sources: Array<{ sourceKey: string; destinationKey: string; expectedSourceVersion: string; expectedVerificationVersion: number | null }>; executionVersion: string }
|
|
||||||
export interface ReceivingPlan { idempotencyKey: string; member: Pick<ReceivingMember, 'batchKey' | 'batchVersion' | 'customerId'>; details: FbaAppointmentDetailsPayload; executionVersion: string }
|
|
||||||
export interface ReceivingContext { batch: FbaAppointmentDto; plans: ReceivingCustomerPlan[]; agreements: ReceivingAgreement[]; pendingChanges: ReceivingPending[]; transport: ReceivingTransport; executionScope: ReceivingExecutionScope; allowedActions: string[]; blockReasons: string[] }
|
|
||||||
export interface ReceivingGroup { agreement: ReceivingAgreement; eligibleMembers: ReceivingMember[]; excludedMembers: Array<{ member: ReceivingMember; reason: string; currentAgreementKey: string | null }>; transport: ReceivingTransport; executionScope: ReceivingExecutionScope }
|
|
||||||
export interface ReceivingResult { changeKey: string | null; status: string; batches: FbaAppointmentDto[]; agreements: ReceivingAgreement[]; steps: Array<{ step: string; status: string; targetKey: string; message: string }>; nextActions: string[] }
|
|
||||||
export interface ReceivingPropose { idempotencyKey: string; intent: ReceivingIntent }
|
|
||||||
export interface ReceivingResolve { idempotencyKey: string; version: number; decision: 'CONFIRM' | 'WITHDRAW'; warehouseEvidence: string | null; transportVersion: string }
|
|
||||||
export interface ReceivingBooking { members: Array<Pick<ReceivingMember, 'batchKey' | 'batchVersion' | 'customerId'>>; details: FbaAppointmentDetailsPayload; warehouseEvidence: string }
|
|
||||||
export interface ReceivingBook { idempotencyKey: string; bookings: ReceivingBooking[]; cancelledAgreementKey: string | null; cancelledAgreementVersion: number | null; executionVersion: string }
|
|
||||||
export interface ReceivingGroupChange { idempotencyKey: string; version: number; action: 'RESCHEDULE' | 'CANCEL'; details: FbaAppointmentDetailsPayload | null; warehouseEvidence: string; transportVersion: string }
|
|
||||||
const base = '/platform/v1/last-leg/appointment-receiving'
|
|
||||||
export async function getReceivingContext(batchKey: string) { return unwrapApiResponse(await http.get<ApiEnvelope<ReceivingContext>, ApiEnvelope<ReceivingContext>>(`${base}/batches/${encodeURIComponent(batchKey)}`)) }
|
|
||||||
export async function getReceivingGroup(agreementKey: string) { return unwrapApiResponse(await http.get<ApiEnvelope<ReceivingGroup>, ApiEnvelope<ReceivingGroup>>(`${base}/agreements/${encodeURIComponent(agreementKey)}`)) }
|
|
||||||
async function post(path: string, request: ReceivingCargoRefresh | ReceivingPlan | ReceivingPropose | ReceivingResolve | ReceivingBook | ReceivingGroupChange) { return unwrapApiResponse(await http.post<ApiEnvelope<ReceivingResult>, ApiEnvelope<ReceivingResult>>(`${base}${path}`, request)) }
|
|
||||||
export const proposeReceivingChange = (request: ReceivingPropose) => post('/changes', request)
|
|
||||||
export const resolveReceivingChange = (changeKey: string, request: ReceivingResolve) => post(`/changes/${encodeURIComponent(changeKey)}/resolve`, request)
|
|
||||||
export const bookReceiving = (request: ReceivingBook) => post('/bookings', request)
|
|
||||||
export const changeReceivingGroup = (agreementKey: string, request: ReceivingGroupChange) => post(`/agreements/${encodeURIComponent(agreementKey)}/${request.action === 'CANCEL' ? 'cancel' : 'reschedule'}`, request)
|
|
||||||
|
|
||||||
export const saveReceivingPlan = (request: ReceivingPlan) => post('/plans', request)
|
|
||||||
|
|
||||||
export async function getReceivingExecutionScope(members: Array<{ batchKey: string; customerId: string }>) { return unwrapApiResponse(await http.post<ApiEnvelope<ReceivingExecutionScope>, ApiEnvelope<ReceivingExecutionScope>>(`${base}/execution-scope`, { members })) }
|
|
||||||
|
|
||||||
export const refreshReceivingCargo = (request: ReceivingCargoRefresh) => post('/cargo-refresh', request)
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { projectContainerSchedule } from './schedule'
|
|
||||||
import type { CalendarSources, WarehouseArrival } from './scheduleApi'
|
|
||||||
const range = { from: '2026-11-01', to: '2026-12-01' }
|
|
||||||
const sources: CalendarSources = { containers: [{ containerBookingId: '1', cabinetNo: 'D0001', containerNo: 'TEST-CONT', vesselName: null, voyageNo: null, destinationPortName: 'Port', destinationWarehouseCode: null, arrivalAt: '2026-10-30T23:00:00', arrivalType: 'ACTUAL' }], emptyReturns: [], emptyReturnsReadable: true }
|
|
||||||
const warehouse: WarehouseArrival = { sourceContainerBookingId: '1', containerNo: 'TEST-CONT', warehouseName: 'US-W', warehouseCode: 'US-W', plannedAt: null, actualAt: null, version: 0, planCount: 0, canEdit: true }
|
|
||||||
describe('four-type schedule projection', () => {
|
|
||||||
it('keeps inconsistent authoritative plan times undated instead of hiding them with an automatic date', () => {
|
|
||||||
const events = projectContainerSchedule(sources, [{ ...warehouse, version: -1, canEdit: false }], range, true)
|
|
||||||
expect(events[0]).toMatchObject({ type: 'warehouse', date: null, subtitle: '柜内计划时间不一致,待核实' })
|
|
||||||
})
|
|
||||||
it('adds two local calendar days across months without creating a time', () => {
|
|
||||||
const events = projectContainerSchedule(sources, [warehouse], range, true)
|
|
||||||
expect(events).toHaveLength(1)
|
|
||||||
expect(events[0]).toMatchObject({ type: 'warehouse', date: '2026-11-01', time: '' })
|
|
||||||
})
|
|
||||||
it('changes the automatic date when the authoritative arrival changes and retains manual plans', () => {
|
|
||||||
const changed = { ...sources, containers: [{ ...sources.containers[0]!, arrivalAt: '2026-11-02T05:00:00' }] }
|
|
||||||
expect(projectContainerSchedule(changed, [warehouse], range, true).find(row => row.type === 'warehouse')?.date).toBe('2026-11-04')
|
|
||||||
expect(projectContainerSchedule(changed, [{ ...warehouse, plannedAt: '2026-11-08T09:30:00', version: 1 }], range, true).find(row => row.type === 'warehouse')).toMatchObject({ date: '2026-11-08', time: '09:30', subtitle: '人工维护' })
|
|
||||||
})
|
|
||||||
it('keeps manually moved containers visible when their arrival is outside this month', () => {
|
|
||||||
const events = projectContainerSchedule({ ...sources, containers: [] }, [{ ...warehouse, plannedAt: '2026-11-08T09:30:00' }], range, true)
|
|
||||||
expect(events).toHaveLength(1)
|
|
||||||
expect(events[0]?.date).toBe('2026-11-08')
|
|
||||||
})
|
|
||||||
it('does not replace the planned date with PDA actual arrival', () => {
|
|
||||||
const event = projectContainerSchedule(sources, [{ ...warehouse, plannedAt: '2026-11-05T09:00:00', actualAt: '2026-11-06T10:00:00', planCount: 1, canEdit: false }], range, true)[0]!
|
|
||||||
expect(event.date).toBe('2026-11-05')
|
|
||||||
expect(event.canEdit).toBe(false)
|
|
||||||
expect(event.fields).toContainEqual({ label: '实际到仓', value: '2026-11-06 10:00' })
|
|
||||||
})
|
|
||||||
it('shows missing dates explicitly and never uses internal IDs as display numbers', () => {
|
|
||||||
const events = projectContainerSchedule({ ...sources, containers: [{ ...sources.containers[0]!, containerNo: null, cabinetNo: null, arrivalAt: null }] }, [warehouse], range, false)
|
|
||||||
expect(events.map(row => row.date)).toEqual([null, null])
|
|
||||||
expect(events.every(row => row.sourcePath === undefined)).toBe(true)
|
|
||||||
expect(events.map(row => row.title)).toEqual(['— 到港', '— 计划到仓'])
|
|
||||||
})
|
|
||||||
it('does not invent default plans when the authoritative warehouse query failed', () => {
|
|
||||||
expect(projectContainerSchedule(sources, null, range, true)).toEqual([])
|
|
||||||
})
|
|
||||||
it('uses the actual return date after completion while preserving the deadline in details', () => {
|
|
||||||
const events = projectContainerSchedule({ ...sources, containers: [], emptyReturns: [{ containerBookingId: '1', containerNo: 'TEST-CONT', fleetSupplierName: null, actualEmptyReturnAt: '2026-11-04T10:00:00', emptyReturnWarning: { status: 'RESOLVED', deadlineAt: '2026-11-02T10:00:00' } }] }, [], range, true)
|
|
||||||
expect(events[0]).toMatchObject({ type: 'return', date: '2026-11-04', subtitle: '实际还柜' })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { addDays } from './calendar'
|
|
||||||
import type { CalendarSources, ScheduleRange, WarehouseArrival } from './scheduleApi'
|
|
||||||
|
|
||||||
export const scheduleTypes = ['arrival', 'dispatch', 'return', 'warehouse'] as const
|
|
||||||
export type ScheduleType = typeof scheduleTypes[number]
|
|
||||||
export const scheduleLabels: Record<ScheduleType, string> = { arrival: '到港', dispatch: '排车', return: '还柜', warehouse: '计划到仓' }
|
|
||||||
export interface ScheduleEvent {
|
|
||||||
key: string
|
|
||||||
type: ScheduleType
|
|
||||||
date: string | null
|
|
||||||
time: string
|
|
||||||
title: string
|
|
||||||
subtitle?: string
|
|
||||||
fields: Array<{ label: string; value?: string | null }>
|
|
||||||
sourcePath?: string
|
|
||||||
warehouse?: WarehouseArrival
|
|
||||||
canEdit?: boolean
|
|
||||||
}
|
|
||||||
const inRange = (date: string | null, range: ScheduleRange) => !date || date >= range.from && date < range.to
|
|
||||||
const timestamp = (at: string | null) => at?.replace('T', ' ').slice(0, 16) || '—'
|
|
||||||
|
|
||||||
export function projectContainerSchedule(sources: CalendarSources, warehouses: WarehouseArrival[] | null, range: ScheduleRange, canViewContainer: boolean) {
|
|
||||||
const events: ScheduleEvent[] = []
|
|
||||||
const warehouseMap = new Map(warehouses?.map(row => [row.sourceContainerBookingId, row]) || [])
|
|
||||||
for (const row of sources.containers) {
|
|
||||||
const label = row.containerNo || row.cabinetNo || '—'
|
|
||||||
const fields = [{ label: '集装箱号', value: row.containerNo }, { label: '柜次号', value: row.cabinetNo },
|
|
||||||
{ label: '船名航次', value: [row.vesselName, row.voyageNo].filter(Boolean).join(' / ') }, { label: '目的港', value: row.destinationPortName }]
|
|
||||||
const sourcePath = canViewContainer ? `/container-loading/overseas/${encodeURIComponent(row.containerBookingId)}` : undefined
|
|
||||||
const date = row.arrivalAt?.slice(0, 10) || null
|
|
||||||
if (inRange(date, range)) events.push({ key: `arrival-${row.containerBookingId}`, type: 'arrival', date,
|
|
||||||
time: row.arrivalAt?.slice(11, 16) || '', title: `${label} 到港`, sourcePath,
|
|
||||||
subtitle: row.arrivalAt ? row.arrivalType === 'ACTUAL' ? '实际到港' : '预计到港' : '到港日期未定',
|
|
||||||
fields: [...fields, { label: row.arrivalType === 'ACTUAL' ? '实际到港' : '预计到港', value: timestamp(row.arrivalAt) }] })
|
|
||||||
// 读取失败时不能用默认值遮掉无法读取的人工安排。
|
|
||||||
if (warehouses === null) continue
|
|
||||||
const warehouse = warehouseMap.get(row.containerBookingId)
|
|
||||||
warehouseMap.delete(row.containerBookingId)
|
|
||||||
const canDefault = !warehouse || warehouse.version === 0 && warehouse.planCount === 0
|
|
||||||
const planned = warehouse?.plannedAt?.slice(0, 10) || (canDefault && date ? addDays(date, 2) : null)
|
|
||||||
if (inRange(planned, range)) events.push({ key: `warehouse-${row.containerBookingId}`, type: 'warehouse', date: planned,
|
|
||||||
time: warehouse?.plannedAt?.slice(11, 16) || '', title: `${label} 计划到仓`, sourcePath, warehouse,
|
|
||||||
canEdit: warehouse?.canEdit === true,
|
|
||||||
subtitle: warehouse?.plannedAt ? warehouse.planCount > 0 ? '已有入库计划,日期已冻结' : '人工维护' : canDefault ? '到港日期+2个自然日(默认)' : '柜内计划时间不一致,待核实',
|
|
||||||
fields: [{ label: '集装箱号', value: row.containerNo }, { label: '接仓仓库', value: warehouse?.warehouseName || warehouse?.warehouseCode },
|
|
||||||
{ label: '计划到仓', value: warehouse?.plannedAt ? timestamp(warehouse.plannedAt) : planned },
|
|
||||||
{ label: '实际到仓', value: timestamp(warehouse?.actualAt || null) }] })
|
|
||||||
}
|
|
||||||
// 人工改期可能跨月,与当前月份的到港记录无关。
|
|
||||||
for (const row of warehouseMap.values()) {
|
|
||||||
const date = row.plannedAt?.slice(0, 10) || null
|
|
||||||
if (!date || !inRange(date, range)) continue
|
|
||||||
events.push({ key: `warehouse-${row.sourceContainerBookingId}`, type: 'warehouse', date, time: row.plannedAt?.slice(11, 16) || '',
|
|
||||||
title: `${row.containerNo || '—'} 计划到仓`, subtitle: row.planCount > 0 ? '已有入库计划,日期已冻结' : '人工维护', warehouse: row, canEdit: row.canEdit,
|
|
||||||
sourcePath: canViewContainer ? `/container-loading/overseas/${encodeURIComponent(row.sourceContainerBookingId)}` : undefined,
|
|
||||||
fields: [{ label: '集装箱号', value: row.containerNo }, { label: '接仓仓库', value: row.warehouseName || row.warehouseCode },
|
|
||||||
{ label: '计划到仓', value: timestamp(row.plannedAt) }, { label: '实际到仓', value: timestamp(row.actualAt) }] })
|
|
||||||
}
|
|
||||||
for (const row of sources.emptyReturns) {
|
|
||||||
const at = row.actualEmptyReturnAt || row.emptyReturnWarning.deadlineAt
|
|
||||||
if (!at || !inRange(at.slice(0, 10), range)) continue
|
|
||||||
events.push({ key: `return-${row.containerBookingId}`, type: 'return', date: at.slice(0, 10), time: at.slice(11, 16),
|
|
||||||
title: `${row.containerNo || '—'} ${row.actualEmptyReturnAt ? '已还柜' : '还柜'}`,
|
|
||||||
subtitle: row.actualEmptyReturnAt ? '实际还柜' : row.emptyReturnWarning.status === 'OVERDUE' ? '已超过还柜截止时间' : '还柜截止提醒',
|
|
||||||
sourcePath: canViewContainer ? `/container-loading/overseas/${encodeURIComponent(row.containerBookingId)}` : undefined,
|
|
||||||
fields: [{ label: '集装箱号', value: row.containerNo }, { label: '车队', value: row.fleetSupplierName },
|
|
||||||
{ label: '还柜截止', value: timestamp(row.emptyReturnWarning.deadlineAt) }, { label: '实际还柜', value: timestamp(row.actualEmptyReturnAt) }] })
|
|
||||||
}
|
|
||||||
return events
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
||||||
import { http } from '@/shared/api/http'
|
|
||||||
import { projectContainerSchedule } from './schedule'
|
|
||||||
import { getCalendarSources, getWarehouseArrivals } from './scheduleApi'
|
|
||||||
|
|
||||||
vi.mock('@/shared/api/http', async original => ({
|
|
||||||
...await original<typeof import('@/shared/api/http')>(),
|
|
||||||
http: { get: vi.fn(), post: vi.fn() },
|
|
||||||
}))
|
|
||||||
|
|
||||||
const range = { from: '2026-09-28', to: '2026-11-02' }
|
|
||||||
const bookingId = '9007199254740993'
|
|
||||||
// 使用真实接口的结构:Long 数量序列化为字符串,空时间字段不输出。
|
|
||||||
const wire = {
|
|
||||||
sourceContainerBookingId: bookingId, containerNo: 'CALENDAR-CONT',
|
|
||||||
warehouseName: '接仓仓库', warehouseCode: 'US-W', version: 0, planCount: '0', canEdit: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks()
|
|
||||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'OK', data: {
|
|
||||||
containers: [{ containerBookingId: bookingId, cabinetNo: 'D-CALENDAR', containerNo: 'CALENDAR-CONT',
|
|
||||||
vesselName: null, voyageNo: null, destinationPortName: null, destinationWarehouseCode: null,
|
|
||||||
arrivalAt: '2026-10-20T23:00:00', arrivalType: 'ESTIMATED' }],
|
|
||||||
emptyReturns: [], emptyReturnsReadable: true,
|
|
||||||
} })
|
|
||||||
})
|
|
||||||
|
|
||||||
async function readSchedule(overrides: Record<string, unknown> = {}) {
|
|
||||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'OK', data: [{ ...wire, ...overrides }] })
|
|
||||||
const sources = await getCalendarSources(range)
|
|
||||||
const warehouses = await getWarehouseArrivals(range, [bookingId])
|
|
||||||
return { warehouses, event: projectContainerSchedule(sources, warehouses, range, true).find(row => row.type === 'warehouse') }
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('warehouse calendar response to schedule', () => {
|
|
||||||
it.each(['0', 0])('uses zero plan count %j to show arrival plus two days without inventing a time', async planCount => {
|
|
||||||
const { warehouses, event } = await readSchedule({ planCount })
|
|
||||||
expect(warehouses[0]).toMatchObject({ sourceContainerBookingId: bookingId, planCount: 0, plannedAt: null, actualAt: null })
|
|
||||||
expect(event).toMatchObject({ date: '2026-10-22', time: '', canEdit: true, subtitle: '到港日期+2个自然日(默认)' })
|
|
||||||
expect(event?.fields).toContainEqual({ label: '计划到仓', value: '2026-10-22' })
|
|
||||||
expect(event?.fields).toContainEqual({ label: '实际到仓', value: '—' })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps the authoritative frozen plan instead of recalculating from arrival', async () => {
|
|
||||||
const { warehouses, event } = await readSchedule({ planCount: '2', plannedAt: '2026-10-25T09:30:00', canEdit: false })
|
|
||||||
expect(warehouses[0]?.planCount).toBe(2)
|
|
||||||
expect(event).toMatchObject({ date: '2026-10-25', time: '09:30', canEdit: false, subtitle: '已有入库计划,日期已冻结' })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps a manually maintained time when there is no inbound plan', async () => {
|
|
||||||
const { event } = await readSchedule({ version: 1, plannedAt: '2026-10-24T08:00:00' })
|
|
||||||
expect(event).toMatchObject({ date: '2026-10-24', time: '08:00', subtitle: '人工维护' })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not calculate a default when existing plans have no unified time', async () => {
|
|
||||||
const { event } = await readSchedule({ planCount: '2', canEdit: false })
|
|
||||||
expect(event?.date).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps conflicting authoritative versions unresolved even with zero plans', async () => {
|
|
||||||
const { event } = await readSchedule({ version: -1, canEdit: false })
|
|
||||||
expect(event).toMatchObject({ date: null, canEdit: false, subtitle: '柜内计划时间不一致,待核实' })
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each([undefined, null, '', 'invalid', '-1', '1.5', '9007199254740992', -1, Infinity])(
|
|
||||||
'rejects invalid or unsafe plan count %j rather than treating it as no plans', async planCount => {
|
|
||||||
await expect(readSchedule({ planCount })).rejects.toThrow('入库计划数量无效')
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
|
||||||
|
|
||||||
export interface CalendarContainer {
|
|
||||||
containerBookingId: string
|
|
||||||
cabinetNo: string | null
|
|
||||||
containerNo: string | null
|
|
||||||
vesselName: string | null
|
|
||||||
voyageNo: string | null
|
|
||||||
destinationPortName: string | null
|
|
||||||
destinationWarehouseCode: string | null
|
|
||||||
arrivalAt: string | null
|
|
||||||
arrivalType: 'ACTUAL' | 'ESTIMATED'
|
|
||||||
}
|
|
||||||
export interface CalendarReturn {
|
|
||||||
containerBookingId: string
|
|
||||||
containerNo: string | null
|
|
||||||
fleetSupplierName: string | null
|
|
||||||
actualEmptyReturnAt: string | null
|
|
||||||
emptyReturnWarning: { status: string; deadlineAt: string | null }
|
|
||||||
}
|
|
||||||
export interface CalendarSources { containers: CalendarContainer[]; emptyReturns: CalendarReturn[]; emptyReturnsReadable: boolean }
|
|
||||||
export interface WarehouseArrival {
|
|
||||||
sourceContainerBookingId: string
|
|
||||||
containerNo: string | null
|
|
||||||
warehouseName: string | null
|
|
||||||
warehouseCode: string | null
|
|
||||||
plannedAt: string | null
|
|
||||||
actualAt: string | null
|
|
||||||
version: number
|
|
||||||
planCount: number
|
|
||||||
canEdit: boolean
|
|
||||||
}
|
|
||||||
export interface ScheduleRange { from: string; to: string }
|
|
||||||
type WarehouseArrivalWire = Omit<WarehouseArrival, 'planCount' | 'plannedAt' | 'actualAt'> & {
|
|
||||||
planCount: string | number
|
|
||||||
plannedAt?: string | null
|
|
||||||
actualAt?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 在接口边界统一长整型数量,未知数量不能被当成零触发默认日期。 */
|
|
||||||
function normalizeWarehouseArrival(row: WarehouseArrivalWire): WarehouseArrival {
|
|
||||||
const count = row.planCount
|
|
||||||
if (typeof count !== 'number' && (typeof count !== 'string' || !/^(0|[1-9]\d*)$/.test(count))) {
|
|
||||||
throw new Error('到仓记录的入库计划数量无效,请刷新后重试')
|
|
||||||
}
|
|
||||||
const planCount = Number(count)
|
|
||||||
if (!Number.isSafeInteger(planCount) || planCount < 0) {
|
|
||||||
throw new Error('到仓记录的入库计划数量无效,请刷新后重试')
|
|
||||||
}
|
|
||||||
return { ...row, planCount, plannedAt: row.plannedAt ?? null, actualAt: row.actualAt ?? null }
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getCalendarSources(range: ScheduleRange, signal?: AbortSignal) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<CalendarSources>, ApiEnvelope<CalendarSources>>(
|
|
||||||
'/platform/v1/terminal-drayages/calendar-sources', { params: range, signal },
|
|
||||||
))
|
|
||||||
}
|
|
||||||
export async function getWarehouseArrivals(range: ScheduleRange, sourceContainerBookingIds: string[], signal?: AbortSignal) {
|
|
||||||
const rows = unwrapApiResponse(await http.post<ApiEnvelope<WarehouseArrivalWire[]>, ApiEnvelope<WarehouseArrivalWire[]>>(
|
|
||||||
'/platform/v1/last-leg/appointment-calendar/warehouse-arrivals/query', { ...range, sourceContainerBookingIds }, { signal },
|
|
||||||
))
|
|
||||||
return rows.map(normalizeWarehouseArrival)
|
|
||||||
}
|
|
||||||
export interface WarehouseArrivalChange { estimatedWarehouseArrivalAt: string; expectedVersion: number }
|
|
||||||
export async function saveWarehouseArrival(containerId: string, body: WarehouseArrivalChange, key: string) {
|
|
||||||
return unwrapApiResponse(await http.put<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(
|
|
||||||
`/platform/v1/last-leg/orders/container-summaries/${encodeURIComponent(containerId)}/expected-arrival`, body,
|
|
||||||
{ headers: { 'Idempotency-Key': key } },
|
|
||||||
))
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
const input = {
|
|
||||||
props: ['modelValue', 'disabled', 'type', 'format', 'valueFormat'],
|
|
||||||
emits: ['update:modelValue', 'change'],
|
|
||||||
template: `<input data-temporal-picker :data-picker-kind="type || 'time'" :value="modelValue" :disabled="disabled" @input="$emit('update:modelValue', $event.target.value); $emit('change', $event.target.value)">`,
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DatePickerStub = { name: 'ElDatePicker', ...input }
|
|
||||||
export const TimePickerStub = { name: 'ElTimePicker', ...input }
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { readdirSync, readFileSync } from 'node:fs'
|
|
||||||
import { join, relative } from 'node:path'
|
|
||||||
import { parse } from 'vue/compiler-sfc'
|
|
||||||
import { expect, it } from 'vitest'
|
|
||||||
|
|
||||||
/** 持续检查后台业务模板,避免再次用原生日期控件替代 Element 公共控件。 */
|
|
||||||
it('uses Element date and time pickers throughout Admin business templates', () => {
|
|
||||||
const root = join(process.cwd(), 'src/modules')
|
|
||||||
const violations: string[] = []
|
|
||||||
function inspect(content: DocumentFragment, file: string) {
|
|
||||||
for (const input of content.querySelectorAll('input, el-input')) {
|
|
||||||
const type = input.getAttribute('type') || ''
|
|
||||||
if (/^(date|time|month|week|datetime-local)$/.test(type)) {
|
|
||||||
violations.push(`${relative(root, file)} ${input.tagName.toLowerCase()} type=${type}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 条件和插槽模板的内容位于独立的 DocumentFragment 中。
|
|
||||||
for (const template of content.querySelectorAll('template')) inspect(template.content, file)
|
|
||||||
}
|
|
||||||
function visit(directory: string) {
|
|
||||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
||||||
const file = join(directory, entry.name)
|
|
||||||
if (entry.isDirectory()) visit(file)
|
|
||||||
else if (entry.name.endsWith('.vue')) {
|
|
||||||
const source = parse(readFileSync(file, 'utf8')).descriptor.template?.content
|
|
||||||
if (source) {
|
|
||||||
const template = document.createElement('template')
|
|
||||||
template.innerHTML = source
|
|
||||||
inspect(template.content, file)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
visit(root)
|
|
||||||
expect(violations).toEqual([])
|
|
||||||
})
|
|
||||||
@@ -3,39 +3,10 @@ import { listTripCalendar, projectTripCalendar, tripQueryWindow, type TripCalend
|
|||||||
import { http } from '@/shared/api/http'
|
import { http } from '@/shared/api/http'
|
||||||
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn() }, unwrapApiResponse: (value: {data: unknown}) => value.data }))
|
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn() }, unwrapApiResponse: (value: {data: unknown}) => value.data }))
|
||||||
const range = { from: '2026-10-01', to: '2026-11-01' }
|
const range = { from: '2026-10-01', to: '2026-11-01' }
|
||||||
function trip(dispatchNo: string, plannedDepartureAt: string, originTimezone = 'America/Los_Angeles'): TripCalendarEntry {
|
function trip(tripNo: string, plannedDepartureAt: string, originTimezone = 'America/Los_Angeles'): TripCalendarEntry {
|
||||||
return { sourceType: 'DISPATCH', dispatchNo, containerNumbers: [], status: 'PLANNED', originWarehouseId: '1', originWarehouseCode: 'US-W', originWarehouseName: 'US warehouse', originCountryCode: 'US', originTimezone, originWarehouseStatus: 'ACTIVE', plannedDepartureAt, expectedDriverEndAt: null, departedAt: null, completedAt: null, stops: [{name:'US warehouse'}, {name:'FBA'}], incompleteReasons: [] }
|
return { sourceType: 'TRIP_PLAN', tripNo, status: 'PLANNED', originWarehouseId: '1', originWarehouseCode: 'US-W', originWarehouseName: 'US warehouse', originCountryCode: 'US', originTimezone, originWarehouseStatus: 'ACTIVE', plannedDepartureAt, expectedDriverEndAt: null, departedAt: null, completedAt: null, stops: [{name:'US warehouse'}, {name:'FBA'}], incompleteReasons: [] }
|
||||||
}
|
}
|
||||||
describe('location-based trip calendar', () => {
|
describe('location-based trip calendar', () => {
|
||||||
it('places the reported UTC plan on October 22 at 09:00 in Los Angeles and exposes every container in one event', () => {
|
|
||||||
const row = { ...trip('PC-CALENDAR-001', '2026-10-22T16:00:00Z'), containerNumbers: ['TSTU1234567', 'TSTU7654321'] }
|
|
||||||
const projected = projectTripCalendar({ records: [row, row], unresolvedRecords: [] }, range)
|
|
||||||
expect(projected.events).toHaveLength(1)
|
|
||||||
expect(projected.events[0]).toMatchObject({ key: 'dispatch-PC-CALENDAR-001', date: '2026-10-22', time: '09:00', sourcePath: '/overseas-warehouse/dispatches/PC-CALENDAR-001' })
|
|
||||||
expect(projected.events[0]!.fields).toContainEqual({ label: '关联柜号', value: 'TSTU1234567、TSTU7654321' })
|
|
||||||
expect(projected.events[0]!.fields).toContainEqual({ label: '计划出发(起运仓当地)', value: '2026-10-22 09:00' })
|
|
||||||
expect(projected.events[0]!.fields).toContainEqual({ label: '计划出发(UTC)', value: '2026-10-22T16:00:00Z' })
|
|
||||||
const beijing = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
|
|
||||||
const parts = Object.fromEntries(beijing.formatToParts(new Date(row.plannedDepartureAt!)).map(part => [part.type, part.value]))
|
|
||||||
expect([parts.year, parts.month, parts.day, parts.hour, parts.minute]).toEqual(['2026', '10', '23', '00', '00'])
|
|
||||||
expect(projectTripCalendar({ records: [row], unresolvedRecords: [] }, { from: '2026-10-22', to: '2026-10-23' }).events).toHaveLength(1)
|
|
||||||
expect(projectTripCalendar({ records: [row], unresolvedRecords: [] }, { from: '2026-10-23', to: '2026-10-24' }).events).toEqual([])
|
|
||||||
})
|
|
||||||
it('routes the canonical dispatch number to dispatch detail and does not invent a link without it', () => {
|
|
||||||
const row = trip('DS/REAL', '2026-10-10T12:00:00Z')
|
|
||||||
const result = projectTripCalendar({ records: [row], unresolvedRecords: [] }, range)
|
|
||||||
expect(result.events[0]).toMatchObject({ key: 'dispatch-DS/REAL', title: 'DS/REAL 排车', sourcePath: '/overseas-warehouse/dispatches/DS%2FREAL' })
|
|
||||||
const missing = projectTripCalendar({ records: [{ ...row, dispatchNo: '' }], unresolvedRecords: [] }, range)
|
|
||||||
expect(missing.events).toEqual([])
|
|
||||||
expect(missing.unresolved[0]!.incompleteReasons).toContain('DISPATCH_REFERENCE_UNKNOWN')
|
|
||||||
})
|
|
||||||
it('counts a shared trip once and excludes cancelled arrangements', () => {
|
|
||||||
const shared = trip('DS-SHARED', '2026-10-10T12:00:00Z')
|
|
||||||
const cancelled = { ...trip('DS-CANCELLED', '2026-10-10T12:00:00Z'), status: 'CANCELLED' }
|
|
||||||
const result = projectTripCalendar({ records: [shared, shared, cancelled], unresolvedRecords: [] }, range)
|
|
||||||
expect(result.events).toHaveLength(1)
|
|
||||||
expect(result.events[0]).toMatchObject({ type: 'dispatch', title: 'DS-SHARED 排车' })
|
|
||||||
})
|
|
||||||
it('queries one padded UTC window for 42 location dates without frontend page scanning', async () => {
|
it('queries one padded UTC window for 42 location dates without frontend page scanning', async () => {
|
||||||
const localRange = {from:'2026-09-28',to:'2026-11-09'}
|
const localRange = {from:'2026-09-28',to:'2026-11-09'}
|
||||||
expect(tripQueryWindow(localRange)).toEqual({from:'2026-09-27T10:00:00.000Z',to:'2026-11-09T14:00:00.000Z'})
|
expect(tripQueryWindow(localRange)).toEqual({from:'2026-09-27T10:00:00.000Z',to:'2026-11-09T14:00:00.000Z'})
|
||||||
@@ -47,34 +18,19 @@ describe('location-based trip calendar', () => {
|
|||||||
it('includes the first and last local day and removes padded rows outside each origin date range', () => {
|
it('includes the first and last local day and removes padded rows outside each origin date range', () => {
|
||||||
const records=[trip('LA-before','2026-10-01T06:30:00Z'),trip('NY-start','2026-10-01T06:30:00Z','America/New_York'),trip('LA-end','2026-11-01T06:30:00Z'),trip('NY-after','2026-11-01T06:30:00Z','America/New_York')]
|
const records=[trip('LA-before','2026-10-01T06:30:00Z'),trip('NY-start','2026-10-01T06:30:00Z','America/New_York'),trip('LA-end','2026-11-01T06:30:00Z'),trip('NY-after','2026-11-01T06:30:00Z','America/New_York')]
|
||||||
const projected=projectTripCalendar({records,unresolvedRecords:[]},range)
|
const projected=projectTripCalendar({records,unresolvedRecords:[]},range)
|
||||||
expect(projected.events.map(event=>[event.key,event.date,event.time])).toEqual([['dispatch-NY-start','2026-10-01','02:30'],['dispatch-LA-end','2026-10-31','23:30']])
|
expect(projected.events.map(event=>[event.key,event.date,event.time])).toEqual([['trip-NY-start','2026-10-01','02:30'],['trip-LA-end','2026-10-31','23:30']])
|
||||||
})
|
})
|
||||||
it('does not guess a slot for absent, fixed-offset, invalid or browser-unsupported time zones', () => {
|
it('does not guess a slot for absent, fixed-offset, invalid or browser-unsupported time zones', () => {
|
||||||
const unknown={...trip('unknown','2026-10-10T12:00:00Z'),originTimezone:null,incompleteReasons:['ORIGIN_TIMEZONE_UNKNOWN']}
|
const unknown={...trip('unknown','2026-10-10T12:00:00Z'),originTimezone:null,incompleteReasons:['ORIGIN_TIMEZONE_UNKNOWN']}
|
||||||
const result=projectTripCalendar({records:[trip('offset','2026-10-10T12:00:00Z','UTC-5'),trip('bad','2026-10-10T12:00:00Z','Mars/Base'),trip('naive','2026-10-10T12:00:00')],unresolvedRecords:[unknown]},range)
|
const result=projectTripCalendar({records:[trip('offset','2026-10-10T12:00:00Z','UTC-5'),trip('bad','2026-10-10T12:00:00Z','Mars/Base'),trip('naive','2026-10-10T12:00:00')],unresolvedRecords:[unknown]},range)
|
||||||
expect(result.events).toEqual([]);expect(result.unresolved.map(row=>row.dispatchNo)).toEqual(['unknown','offset','bad','naive'])
|
expect(result.events).toEqual([]);expect(result.unresolved.map(row=>row.tripNo)).toEqual(['unknown','offset','bad','naive'])
|
||||||
})
|
})
|
||||||
it('uses actual local departure through DST changes while retaining the original plan for comparison', () => {
|
it('retains original instants through DST overlap and does not replace the plan date with actual departure', () => {
|
||||||
const row={...trip('DS-DST','2026-11-01T05:30:00Z','America/New_York'),departedAt:'2026-11-02T05:00:00Z',stops:Array.from({length:20},(_,i)=>({name:`Stop ${i}`}))}
|
const row={...trip('TR-DST','2026-11-01T05:30:00Z','America/New_York'),departedAt:'2026-11-02T05:00:00Z',stops:Array.from({length:20},(_,i)=>({name:`Stop ${i}`}))}
|
||||||
const events=projectTripCalendar({records:[row,trip('DS-DST-2','2026-11-01T06:30:00Z','America/New_York')],unresolvedRecords:[]},{from:'2026-11-01',to:'2026-11-08'}).events
|
const events=projectTripCalendar({records:[row,trip('TR-DST-2','2026-11-01T06:30:00Z','America/New_York')],unresolvedRecords:[]},{from:'2026-11-01',to:'2026-11-08'}).events
|
||||||
expect(events.map(event=>event.time)).toEqual(['00:00','01:30'])
|
expect(events.map(event=>event.time)).toEqual(['01:30','01:30'])
|
||||||
expect(events[0]).toMatchObject({date:'2026-11-02',title:'DS-DST 实际发车'})
|
expect(events[0]).toMatchObject({date:'2026-11-01',subtitle:'运输计划,不代表收货方预约已确认'})
|
||||||
expect(events[0]!.fields).toContainEqual({label:'计划出发(UTC)',value:'2026-11-01T05:30:00Z'})
|
expect(events[0]!.fields).toContainEqual({label:'计划出发(UTC)',value:'2026-11-01T05:30:00Z'})
|
||||||
expect(events[0]!.fields).toContainEqual({label:'路线',value:'Stop 0 → Stop 1 → Stop 2 等20站'})
|
expect(events[0]!.fields).toContainEqual({label:'路线',value:'Stop 0 → Stop 1 → Stop 2 等20站'})
|
||||||
})
|
})
|
||||||
it('keeps executed trips in the actual month after replanning and excludes their old plan month', () => {
|
|
||||||
const executed = {...trip('DS-ACTUAL', '2026-10-31T12:00:00Z'), departedAt:'2026-11-01T12:00:00Z'}
|
|
||||||
expect(projectTripCalendar({records:[executed],unresolvedRecords:[]}, range).events).toEqual([])
|
|
||||||
const november = {from:'2026-11-01',to:'2026-12-01'}
|
|
||||||
const event = projectTripCalendar({records:[executed],unresolvedRecords:[]}, november).events[0]
|
|
||||||
expect(event).toMatchObject({date:'2026-11-01',time:'04:00'})
|
|
||||||
const changed = {...executed, plannedDepartureAt:'2026-12-10T12:00:00Z'}
|
|
||||||
expect(projectTripCalendar({records:[changed],unresolvedRecords:[]},november).events[0]).toMatchObject({date:event!.date,time:event!.time})
|
|
||||||
})
|
|
||||||
it('does not fall back to the plan when an actual departure cannot be resolved', () => {
|
|
||||||
const invalid = {...trip('DS-INVALID', '2026-10-15T12:00:00Z'), departedAt:'2026-10-16T12:00:00'}
|
|
||||||
const result = projectTripCalendar({records:[invalid],unresolvedRecords:[]},range)
|
|
||||||
expect(result.events).toEqual([])
|
|
||||||
expect(result.unresolved.map(row=>row.dispatchNo)).toEqual(['DS-INVALID'])
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||||
import type { ScheduleEvent } from './schedule'
|
import type { CalendarEvent } from './AppointmentCalendarPanel.vue'
|
||||||
|
|
||||||
export interface TripCalendarEntry {
|
export interface TripCalendarEntry {
|
||||||
sourceType: 'DISPATCH'
|
sourceType: 'TRIP_PLAN'
|
||||||
dispatchNo: string
|
tripNo: string
|
||||||
containerNumbers: string[]
|
|
||||||
status: string
|
status: string
|
||||||
originWarehouseId: string | null
|
originWarehouseId: string | null
|
||||||
originWarehouseCode: string | null
|
originWarehouseCode: string | null
|
||||||
@@ -24,7 +23,6 @@ export const tripIssueLabels: Record<string, string> = {
|
|||||||
ORIGIN_WAREHOUSE_UNKNOWN: '起运仓资料缺失', ORIGIN_COUNTRY_UNKNOWN: '起运国家待核实',
|
ORIGIN_WAREHOUSE_UNKNOWN: '起运仓资料缺失', ORIGIN_COUNTRY_UNKNOWN: '起运国家待核实',
|
||||||
ORIGIN_TIMEZONE_UNKNOWN: '起运仓时区待核实', ROUTE_INCOMPLETE: '路线资料不完整',
|
ORIGIN_TIMEZONE_UNKNOWN: '起运仓时区待核实', ROUTE_INCOMPLETE: '路线资料不完整',
|
||||||
LOCAL_DATE_UNRESOLVED: '无法确定当地日期',
|
LOCAL_DATE_UNRESOLVED: '无法确定当地日期',
|
||||||
DISPATCH_REFERENCE_UNKNOWN: '排车单号缺失',
|
|
||||||
}
|
}
|
||||||
export function tripIssues(row: TripCalendarEntry) {
|
export function tripIssues(row: TripCalendarEntry) {
|
||||||
return row.incompleteReasons.map(reason => tripIssueLabels[reason] || '资料待核实').join(';')
|
return row.incompleteReasons.map(reason => tripIssueLabels[reason] || '资料待核实').join(';')
|
||||||
@@ -56,34 +54,23 @@ function localStamp(value: string | null, zone: string | null) {
|
|||||||
} catch { return null }
|
} catch { return null }
|
||||||
}
|
}
|
||||||
export function projectTripCalendar(result: TripCalendarResult, range: { from: string; to: string }) {
|
export function projectTripCalendar(result: TripCalendarResult, range: { from: string; to: string }) {
|
||||||
const events: ScheduleEvent[] = [], unresolved = [...result.unresolvedRecords]
|
const events: CalendarEvent[] = [], unresolved = [...result.unresolvedRecords]
|
||||||
const labels: Record<string, string> = { PLANNED: '计划中', IN_TRANSIT: '运输中', COMPLETED: '货物已结案', CANCELLED: '已取消' }
|
const labels: Record<string, string> = { PLANNED: '计划中', IN_TRANSIT: '运输中', COMPLETED: '货物已结案', CANCELLED: '已取消' }
|
||||||
const seen = new Set<string>()
|
|
||||||
for (const row of result.records) {
|
for (const row of result.records) {
|
||||||
if (!row.dispatchNo?.trim()) {
|
const planned = localStamp(row.plannedDepartureAt, row.originTimezone)
|
||||||
unresolved.push({ ...row, incompleteReasons: [...row.incompleteReasons, 'DISPATCH_REFERENCE_UNKNOWN'] }); continue
|
if (row.originCountryCode !== 'US' || !planned) {
|
||||||
}
|
|
||||||
if (seen.has(row.dispatchNo)) continue
|
|
||||||
seen.add(row.dispatchNo)
|
|
||||||
if (row.status === 'CANCELLED') continue
|
|
||||||
// Executed work stays on its actual local date even if the plan changes later.
|
|
||||||
const occurrence = localStamp(row.departedAt ?? row.plannedDepartureAt, row.originTimezone)
|
|
||||||
if (row.originCountryCode !== 'US' || !occurrence) {
|
|
||||||
unresolved.push({ ...row, incompleteReasons: [...row.incompleteReasons, 'LOCAL_DATE_UNRESOLVED'] }); continue
|
unresolved.push({ ...row, incompleteReasons: [...row.incompleteReasons, 'LOCAL_DATE_UNRESOLVED'] }); continue
|
||||||
}
|
}
|
||||||
if (occurrence.date < range.from || occurrence.date >= range.to) continue
|
if (planned.date < range.from || planned.date >= range.to) continue
|
||||||
const actual = localStamp(row.departedAt, row.originTimezone)
|
const actual = localStamp(row.departedAt, row.originTimezone)
|
||||||
const planned = localStamp(row.plannedDepartureAt, row.originTimezone)
|
|
||||||
const driverEnd = localStamp(row.expectedDriverEndAt, row.originTimezone)
|
const driverEnd = localStamp(row.expectedDriverEndAt, row.originTimezone)
|
||||||
events.push({ key: `dispatch-${row.dispatchNo}`, type: 'dispatch', date: occurrence.date, time: occurrence.time,
|
events.push({ key: `trip-${row.tripNo}`, type: 'trip', date: planned.date, time: planned.time,
|
||||||
title: `${row.dispatchNo} ${row.departedAt ? '实际发车' : '排车'}`, subtitle: row.departedAt ? '按起运仓当地实际发车时间展示' : '按起运仓当地计划发车时间展示',
|
title: `${row.tripNo} 用车计划`, subtitle: '运输计划,不代表收货方预约已确认',
|
||||||
sourcePath: `/overseas-warehouse/dispatches/${encodeURIComponent(row.dispatchNo)}`,
|
sourcePath: `/overseas-master-data/trips/${encodeURIComponent(row.tripNo)}`,
|
||||||
fields: [
|
fields: [
|
||||||
{ label: '运输状态', value: labels[row.status] || '待核实' },
|
{ label: '车次状态', value: labels[row.status] || '待核实' },
|
||||||
{ label: '关联柜号', value: row.containerNumbers.join('、') },
|
|
||||||
{ label: '起运仓', value: row.originWarehouseName || row.originWarehouseCode },
|
{ label: '起运仓', value: row.originWarehouseName || row.originWarehouseCode },
|
||||||
{ label: '地点时区', value: row.originTimezone },
|
{ label: '地点时区', value: row.originTimezone },
|
||||||
{ label: '计划出发(起运仓当地)', value: planned ? `${planned.date} ${planned.time}` : null },
|
|
||||||
{ label: '计划出发(UTC)', value: row.plannedDepartureAt },
|
{ label: '计划出发(UTC)', value: row.plannedDepartureAt },
|
||||||
{ label: '路线', value: row.stops.slice(0, 3).map(stop => stop.name).join(' → ') + (row.stops.length > 3 ? ` 等${row.stops.length}站` : '') },
|
{ label: '路线', value: row.stops.slice(0, 3).map(stop => stop.name).join(' → ') + (row.stops.length > 3 ? ` 等${row.stops.length}站` : '') },
|
||||||
{ label: '实际出发', value: actual ? `${actual.date} ${actual.time}` : row.departedAt ? '时刻待核实' : '尚未记录' },
|
{ label: '实际出发', value: actual ? `${actual.date} ${actual.time}` : row.departedAt ? '时刻待核实' : '尚未记录' },
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
import { inject, onBeforeUnmount, type Ref } from 'vue'
|
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
|
||||||
import axios from 'axios'
|
|
||||||
import { ApiResponseError, getApiErrorDetails } from '@/shared/api/http'
|
|
||||||
export type LeaveGuard = () => Promise<boolean>
|
|
||||||
export function useWorkDraft(dirty: Ref<boolean>, pending: Ref<boolean>) {
|
|
||||||
const register = inject<((guard: LeaveGuard) => () => void) | undefined>('appointment-work-leave-guard', undefined)
|
|
||||||
const canLeave: LeaveGuard = async () => {
|
|
||||||
if (pending.value) { ElMessage.warning('本次保存结果待确认,请重试后再离开'); return false }
|
|
||||||
if (!dirty.value) return true
|
|
||||||
try { await ElMessageBox.confirm('未保存的内容将丢失,确认离开?', '保留编辑', { confirmButtonText: '离开', cancelButtonText: '继续编辑', customClass: 'admin-density-confirm' }); return true } catch { return false }
|
|
||||||
}
|
|
||||||
const unregister = register?.(canLeave)
|
|
||||||
onBeforeUnmount(() => unregister?.())
|
|
||||||
return canLeave
|
|
||||||
}
|
|
||||||
export function rejectedCommand(cause: unknown) {
|
|
||||||
const status = cause instanceof ApiResponseError ? cause.status : axios.isAxiosError(cause) ? cause.response?.status : undefined
|
|
||||||
const code = getApiErrorDetails(cause).code || ''
|
|
||||||
return [400, 403, 404, 409, 422].includes(status || 0) || /^(HTTP_|A0?)?(400|403|404|409|422)$/.test(code)
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
import { afterEach, expect, it, vi } from 'vitest'
|
|
||||||
import { ApiResponseError } from '@/shared/api/http'
|
|
||||||
import { useWorkSyncRead } from './useWorkSyncRead'
|
|
||||||
const pending = () => new ApiResponseError('预约批次或运输关联已变化,服务端正在协调完整工作清单', 'A0409', 409, undefined, 'request-sync', 'trace-sync')
|
|
||||||
afterEach(() => vi.useRealTimers())
|
|
||||||
it('waits only for the full-work synchronization guard and returns the fresh result', async () => {
|
|
||||||
vi.useFakeTimers()
|
|
||||||
const reader = useWorkSyncRead(), load = vi.fn().mockRejectedValueOnce(pending()).mockResolvedValue('fresh')
|
|
||||||
const result = reader.read(load, new AbortController().signal)
|
|
||||||
await vi.advanceTimersByTimeAsync(0)
|
|
||||||
expect(reader.syncing.value).toBe(true)
|
|
||||||
expect(load).toHaveBeenCalledTimes(1)
|
|
||||||
await vi.advanceTimersByTimeAsync(2000)
|
|
||||||
expect(await result).toBe('fresh')
|
|
||||||
expect(reader.syncing.value).toBe(false)
|
|
||||||
})
|
|
||||||
it.each([new ApiResponseError('事项版本已变化', 'A0409', 409), new ApiResponseError('无权查看', 'A0403', 403), new Error('network')])('does not retry other failures: %s', async error => {
|
|
||||||
const reader = useWorkSyncRead(), load = vi.fn().mockRejectedValue(error)
|
|
||||||
await expect(reader.read(load, new AbortController().signal)).rejects.toBe(error)
|
|
||||||
expect(load).toHaveBeenCalledTimes(1)
|
|
||||||
expect(reader.syncing.value).toBe(false)
|
|
||||||
})
|
|
||||||
it('stops waiting at the limit and preserves diagnostic IDs on the original error', async () => {
|
|
||||||
vi.useFakeTimers()
|
|
||||||
const error = pending(), reader = useWorkSyncRead(), load = vi.fn().mockRejectedValue(error)
|
|
||||||
const result = expect(reader.read(load, new AbortController().signal)).rejects.toBe(error)
|
|
||||||
await vi.advanceTimersByTimeAsync(30000)
|
|
||||||
await result
|
|
||||||
expect(load).toHaveBeenCalledTimes(16)
|
|
||||||
expect(reader.syncing.value).toBe(false)
|
|
||||||
expect(error.traceId).toBe('trace-sync')
|
|
||||||
expect(vi.getTimerCount()).toBe(0)
|
|
||||||
})
|
|
||||||
it('cancels a waiting read without sending another request', async () => {
|
|
||||||
vi.useFakeTimers()
|
|
||||||
const controller = new AbortController(), reader = useWorkSyncRead(), load = vi.fn().mockRejectedValue(pending())
|
|
||||||
const result = expect(reader.read(load, controller.signal)).rejects.toHaveProperty('name', 'AbortError')
|
|
||||||
await vi.advanceTimersByTimeAsync(0)
|
|
||||||
controller.abort()
|
|
||||||
await result
|
|
||||||
await vi.advanceTimersByTimeAsync(30000)
|
|
||||||
expect(load).toHaveBeenCalledTimes(1)
|
|
||||||
expect(reader.syncing.value).toBe(false)
|
|
||||||
expect(vi.getTimerCount()).toBe(0)
|
|
||||||
})
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
import { ref } from 'vue'
|
|
||||||
import { getApiErrorDetails } from '@/shared/api/http'
|
|
||||||
|
|
||||||
// 只等待工作清单同步守卫;版本冲突、权限失败和写请求均不重试。
|
|
||||||
export function useWorkSyncRead() {
|
|
||||||
const syncing = ref(false)
|
|
||||||
let generation = 0
|
|
||||||
async function read<T>(load: () => Promise<T>, signal: AbortSignal): Promise<T> {
|
|
||||||
const current = ++generation
|
|
||||||
syncing.value = false
|
|
||||||
try {
|
|
||||||
for (let attempt = 0; ; attempt++) {
|
|
||||||
signal.throwIfAborted()
|
|
||||||
try { return await load() }
|
|
||||||
catch (cause) {
|
|
||||||
const error = getApiErrorDetails(cause)
|
|
||||||
if (error.code !== 'A0409' || error.message !== '预约批次或运输关联已变化,服务端正在协调完整工作清单' || attempt >= 15) throw cause
|
|
||||||
if (current === generation) syncing.value = true
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
|
||||||
const abort = () => { clearTimeout(timer); reject(signal.reason) }
|
|
||||||
const timer = setTimeout(() => { signal.removeEventListener('abort', abort); resolve() }, 2000)
|
|
||||||
signal.addEventListener('abort', abort, { once: true })
|
|
||||||
if (signal.aborted) { signal.removeEventListener('abort', abort); abort() }
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally { if (current === generation) syncing.value = false }
|
|
||||||
}
|
|
||||||
return { syncing, read }
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import type { WorkAction, WorkDetail, WorkItem, WorkCalendar, WorkSummary } from './workApi'
|
|
||||||
export const followAction: WorkAction = { code: 'SAVE_FOLLOWUP', label: '记录回复', targetWorkItemKey: null, target: { kind: 'WORK_COMMAND', command: 'SAVE_FOLLOWUP' } }
|
|
||||||
export function workItem(overrides: Partial<WorkItem> = {}): WorkItem {
|
|
||||||
return { workItemKey: 'work-delivery-1', version: 3, type: 'DELIVERY', flow: 'TRANSFER', title: '批次 SD-001 · ONT8 收货', businessNo: 'SD-001', containers: [{ containerBookingId: '9007199254740993', bookingNo: 'D-001', containerNo: 'TEST-CN-001' }], requirementKey: 'requirement-1', batchKey: 'batch-1', batchNo: 'SD-001', originName: '洛杉矶测试仓', destinationName: 'ONT8', planStatus: 'UNPLANNED', executionStatus: 'PENDING', reviewRequired: false, target: null, confirmed: null, actual: null, calendarDate: null, dateBasis: 'NONE', timezone: 'America/Los_Angeles', owner: { id: 'user-1', name: '测试调度' }, followupDate: '2026-10-15', overdueReasons: [], allowedActions: [followAction], nextAction: followAction, blockReasons: [], missingFields: [], ...overrides }
|
|
||||||
}
|
|
||||||
export function workDetail(overrides: Partial<WorkDetail> = {}): WorkDetail { return { item: workItem(), relatedItems: [], references: [], history: [], review: null, requirement: null, returnHandoff: null, ...overrides } }
|
|
||||||
export const workSummary: WorkSummary = { all: 20, followToday: 9, overdue: 3, undated: 7, review: 2 }
|
|
||||||
export const workCalendar: WorkCalendar = { from: '2026-09-28', to: '2026-11-08', total: 2, counts: { pending: 1, confirmed: 0, noBookingRequired: 0, review: 0, completed: 1 }, days: [{ date: '2026-10-15', total: 2, typeCounts: { DELIVERY: 1, PICKUP: 1 }, counts: { pending: 1, confirmed: 0, noBookingRequired: 0, review: 0, completed: 1 } }] }
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
import { beforeEach, expect, it, vi } from 'vitest'
|
|
||||||
import { http } from '@/shared/api/http'
|
|
||||||
import { getWorkCalendar, getWorkSummary, getWorkItems, getWorkDetail, submitWorkCommand, resolveBatchWork } from './workApi'
|
|
||||||
import { getCargoVerification, saveCargoVerification } from './cargoVerificationApi'
|
|
||||||
import { workCalendar, workDetail, workItem, workSummary } from './work.test-support'
|
|
||||||
vi.mock('@/shared/api/http', () => ({ http: { get: vi.fn(), post: vi.fn() }, unwrapApiResponse: <T>(value: { data: T }) => value.data }))
|
|
||||||
beforeEach(() => vi.clearAllMocks())
|
|
||||||
it('resolves a real batch and optional customer without manufacturing a work key', async () => {
|
|
||||||
const resolved = { batchKey: 'FBA_APPOINTMENT:40', customerId: '9007199254740999', detail: workDetail(), candidates: [] }
|
|
||||||
vi.mocked(http.get).mockResolvedValue({ data: resolved })
|
|
||||||
expect(await resolveBatchWork(resolved.batchKey, resolved.customerId)).toEqual(resolved)
|
|
||||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-work/items/resolve', { params: { batchKey: resolved.batchKey, customerId: resolved.customerId }, signal: undefined })
|
|
||||||
})
|
|
||||||
it('uses inclusive calendar dates and repeated type parameters with no duplicate API prefix', async () => {
|
|
||||||
vi.mocked(http.get).mockResolvedValue({ data: workCalendar })
|
|
||||||
const signal = new AbortController().signal
|
|
||||||
await getWorkCalendar({ from: '2026-10-01', to: '2026-10-31', flow: 'DIRECT', types: ['PICKUP', 'EMPTY_RETURN'] }, signal)
|
|
||||||
const [path, config] = vi.mocked(http.get).mock.calls[0]!
|
|
||||||
expect(path).toBe('/platform/v1/last-leg/appointment-work/calendar')
|
|
||||||
expect(config?.params.getAll('types')).toEqual(['PICKUP', 'EMPTY_RETURN'])
|
|
||||||
expect(config?.params.get('to')).toBe('2026-10-31'); expect(config?.signal).toBe(signal)
|
|
||||||
})
|
|
||||||
it('keeps global summary free of month, flow, types and page parameters', async () => {
|
|
||||||
vi.mocked(http.get).mockResolvedValue({ data: workSummary })
|
|
||||||
expect(await getWorkSummary()).toEqual(workSummary)
|
|
||||||
expect(http.get).toHaveBeenCalledExactlyOnceWith('/platform/v1/last-leg/appointment-work/summary', { signal: undefined })
|
|
||||||
})
|
|
||||||
it('preserves server totals, null work dates and long string identities', async () => {
|
|
||||||
vi.mocked(http.get).mockResolvedValue({ data: { records: [workItem()], page: '2', size: '8', total: '35', pages: '5' } })
|
|
||||||
const result = await getWorkItems({ view: 'UNDATED', page: 2, size: 8 })
|
|
||||||
expect(result.total).toBe(35); expect(result.records[0]!.calendarDate).toBeNull()
|
|
||||||
expect(result.records[0]!.containers[0]!.containerBookingId).toBe('9007199254740993')
|
|
||||||
const params = vi.mocked(http.get).mock.calls[0]![1]?.params as URLSearchParams
|
|
||||||
expect([...params.keys()]).toEqual(['view', 'page', 'size'])
|
|
||||||
})
|
|
||||||
it('encodes stable keys and forwards the immutable versioned command', async () => {
|
|
||||||
vi.mocked(http.get).mockResolvedValue({ data: workDetail() }); vi.mocked(http.post).mockResolvedValue({ data: { item: workItem(), affectedWorkItemKeys: [] } })
|
|
||||||
await getWorkDetail('work/ORDER:1')
|
|
||||||
const command = { command: 'CONFIRM_ROUTE' as const, expectedVersion: 3, idempotencyKey: 'same-command', payload: { flow: 'DIRECT' as const, reason: null } }
|
|
||||||
await submitWorkCommand('work/ORDER:1', command)
|
|
||||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-work/items/work%2FORDER%3A1/commands', command)
|
|
||||||
})
|
|
||||||
it('does not turn upstream failures into an empty calendar or zero summary', async () => {
|
|
||||||
vi.mocked(http.get).mockRejectedValue(new Error('unavailable'))
|
|
||||||
await expect(getWorkSummary()).rejects.toThrow('unavailable')
|
|
||||||
await expect(getWorkCalendar({ from: '2026-10-01', to: '2026-10-31' })).rejects.toThrow('unavailable')
|
|
||||||
})
|
|
||||||
it('scopes cargo verification to its explicit customer and never coerces unknown allocation to zero', async () => {
|
|
||||||
const source = { sourceKey: 'BOOKING:B/1', customerId: '9007199254740995', destinationKey: 'FBA:ONT8' }
|
|
||||||
vi.mocked(http.get).mockResolvedValue({ data: { availablePackages: null, sourceChanged: true } })
|
|
||||||
const context = await getCargoVerification(source); expect(context.availablePackages).toBeNull()
|
|
||||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/appointment-planning/sources/BOOKING%3AB%2F1/cargo-verification', { params: { customerId: source.customerId, destinationKey: source.destinationKey } })
|
|
||||||
const request = { destinationKey: source.destinationKey, expectedSourceVersion: null, expectedVersion: 0, packageCount: null, shipmentReferences: ['FBA-TEST'], remark: null, idempotencyKey: 'verify-1' }
|
|
||||||
vi.mocked(http.post).mockResolvedValue({ data: { version: 1 } }); await saveCargoVerification(source, request)
|
|
||||||
expect(http.post).toHaveBeenCalledWith(expect.stringContaining('/cargo-verification'), request, { params: { customerId: source.customerId } })
|
|
||||||
})
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
|
||||||
|
|
||||||
export const workTypes = ['PICKUP', 'WAREHOUSE_RECEIPT', 'DELIVERY', 'TRANSPORT', 'EMPTY_RETURN'] as const
|
|
||||||
export type WorkType = typeof workTypes[number] | 'ROUTE'
|
|
||||||
export type WorkFlow = 'TRANSFER' | 'DIRECT' | 'UNKNOWN'
|
|
||||||
export type WorkView = 'ALL' | 'FOLLOW_TODAY' | 'OVERDUE' | 'UNDATED' | 'REVIEW'
|
|
||||||
export type WorkBucket = 'PENDING' | 'CONFIRMED' | 'NO_BOOKING_REQUIRED' | 'REVIEW' | 'COMPLETED'
|
|
||||||
export interface WorkSlot { date: string; startTime: string | null; endDate: string | null; endTime: string | null; timezone: string | null }
|
|
||||||
export const workCommands = ['CONFIRM_ROUTE', 'SAVE_FOLLOWUP', 'RESOLVE_REVIEW', 'SAVE_REQUIREMENT', 'HANDOFF_RETURN', 'ACCEPT_RETURN'] as const
|
|
||||||
export type WorkCommandName = typeof workCommands[number]
|
|
||||||
export const actionCodes = ['VIEW_DETAIL', 'SAVE_PLAN', 'REQUEST_BOOKING', 'RECORD_CONFIRMATION', 'CHANGE_BOOKING', 'CANCEL_BOOKING', 'VERIFY_CARGO', 'EDIT_BATCH', 'ARRANGE_TRANSPORT', 'RECORD_EXECUTION', 'CONFIRM_ROUTE', 'SAVE_FOLLOWUP', 'RESOLVE_REVIEW', 'SAVE_REQUIREMENT', 'HANDOFF_RETURN', 'ACCEPT_RETURN', 'VIEW_HISTORY'] as const
|
|
||||||
export interface SourceReference { customerId: string; sourceKey: string; destinationKey: string | null }
|
|
||||||
export interface BusinessReference { kind: string; key: string; businessNo: string | null; label: string }
|
|
||||||
export type ActionTarget =
|
|
||||||
| { kind: 'WORK_COMMAND'; command: WorkCommandName }
|
|
||||||
| { kind: 'CARGO_VERIFICATION'; source: SourceReference }
|
|
||||||
| { kind: 'FBA_APPOINTMENT'; appointmentId: string | null; batchKey: string | null; sources: SourceReference[] }
|
|
||||||
| { kind: 'FIRSTLEG_CONTAINER'; containerBookingId: string }
|
|
||||||
| { kind: 'FLEET_TRIP'; tripId: string | null; batchKeys: string[] }
|
|
||||||
| { kind: 'WAREHOUSE_RECEIPT'; inboundPlanId: string | null; inboundPlanNo: string | null; customerId: string | null; containerBookingId: string }
|
|
||||||
| { kind: 'READ_ONLY'; references: BusinessReference[] }
|
|
||||||
export interface WorkAction { code: typeof actionCodes[number]; label: string; targetWorkItemKey: string | null; target: ActionTarget }
|
|
||||||
export interface Responsibility { kind: 'USER' | 'SUPPLIER' | 'EXTERNAL'; id: string | null; name: string }
|
|
||||||
export interface WorkItem {
|
|
||||||
workItemKey: string; version: number; type: WorkType; flow: WorkFlow
|
|
||||||
title: string; businessNo: string | null; containers: Array<{ containerBookingId: string; bookingNo: string | null; containerNo: string | null }>
|
|
||||||
requirementKey: string | null; batchKey: string | null; batchNo: string | null
|
|
||||||
originName: string | null; destinationName: string | null
|
|
||||||
planStatus: 'UNPLANNED' | 'TARGET_SET' | 'AWAITING_REPLY' | 'CONFIRMED' | 'NOT_REQUIRED'
|
|
||||||
executionStatus: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED'; reviewRequired: boolean
|
|
||||||
target: WorkSlot | null; confirmed: WorkSlot | null
|
|
||||||
actual: { occurredAt: string | null; localOccurredAt: string | null; timezone: string | null } | null
|
|
||||||
calendarDate: string | null; dateBasis: 'ACTUAL' | 'CONFIRMED' | 'TARGET' | 'NONE'; timezone: string | null
|
|
||||||
owner: { id: string; name: string } | null; followupDate: string | null; overdueReasons: string[]
|
|
||||||
allowedActions: WorkAction[]; nextAction: WorkAction | null; blockReasons: string[]; missingFields: string[]
|
|
||||||
}
|
|
||||||
export interface WorkDetail {
|
|
||||||
item: WorkItem; relatedItems: WorkItem[]
|
|
||||||
references: BusinessReference[]
|
|
||||||
history: Array<{ occurredAt: string; operatorName: string | null; action: string; summary: string }>
|
|
||||||
review: { version: number; reasons: string[] } | null
|
|
||||||
requirement: { bookingRequired: boolean; receivingRequirements: string; reason: string | null } | null
|
|
||||||
returnHandoff: { version: number; from: Responsibility; to: Responsibility; status: 'PENDING_ACCEPTANCE' | 'ACCEPTED'; reason: string } | null
|
|
||||||
}
|
|
||||||
export interface WorkSummary { all: number; followToday: number; overdue: number; undated: number; review: number }
|
|
||||||
export interface WorkCounts { pending: number; confirmed: number; noBookingRequired: number; review: number; completed: number }
|
|
||||||
export interface WorkDay { date: string; total: number; typeCounts: Partial<Record<WorkType, number>>; counts: WorkCounts }
|
|
||||||
export interface WorkCalendar { from: string; to: string; total: number; counts: WorkCounts; days: WorkDay[] }
|
|
||||||
export interface WorkPage { records: WorkItem[]; page: number; size: number; total: number; pages: number }
|
|
||||||
export interface WorkCalendarQuery { from: string; to: string; flow?: WorkFlow; types?: WorkType[] }
|
|
||||||
export interface WorkItemsQuery { view: WorkView; page: number; size: number; date?: string; flow?: WorkFlow; types?: WorkType[]; containerBookingId?: string; bucket?: WorkBucket; keyword?: string }
|
|
||||||
export type WorkCommandPayload =
|
|
||||||
| { command: 'CONFIRM_ROUTE'; payload: { flow: 'TRANSFER' | 'DIRECT'; reason: string | null } }
|
|
||||||
| { command: 'SAVE_FOLLOWUP'; payload: { ownerId: string; followupDate: string | null; note: string } }
|
|
||||||
| { command: 'RESOLVE_REVIEW'; payload: { reviewVersion: number; note: string } }
|
|
||||||
| { command: 'SAVE_REQUIREMENT'; payload: { target: WorkSlot | null; bookingRequired: boolean; receivingRequirements: string; reason: string } }
|
|
||||||
| { command: 'HANDOFF_RETURN'; payload: { recipient: Responsibility; reason: string } }
|
|
||||||
| { command: 'ACCEPT_RETURN'; payload: { handoffVersion: number; note: string | null } }
|
|
||||||
export type WorkCommand = WorkCommandPayload & { expectedVersion: number; idempotencyKey: string }
|
|
||||||
export interface WorkCommandResult { item: WorkItem; affectedWorkItemKeys: string[] }
|
|
||||||
export interface BatchWorkResolution { batchKey: string; customerId: string | null; detail: WorkDetail | null; candidates: Array<{ customerId: string; workItemKey: string; batchNo: string | null }> }
|
|
||||||
const base = '/platform/v1/last-leg/appointment-work'
|
|
||||||
|
|
||||||
// Repeated types parameters are part of v1; Axios' default types[] syntax is not.
|
|
||||||
function params(query: WorkCalendarQuery | WorkItemsQuery) {
|
|
||||||
const result = new URLSearchParams()
|
|
||||||
for (const [key, value] of Object.entries(query)) {
|
|
||||||
if (value === undefined) continue
|
|
||||||
if (Array.isArray(value)) value.forEach(type => result.append(key, type))
|
|
||||||
else result.set(key, String(value))
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
export async function getWorkCalendar(query: WorkCalendarQuery, signal?: AbortSignal) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<WorkCalendar>, ApiEnvelope<WorkCalendar>>(`${base}/calendar`, { params: params(query), signal }))
|
|
||||||
}
|
|
||||||
export async function getWorkSummary(signal?: AbortSignal) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<WorkSummary>, ApiEnvelope<WorkSummary>>(`${base}/summary`, { signal }))
|
|
||||||
}
|
|
||||||
export async function getWorkItems(query: WorkItemsQuery, signal?: AbortSignal) {
|
|
||||||
const result = unwrapApiResponse(await http.get<ApiEnvelope<WorkPage>, ApiEnvelope<WorkPage>>(`${base}/items`, { params: params(query), signal }))
|
|
||||||
return { ...result, page: Number(result.page), size: Number(result.size), total: Number(result.total), pages: Number(result.pages) }
|
|
||||||
}
|
|
||||||
export async function getWorkDetail(key: string, signal?: AbortSignal) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<WorkDetail>, ApiEnvelope<WorkDetail>>(`${base}/items/${encodeURIComponent(key)}`, { signal }))
|
|
||||||
}
|
|
||||||
export async function resolveBatchWork(batchKey: string, customerId?: string, signal?: AbortSignal) {
|
|
||||||
return unwrapApiResponse(await http.get<ApiEnvelope<BatchWorkResolution>, ApiEnvelope<BatchWorkResolution>>(`${base}/items/resolve`, { params: { batchKey, customerId }, signal }))
|
|
||||||
}
|
|
||||||
export async function submitWorkCommand(key: string, command: WorkCommand) {
|
|
||||||
return unwrapApiResponse(await http.post<ApiEnvelope<WorkCommandResult>, ApiEnvelope<WorkCommandResult>>(`${base}/items/${encodeURIComponent(key)}/commands`, command))
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { expect, it } from 'vitest'
|
|
||||||
import { appointmentExternalTarget, appointmentReturnQuery, appointmentReturnTarget } from './workNavigation'
|
|
||||||
it('preserves the item, prerequisite stack, global scope and page through an external action', () => {
|
|
||||||
const target = appointmentExternalTarget('/overseas-master-data/trips/TR-001?tab=loading', { workAnchor: '2026-10-15', workItem: 'work:1', workOrigins: '["work:0"]', workScope: 'global', workView: 'UNDATED', workPage: '3' })
|
|
||||||
expect(target.path).toBe('/overseas-master-data/trips/TR-001'); expect(target.query.tab).toBe('loading')
|
|
||||||
const back = appointmentReturnTarget(target.query)!
|
|
||||||
const query = new URL(back, 'https://appointment.invalid').searchParams
|
|
||||||
expect(query.get('workOrigins')).toBe('["work:0"]'); expect(query.get('workPage')).toBe('3'); expect(query.get('workView')).toBe('UNDATED')
|
|
||||||
expect(appointmentReturnQuery(target.query)).toEqual({ appointmentReturn: back })
|
|
||||||
})
|
|
||||||
it.each(['https://example.com/appointment-calendar?workItem=1', '//example.com/appointment-calendar?workItem=1', '/other?workItem=1', '/appointment-calendar/../other?x=1', '/appointment-calendar?x=1#fragment'])('rejects an unrelated return destination %s', value => {
|
|
||||||
expect(appointmentReturnTarget({ appointmentReturn: value })).toBeNull()
|
|
||||||
})
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import type { LocationQuery, LocationQueryRaw } from 'vue-router'
|
|
||||||
|
|
||||||
// Accept only this application's appointment route, never an arbitrary return URL.
|
|
||||||
export function appointmentReturnTarget(query: LocationQuery): string | null {
|
|
||||||
const value = query.appointmentReturn
|
|
||||||
if (typeof value !== 'string' || value.length > 12000) return null
|
|
||||||
try {
|
|
||||||
const target = new URL(value, 'https://appointment.invalid')
|
|
||||||
return target.origin === 'https://appointment.invalid' && target.pathname === '/appointment-calendar' && value.startsWith('/appointment-calendar?') && !target.hash ? `${target.pathname}${target.search}` : null
|
|
||||||
} catch { return null }
|
|
||||||
}
|
|
||||||
export function appointmentReturnQuery(query: LocationQuery): LocationQueryRaw {
|
|
||||||
const target = appointmentReturnTarget(query)
|
|
||||||
return target ? { appointmentReturn: target } : {}
|
|
||||||
}
|
|
||||||
export function appointmentExternalTarget(path: string, context: LocationQueryRaw) {
|
|
||||||
const target = new URL(path, 'https://appointment.invalid')
|
|
||||||
const params = new URLSearchParams()
|
|
||||||
for (const [key, value] of Object.entries(context)) if (value !== undefined && value !== null) params.set(key, String(value))
|
|
||||||
const query: Record<string, string> = { ...Object.fromEntries(target.searchParams), appointmentReturn: `/appointment-calendar?${params}` }
|
|
||||||
return { path: target.pathname, query }
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import { expect, it } from 'vitest'
|
|
||||||
import { actionAllowed, actionRoute, referenceRoute, commandName, workDate, workStatus, workReason } from './workPresentation'
|
|
||||||
import { followAction, workItem } from './work.test-support'
|
|
||||||
import type { WorkAction } from './workApi'
|
|
||||||
it.each([
|
|
||||||
['SOURCE_TIMEZONE', '原业务作业地点时区待核实'],
|
|
||||||
['SOURCE_CONFIGURATION', '原货源或仓库配置待核实'],
|
|
||||||
['LASTLEG_SOURCE', '尾程货源待建立'],
|
|
||||||
['READY_WINDOW_UNVERIFIED', '货物备妥窗口待核实'],
|
|
||||||
['CARGO_QUANTITY_REVIEW', '货量或重复关联需要核对。'],
|
|
||||||
])('shows readable text for work item reason %s', (code, expected) => {
|
|
||||||
expect(workReason(code)).toBe(expected)
|
|
||||||
})
|
|
||||||
it('preserves the server explanation for an overdue or blocked work item', () => {
|
|
||||||
expect(workReason('作业日期已过,尚未完成')).toBe('作业日期已过,尚未完成')
|
|
||||||
expect(workReason('实际提柜后才能记录直送卸货')).toBe('实际提柜后才能记录直送卸货')
|
|
||||||
})
|
|
||||||
it('links original dispatch and delivery references by business number without inventing unknown routes', () => {
|
|
||||||
expect(referenceRoute({ kind: 'DISPATCH', key: 'DISPATCH:9007199254740999', businessNo: 'DS/001', label: '客户仓排车' })).toBe('/overseas-warehouse/dispatches?dispatchNo=DS%2F001')
|
|
||||||
expect(referenceRoute({ kind: 'DELIVERY', key: 'internal', businessNo: 'DL/001', label: '原派送' })).toBe('/overseas-warehouse/delivery-orders/DL%2F001')
|
|
||||||
expect(referenceRoute({ kind: 'DELIVERY', key: 'internal', businessNo: null, label: '原派送' })).toBeNull()
|
|
||||||
expect(referenceRoute({ kind: 'EXTERNAL_URL', key: 'https://example.com', businessNo: 'example', label: '未知' })).toBeNull()
|
|
||||||
})
|
|
||||||
it('shows both complete local dates for a confirmed cross-day slot', () => {
|
|
||||||
expect(workDate(workItem({ calendarDate: '2026-10-15', dateBasis: 'CONFIRMED', confirmed: { date: '2026-10-15', startTime: '23:00', endDate: '2026-10-16', endTime: '01:00', timezone: 'America/Los_Angeles' } }))).toBe('确认 2026-10-15 23:00 → 2026-10-16 01:00')
|
|
||||||
})
|
|
||||||
it('keeps executed pickup on its actual location date after the plan moves', () => {
|
|
||||||
const item = workItem({ type: 'PICKUP', dateBasis: 'ACTUAL', calendarDate: '2026-10-14', actual: { occurredAt: '2026-10-15T03:00:00Z', localOccurredAt: null, timezone: 'America/Los_Angeles' }, target: { date: '2026-10-20', startTime: null, endDate: null, endTime: null, timezone: 'America/Los_Angeles' } })
|
|
||||||
expect(workDate(item)).toContain('2026/10/14'); expect(workDate(item)).not.toContain('2026-10-20')
|
|
||||||
expect(item.target?.date).toBe('2026-10-20')
|
|
||||||
})
|
|
||||||
it('preserves original local actual and planned dates without imposing a browser or default timezone', () => {
|
|
||||||
expect(workDate(workItem({ dateBasis: 'ACTUAL', calendarDate: '2026-10-15', timezone: null, actual: { occurredAt: null, localOccurredAt: '2026-10-15T23:30:00', timezone: null } }))).toBe('实际 2026-10-15 23:30:00')
|
|
||||||
expect(workDate(workItem({ dateBasis: 'TARGET', calendarDate: '2026-10-15', timezone: null, target: { date: '2026-10-15', startTime: '23:30', endDate: '2026-10-16', endTime: '01:30', timezone: null } }))).toBe('目标 2026-10-15 23:30 → 2026-10-16 01:30')
|
|
||||||
})
|
|
||||||
it('does not turn a follow-up date into a work slot or no-booking into a confirmation', () => {
|
|
||||||
expect(workDate(workItem())).toBe('作业日期未定')
|
|
||||||
expect(workStatus(workItem({ planStatus: 'NOT_REQUIRED' }))).toBe('无需预约')
|
|
||||||
})
|
|
||||||
it('rejects unknown commands and never treats internal trip identifiers as business numbers', () => {
|
|
||||||
const unknown = { ...followAction, target: { kind: 'WORK_COMMAND', command: 'MARK_COMPLETE' } } as unknown as WorkAction
|
|
||||||
expect(commandName(unknown)).toBeNull(); expect(actionAllowed(workItem(), unknown)).toBe(false)
|
|
||||||
const trip: WorkAction = { code: 'RECORD_EXECUTION', label: '登记发车', targetWorkItemKey: null, target: { kind: 'FLEET_TRIP', tripId: 'internal-1', batchKeys: [] } }
|
|
||||||
expect(actionRoute(trip, [])).toBeNull()
|
|
||||||
expect(actionRoute(trip, [{ kind: 'FLEET_TRIP', key: 'internal-1', businessNo: 'TR/2026-1', label: '车次' }])).toBe('/overseas-master-data/trips/TR%2F2026-1')
|
|
||||||
})
|
|
||||||
it('opens the original container operation with a real source selection for direct unloading', () => {
|
|
||||||
const action: WorkAction = { code: 'RECORD_EXECUTION', label: '登记执行', targetWorkItemKey: null, target: { kind: 'FIRSTLEG_CONTAINER', containerBookingId: '9007199254740993' } }
|
|
||||||
expect(actionRoute(action, [], workItem({ type: 'PICKUP' }))).toBe('/container-loading/overseas/9007199254740993?action=pickup')
|
|
||||||
expect(actionRoute(action, [], workItem({ type: 'EMPTY_RETURN' }))).toBe('/container-loading/overseas/9007199254740993?action=empty-return')
|
|
||||||
expect(actionRoute(action, [], workItem({ type: 'DELIVERY', flow: 'DIRECT', requirementKey: 'INBOUND:9007199254740999' }))).toBe('/container-loading/overseas/9007199254740993?action=direct-unload&requirementKey=INBOUND%3A9007199254740999')
|
|
||||||
})
|
|
||||||
it('routes receiving by plan business number plus customer scope, never the internal plan ID', () => {
|
|
||||||
const action: WorkAction = { code: 'RECORD_EXECUTION', label: '查看接仓', targetWorkItemKey: null, target: { kind: 'WAREHOUSE_RECEIPT', inboundPlanId: 'internal-plan', inboundPlanNo: 'IP/TEST', customerId: '9007199254740999', containerBookingId: 'container-1' } }
|
|
||||||
expect(actionRoute(action, [])).toBe('/overseas-warehouse/inbound-orders/IP%2FTEST?customerId=9007199254740999')
|
|
||||||
expect(actionRoute({ ...action, target: { kind: 'WAREHOUSE_RECEIPT', inboundPlanId: null, inboundPlanNo: null, customerId: null, containerBookingId: 'container-1' } }, [])).toBeNull()
|
|
||||||
})
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import type { WorkAction, WorkItem, WorkType, WorkView, BusinessReference } from './workApi'
|
|
||||||
import { actionCodes, workCommands, type WorkCommandName } from './workApi'
|
|
||||||
export const typeLabels: Record<WorkType, string> = { PICKUP: '提柜', WAREHOUSE_RECEIPT: '接仓卸柜', DELIVERY: '送仓 / FBA', TRANSPORT: '用车计划', EMPTY_RETURN: '还空柜', ROUTE: '确认路线' }
|
|
||||||
export const flowLabels = { TRANSFER: '海外仓中转', DIRECT: '整柜直送', UNKNOWN: '路线待确认' }
|
|
||||||
export const viewLabels: Record<WorkView, string> = { ALL: '全部待办', FOLLOW_TODAY: '今日需跟进', OVERDUE: '已超期', UNDATED: '未定日期', REVIEW: '需复核' }
|
|
||||||
export function workReason(reason: string) {
|
|
||||||
switch (reason) {
|
|
||||||
case 'SOURCE_TIMEZONE': return '原业务作业地点时区待核实'
|
|
||||||
case 'SOURCE_CONFIGURATION': return '原货源或仓库配置待核实'
|
|
||||||
case 'LASTLEG_SOURCE': return '尾程货源待建立'
|
|
||||||
case 'READY_WINDOW_UNVERIFIED': return '货物备妥窗口待核实'
|
|
||||||
case 'CARGO_QUANTITY_REVIEW': return '货量或重复关联需要核对。'
|
|
||||||
default: return reason
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export function workStatus(item: WorkItem) {
|
|
||||||
if (item.executionStatus === 'COMPLETED') return '已完成'
|
|
||||||
if (item.reviewRequired) return '需复核'
|
|
||||||
if (item.executionStatus === 'IN_PROGRESS') return '执行中'
|
|
||||||
return { UNPLANNED: '待安排', TARGET_SET: '已有目标日期', AWAITING_REPLY: '等待回复', CONFIRMED: '已落实', NOT_REQUIRED: '无需预约' }[item.planStatus]
|
|
||||||
}
|
|
||||||
export function localInstant(value: string, timezone: string | null) {
|
|
||||||
if (!timezone) return '作业地点时区待核实'
|
|
||||||
try { return new Intl.DateTimeFormat('zh-CN', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(new Date(value)) }
|
|
||||||
catch { return '实际时间待核实' }
|
|
||||||
}
|
|
||||||
export function workDate(item: WorkItem) {
|
|
||||||
if (item.dateBasis === 'ACTUAL') {
|
|
||||||
const actual = item.actual
|
|
||||||
if (actual?.localOccurredAt) return `实际 ${actual.localOccurredAt.replace('T', ' ')}`
|
|
||||||
return actual?.occurredAt ? `实际 ${localInstant(actual.occurredAt, actual.timezone)}` : '实际时间待核实'
|
|
||||||
}
|
|
||||||
if (item.dateBasis === 'NONE' || !item.calendarDate) return '作业日期未定'
|
|
||||||
const slot = item.dateBasis === 'CONFIRMED' ? item.confirmed : item.target
|
|
||||||
const end = slot?.endDate && slot.endTime ? ` → ${slot.endDate} ${slot.endTime}` : ''
|
|
||||||
return `${item.dateBasis === 'CONFIRMED' ? '确认' : '目标'} ${slot?.date || item.calendarDate}${slot?.startTime ? ` ${slot.startTime}${end}` : ' · 时段未定'}`
|
|
||||||
}
|
|
||||||
export function commandName(action: WorkAction): WorkCommandName | null {
|
|
||||||
return action.target.kind === 'WORK_COMMAND' && workCommands.includes(action.target.command as WorkCommandName) ? action.target.command as WorkCommandName : null
|
|
||||||
}
|
|
||||||
export function sameAction(a: WorkAction, b: WorkAction) {
|
|
||||||
return a.code === b.code && a.targetWorkItemKey === b.targetWorkItemKey && JSON.stringify(a.target) === JSON.stringify(b.target)
|
|
||||||
}
|
|
||||||
export function actionAllowed(item: WorkItem, action: WorkAction) { return actionCodes.includes(action.code) && item.allowedActions.some(candidate => sameAction(candidate, action)) }
|
|
||||||
export function referenceRoute(reference: BusinessReference) {
|
|
||||||
if (!reference.businessNo) return null
|
|
||||||
if (reference.kind === 'DISPATCH') return `/overseas-warehouse/dispatches?dispatchNo=${encodeURIComponent(reference.businessNo)}`
|
|
||||||
if (reference.kind === 'DELIVERY') return `/overseas-warehouse/delivery-orders/${encodeURIComponent(reference.businessNo)}`
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
export function actionRoute(action: WorkAction, references: BusinessReference[], item?: WorkItem) {
|
|
||||||
// Only known application routes. No server-provided URL or method is executed.
|
|
||||||
switch (action.target.kind) {
|
|
||||||
case 'FIRSTLEG_CONTAINER': {
|
|
||||||
const path = `/container-loading/overseas/${encodeURIComponent(action.target.containerBookingId)}`
|
|
||||||
if (!item || action.code === 'VIEW_DETAIL' || action.code === 'VIEW_HISTORY') return path
|
|
||||||
if (item.type === 'PICKUP') return `${path}?action=pickup`
|
|
||||||
if (item.type === 'EMPTY_RETURN' && action.code === 'RECORD_EXECUTION') return `${path}?action=empty-return`
|
|
||||||
if (item.type === 'DELIVERY' && item.flow === 'DIRECT' && action.code === 'RECORD_EXECUTION') return `${path}?action=direct-unload${item.requirementKey ? `&requirementKey=${encodeURIComponent(item.requirementKey)}` : ''}`
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
case 'FLEET_TRIP': {
|
|
||||||
const id = action.target.tripId
|
|
||||||
const trip = references.find(ref => ref.kind === 'FLEET_TRIP' && ref.key === id)
|
|
||||||
return trip?.businessNo ? `/overseas-master-data/trips/${encodeURIComponent(trip.businessNo)}` : null
|
|
||||||
}
|
|
||||||
case 'WAREHOUSE_RECEIPT': return action.target.inboundPlanNo && action.target.customerId ? `/overseas-warehouse/inbound-orders/${encodeURIComponent(action.target.inboundPlanNo)}?customerId=${encodeURIComponent(action.target.customerId)}` : null
|
|
||||||
default: return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
# Admin 操作日志与审计模块指引
|
|
||||||
|
|
||||||
## 路径基准与读取顺序
|
|
||||||
|
|
||||||
- 本文件适用于 `src/modules/audit/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`。
|
|
||||||
- 本模块**没有独立页面**:审计日志是客户详情里的内嵌面板(`components/CustomerAuditLogsPanel.vue`),查询接口在 `api/platformAudit.ts`。
|
|
||||||
- 后端查 `audit-service/`(`PlatformAuditLogController`、`AuditLogQueryService`);若是“操作人没被记录”,还要查采集侧 `common-audit/`(`BusinessAuditAspect.java`、`AuditEvent.java`)。
|
|
||||||
|
|
||||||
## 页面与入口
|
|
||||||
|
|
||||||
| 目标 | 入口 | API 与后端 |
|
|
||||||
|---|---|---|
|
|
||||||
| 客户详情内的操作日志面板、分页与详情 | `components/CustomerAuditLogsPanel.vue`(props:`customerId`、`customerName`) | `api/platformAudit.ts` 的 `listPlatformAuditLogs`、`getPlatformAuditLog`;`audit-service/` |
|
|
||||||
| 日志字段展示、时间与文案映射 | `presentation.ts` | 服务端返回结构 |
|
|
||||||
| 日志列表/详情的对外类型 | `index.ts` | `audit-service` DTO |
|
|
||||||
| 操作人缺失、字段为空 | 面板空态与列定义 | 先查 `common-audit/` 是否采集该字段,再查 `audit-service/` 摄取 DTO 与表结构 |
|
|
||||||
|
|
||||||
## 关键边界
|
|
||||||
|
|
||||||
- 列表不返回变更前后快照,详情才返回已脱敏 JSON;不要在列表里展开完整 payload。
|
|
||||||
- 客户账号不得访问平台审计查询;面板只在平台侧客户详情内使用。
|
|
||||||
- 审计字段缺失属于“采集侧漏采”或“查询侧未映射”,两者分属 `common-audit/` 与 `audit-service/`,不要只改前端展示。
|
|
||||||
- 审计链路故障不得阻塞核心交易,前端也不得据此推断业务失败。
|
|
||||||
|
|
||||||
## 验证
|
|
||||||
|
|
||||||
- 定向:`pnpm test src/modules/audit/<目标测试>`;字段或查询变化同时核对 `audit-service` 的查询接口与表结构。
|
|
||||||
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
|
|
||||||
@@ -1,22 +1,17 @@
|
|||||||
import ElementPlus from 'element-plus'
|
import ElementPlus from 'element-plus'
|
||||||
import { createPinia, setActivePinia } from 'pinia'
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
import { useAuthStore } from '@/core/auth/auth'
|
||||||
import AppDrawer from '@/shared/components/AppDrawer.vue'
|
|
||||||
import QueryToolbar from '@/shared/components/QueryToolbar.vue'
|
import QueryToolbar from '@/shared/components/QueryToolbar.vue'
|
||||||
import { getPlatformAuditLog, listPlatformAuditLogs, type PlatformAuditLogDetail } from '../api/platformAudit'
|
import { getPlatformAuditLog, listPlatformAuditLogs } from '../api/platformAudit'
|
||||||
import CustomerAuditLogsPanel from './CustomerAuditLogsPanel.vue'
|
import CustomerAuditLogsPanel from './CustomerAuditLogsPanel.vue'
|
||||||
|
|
||||||
vi.mock('../api/platformAudit', () => ({ getPlatformAuditLog: vi.fn(), listPlatformAuditLogs: vi.fn() }))
|
vi.mock('../api/platformAudit', () => ({ getPlatformAuditLog: vi.fn(), listPlatformAuditLogs: vi.fn() }))
|
||||||
|
|
||||||
const row = { id: '1', eventId: 'evt', eventType: 'PLATFORM_TENANT_UPDATE', resourceType: 'TENANT', resourceId: '8', description: '编辑客户', accountId: '8', operatorTenantId: '0', userId: '9', username: 'platform_admin', appCode: 'ADMIN', clientType: 'WEB', clientIp: '127.0.0.1', requestId: 'req', traceId: 'trace', serviceName: 'iam-service', success: true, errorCode: null, errorMessage: null, occurredAt: '2026-08-13T01:00:00Z', createdAt: '2026-08-13T09:00:00' }
|
const row = { id: '1', eventId: 'evt', eventType: 'PLATFORM_TENANT_UPDATE', resourceType: 'TENANT', resourceId: '8', description: '编辑客户', accountId: '8', operatorTenantId: '0', userId: '9', username: 'platform_admin', appCode: 'ADMIN', clientType: 'WEB', clientIp: '127.0.0.1', requestId: 'req', traceId: 'trace', serviceName: 'iam-service', success: true, errorCode: null, errorMessage: null, occurredAt: '2026-08-13T01:00:00Z', createdAt: '2026-08-13T09:00:00' }
|
||||||
|
|
||||||
const detail: PlatformAuditLogDetail = { ...row, resourceId: '9007199254740993123', httpMethod: 'PUT', requestUri: '/tenants/8', durationMs: 12, beforeData: '{"name":"旧名称"}', afterData: '{"name":"新名称"}' }
|
|
||||||
|
|
||||||
enableAutoUnmount(afterEach)
|
|
||||||
|
|
||||||
function mountPanel(permissions: string[]) {
|
function mountPanel(permissions: string[]) {
|
||||||
const pinia = createPinia(); setActivePinia(pinia)
|
const pinia = createPinia(); setActivePinia(pinia)
|
||||||
const auth = useAuthStore(); auth.token = 'token'; auth.permissions = permissions
|
const auth = useAuthStore(); auth.token = 'token'; auth.permissions = permissions
|
||||||
@@ -25,7 +20,7 @@ function mountPanel(permissions: string[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('CustomerAuditLogsPanel', () => {
|
describe('CustomerAuditLogsPanel', () => {
|
||||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(getPlatformAuditLog).mockResolvedValue(detail); vi.mocked(listPlatformAuditLogs).mockResolvedValue({ records: [row], page: 1, size: 20, total: 1, pages: 1 }) })
|
beforeEach(() => { vi.clearAllMocks(); vi.mocked(listPlatformAuditLogs).mockResolvedValue({ records: [row], page: 1, size: 20, total: 1, pages: 1 }) })
|
||||||
|
|
||||||
it('queries logs with the current customer id', async () => {
|
it('queries logs with the current customer id', async () => {
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
||||||
@@ -96,24 +91,17 @@ describe('CustomerAuditLogsPanel', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('loads detail and formats json snapshots', async () => {
|
it('loads detail and formats json snapshots', async () => {
|
||||||
const privateId = '9007199254740993123'
|
vi.mocked(getPlatformAuditLog).mockResolvedValue({ ...row, eventType: 'INBOUND_MEASURE_APPROVE', resourceType: 'INBOUND_MEASUREMENT', serviceName: 'firstleg-service', httpMethod: 'PUT', requestUri: '/tenants/8', clientIp: '127.0.0.1', durationMs: 12, beforeData: '{"name":"旧名称"}', afterData: '{"name":"新名称"}' })
|
||||||
vi.mocked(listPlatformAuditLogs).mockResolvedValue({ records: [{ ...row, id: privateId }], page: 1, size: 20, total: 1, pages: 1 })
|
|
||||||
vi.mocked(getPlatformAuditLog).mockResolvedValue({ ...detail, id: privateId, eventType: 'INBOUND_MEASURE_APPROVE', resourceType: 'INBOUND_MEASUREMENT', serviceName: 'firstleg-service', httpMethod: 'PUT', requestUri: '/tenants/8', clientIp: '127.0.0.1', durationMs: 12, beforeData: '{"name":"旧名称"}', afterData: '{"name":"新名称"}' })
|
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
||||||
await wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').trigger('click'); await flushPromises()
|
await wrapper.get('button[aria-label="查看操作日志1详情"]').trigger('click'); await flushPromises()
|
||||||
expect(getPlatformAuditLog).toHaveBeenCalledWith(privateId)
|
expect(getPlatformAuditLog).toHaveBeenCalledWith('1')
|
||||||
expect(wrapper.text()).toContain('旧名称')
|
expect(wrapper.text()).toContain('旧名称')
|
||||||
expect(wrapper.text()).toContain('新名称')
|
expect(wrapper.text()).toContain('新名称')
|
||||||
expect(wrapper.text()).toContain('入库测量审核通过')
|
expect(wrapper.text()).toContain('入库测量审核通过')
|
||||||
expect(wrapper.text()).toContain('入库测量')
|
expect(wrapper.text()).toContain('入库测量')
|
||||||
expect(wrapper.text()).toContain('头程履约服务')
|
expect(wrapper.text()).toContain('头程履约服务')
|
||||||
expect(wrapper.text()).toContain('更新')
|
expect(wrapper.text()).toContain('更新')
|
||||||
expect(wrapper.find('.audit-detail-table').exists()).toBe(true)
|
expect(wrapper.find('.audit-detail-grid').exists()).toBe(true)
|
||||||
expect(wrapper.findComponent(AppDrawer).props()).toMatchObject({ title: '操作日志详情 · 柏悦物流', size: 'min(920px, 96vw)', showFooter: false })
|
|
||||||
expect(wrapper.find('.audit-detail-table').text()).toContain('req')
|
|
||||||
expect(wrapper.find('.audit-detail-table').text()).toContain('trace')
|
|
||||||
expect(wrapper.find('.audit-detail-table').text()).not.toContain(privateId)
|
|
||||||
expect(wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').attributes('aria-label')).not.toContain(privateId)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('loads the selected audit page', async () => {
|
it('loads the selected audit page', async () => {
|
||||||
@@ -143,100 +131,4 @@ describe('CustomerAuditLogsPanel', () => {
|
|||||||
expect(listPlatformAuditLogs).toHaveBeenCalledTimes(1)
|
expect(listPlatformAuditLogs).toHaveBeenCalledTimes(1)
|
||||||
expect(listPlatformAuditLogs).toHaveBeenCalledWith({ accountId: '9', page: 1, size: 20, keyword: undefined, success: undefined, occurredFrom: undefined, occurredTo: undefined })
|
expect(listPlatformAuditLogs).toHaveBeenCalledWith({ accountId: '9', page: 1, size: 20, keyword: undefined, success: undefined, occurredFrom: undefined, occurredTo: undefined })
|
||||||
})
|
})
|
||||||
it('preserves failure details and complete long or non-json snapshots as text', async () => {
|
|
||||||
const longText = '长内容'.repeat(1200)
|
|
||||||
const raw = '<script>原始内容</script>\n不是JSON'
|
|
||||||
vi.mocked(getPlatformAuditLog).mockResolvedValue({ ...detail, success: false, errorMessage: '数据版本冲突', beforeData: JSON.stringify({ note: longText }), afterData: raw })
|
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
|
||||||
await wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').trigger('click'); await flushPromises()
|
|
||||||
const drawer = wrapper.findComponent(AppDrawer)
|
|
||||||
expect(drawer.text()).toContain('操作失败')
|
|
||||||
expect(drawer.get('[role="alert"]').text()).toContain('数据版本冲突')
|
|
||||||
const snapshots = drawer.findAll('.density-code-block')
|
|
||||||
expect(snapshots[0].text()).toBe(JSON.stringify({ note: longText }, null, 2))
|
|
||||||
expect(snapshots[1].text()).toBe(raw)
|
|
||||||
expect(drawer.find('script').exists()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps missing snapshots compact and a zero duration visible', async () => {
|
|
||||||
vi.mocked(getPlatformAuditLog).mockResolvedValue({ ...detail, success: false, errorMessage: null, errorCode: 'OPERATION_CONFLICT', durationMs: 0, beforeData: '', afterData: null, requestId: null, traceId: null })
|
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
|
||||||
await wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.findAll('.density-code-block').map(snapshot => snapshot.text())).toEqual(['无', '无'])
|
|
||||||
expect(wrapper.find('.audit-detail-table').text()).toContain('0 ms')
|
|
||||||
expect(wrapper.find('.audit-detail-table').text()).not.toContain('链路标识')
|
|
||||||
expect(wrapper.find('.audit-detail-table').text()).toContain('OPERATION_CONFLICT')
|
|
||||||
expect(wrapper.findComponent(AppDrawer).get('[role="alert"]').text()).toContain('操作失败,请查看诊断信息')
|
|
||||||
expect(wrapper.findComponent(AppDrawer).get('[role="alert"]').text()).not.toContain('OPERATION_CONFLICT')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('retries the selected log after a detail request failure', async () => {
|
|
||||||
vi.mocked(getPlatformAuditLog).mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce(detail)
|
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
|
||||||
await wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').trigger('click'); await flushPromises()
|
|
||||||
expect(wrapper.findComponent(AppDrawer).text()).toContain('详情加载失败')
|
|
||||||
await wrapper.findComponent(AppDrawer).get('.load-error-state button').trigger('click'); await flushPromises()
|
|
||||||
expect(vi.mocked(getPlatformAuditLog).mock.calls).toEqual([['1'], ['1']])
|
|
||||||
expect(wrapper.findComponent(AppDrawer).text()).toContain('新名称')
|
|
||||||
expect(wrapper.findComponent(AppDrawer).find('.load-error-state').exists()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each(['resolve', 'reject'] as const)('ignores a late %s from the previously selected log', async outcome => {
|
|
||||||
let finish!: (value: PlatformAuditLogDetail) => void
|
|
||||||
let fail!: (reason: Error) => void
|
|
||||||
const previous = new Promise<PlatformAuditLogDetail>((resolve, reject) => { finish = resolve; fail = reject })
|
|
||||||
vi.mocked(listPlatformAuditLogs).mockResolvedValue({ records: [row, { ...row, id: '2', description: '第二条记录' }], page: 1, size: 20, total: 2, pages: 1 })
|
|
||||||
vi.mocked(getPlatformAuditLog).mockImplementation(id => id === '1' ? previous : Promise.resolve({ ...detail, id: '2', description: '第二条详情' }))
|
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
|
||||||
const actions = wrapper.findAll('.el-table__body button[aria-label^="查看操作日志:"]')
|
|
||||||
await actions[0].trigger('click'); await flushPromises()
|
|
||||||
await actions[1].trigger('click'); await flushPromises()
|
|
||||||
if (outcome === 'resolve') finish({ ...detail, description: '不应重新展示的旧详情' })
|
|
||||||
else fail(new Error('旧请求失败'))
|
|
||||||
await flushPromises()
|
|
||||||
expect(wrapper.findComponent(AppDrawer).props('loading')).toBe(false)
|
|
||||||
expect(wrapper.findComponent(AppDrawer).text()).toContain('第二条详情')
|
|
||||||
expect(wrapper.findComponent(AppDrawer).text()).not.toContain('不应重新展示的旧详情')
|
|
||||||
expect(wrapper.findComponent(AppDrawer).find('.load-error-state').exists()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('closes and clears pending detail when switching customers', async () => {
|
|
||||||
let finish!: (value: PlatformAuditLogDetail) => void
|
|
||||||
vi.mocked(getPlatformAuditLog).mockReturnValueOnce(new Promise(resolve => { finish = resolve }))
|
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
|
||||||
await wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').trigger('click'); await flushPromises()
|
|
||||||
await wrapper.setProps({ customerId: '9', customerName: '另一客户' }); await flushPromises()
|
|
||||||
finish(detail); await flushPromises()
|
|
||||||
expect(wrapper.findComponent(AppDrawer).props('modelValue')).toBe(false)
|
|
||||||
expect(wrapper.find('.audit-detail-table').exists()).toBe(false)
|
|
||||||
expect(listPlatformAuditLogs).toHaveBeenLastCalledWith(expect.objectContaining({ accountId: '9' }))
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ignores pending responses after closing and permits a fresh reopen', async () => {
|
|
||||||
let finish!: (value: PlatformAuditLogDetail) => void
|
|
||||||
vi.mocked(getPlatformAuditLog).mockReturnValueOnce(new Promise(resolve => { finish = resolve }))
|
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
|
||||||
await wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').trigger('click'); await flushPromises()
|
|
||||||
wrapper.findComponent(AppDrawer).vm.$emit('update:modelValue', false)
|
|
||||||
await flushPromises()
|
|
||||||
finish({ ...detail, description: '过期详情' }); await flushPromises()
|
|
||||||
expect(wrapper.find('.audit-detail-table').exists()).toBe(false)
|
|
||||||
await wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').trigger('click'); await flushPromises()
|
|
||||||
expect(getPlatformAuditLog).toHaveBeenCalledTimes(2)
|
|
||||||
expect(wrapper.findComponent(AppDrawer).text()).toContain('新名称')
|
|
||||||
expect(wrapper.findComponent(AppDrawer).text()).not.toContain('过期详情')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clears detail when audit permission is revoked', async () => {
|
|
||||||
const wrapper = mountPanel(['platform:audit:list']); await flushPromises()
|
|
||||||
await wrapper.get('.el-table__body button[aria-label^="查看操作日志:"]').trigger('click'); await flushPromises()
|
|
||||||
useAuthStore().permissions = []
|
|
||||||
useAccessPreviewStore().initializeAfterLogin()
|
|
||||||
await flushPromises()
|
|
||||||
expect(wrapper.findComponent(AppDrawer).props('modelValue')).toBe(false)
|
|
||||||
expect(wrapper.find('.audit-detail-table').exists()).toBe(false)
|
|
||||||
expect(wrapper.text()).toContain('暂无操作日志查看权限')
|
|
||||||
expect(listPlatformAuditLogs).toHaveBeenCalledTimes(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
import '@/styles/adminDensity.css'
|
import '@/styles/adminDensity.css'
|
||||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
import { ref, watch } from 'vue'
|
||||||
import { ScrollText } from '@lucide/vue'
|
import { CircleCheck, CircleX, ScrollText } from '@lucide/vue'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||||
@@ -25,9 +24,6 @@ const detailOpen = ref(false)
|
|||||||
const detailLoading = ref(false)
|
const detailLoading = ref(false)
|
||||||
const detail = ref<PlatformAuditLogDetail | null>(null)
|
const detail = ref<PlatformAuditLogDetail | null>(null)
|
||||||
const detailError = ref<ApiErrorDetails | null>(null)
|
const detailError = ref<ApiErrorDetails | null>(null)
|
||||||
const selectedLogId = ref<string | null>(null)
|
|
||||||
const detailTitle = computed(() => props.customerName.trim() ? `操作日志详情 · ${props.customerName.trim()}` : '操作日志详情')
|
|
||||||
let detailRequestSerial = 0
|
|
||||||
const emptyFilters = (): QueryModel => ({ keyword: '', success: '', occurredRange: [] })
|
const emptyFilters = (): QueryModel => ({ keyword: '', success: '', occurredRange: [] })
|
||||||
const filters = ref<QueryModel>(emptyFilters())
|
const filters = ref<QueryModel>(emptyFilters())
|
||||||
const appliedFilters = ref<QueryModel>(emptyFilters())
|
const appliedFilters = ref<QueryModel>(emptyFilters())
|
||||||
@@ -84,7 +80,7 @@ async function load() {
|
|||||||
rows.value = []
|
rows.value = []
|
||||||
total.value = 0
|
total.value = 0
|
||||||
loadError.value = null
|
loadError.value = null
|
||||||
if (!customerId || !access.can('platform:audit:list')) { loading.value = false; return }
|
if (!customerId || !access.can('platform:audit:list')) return
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const result = await listPlatformAuditLogs(toQuery(customerId))
|
const result = await listPlatformAuditLogs(toQuery(customerId))
|
||||||
@@ -108,45 +104,17 @@ function applyFilters(model: QueryModel) {
|
|||||||
else page.value = 1
|
else page.value = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearDetail() {
|
async function openDetail(row: PlatformAuditLogListItem) {
|
||||||
detailRequestSerial += 1
|
detailOpen.value = true
|
||||||
selectedLogId.value = null
|
|
||||||
detailOpen.value = false
|
|
||||||
detailLoading.value = false
|
|
||||||
detail.value = null
|
|
||||||
detailError.value = null
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadDetail() {
|
|
||||||
const logId = selectedLogId.value
|
|
||||||
const customerId = props.customerId.trim()
|
|
||||||
if (!logId || !detailOpen.value || !access.can('platform:audit:list')) return
|
|
||||||
const serial = ++detailRequestSerial
|
|
||||||
const isCurrent = () => serial === detailRequestSerial && customerId === props.customerId.trim() && detailOpen.value
|
|
||||||
detailLoading.value = true
|
detailLoading.value = true
|
||||||
detail.value = null
|
detail.value = null
|
||||||
detailError.value = null
|
detailError.value = null
|
||||||
try {
|
try { detail.value = await getPlatformAuditLog(row.id) }
|
||||||
const result = await getPlatformAuditLog(logId)
|
catch (error) { detailError.value = getApiErrorDetails(error, '操作日志详情加载失败,请稍后重试') }
|
||||||
if (isCurrent()) detail.value = result
|
finally { detailLoading.value = false }
|
||||||
} catch (error) {
|
|
||||||
if (isCurrent()) detailError.value = getApiErrorDetails(error, '操作日志详情加载失败,请稍后重试')
|
|
||||||
} finally {
|
|
||||||
if (isCurrent()) detailLoading.value = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openDetail(row: PlatformAuditLogListItem) {
|
watch(() => props.customerId, () => {
|
||||||
selectedLogId.value = row.id
|
|
||||||
detailOpen.value = true
|
|
||||||
await loadDetail()
|
|
||||||
}
|
|
||||||
|
|
||||||
watch(detailOpen, open => { if (!open) clearDetail() })
|
|
||||||
onBeforeUnmount(() => { requestSerial += 1; detailRequestSerial += 1 })
|
|
||||||
|
|
||||||
watch([() => props.customerId, () => access.can('platform:audit:list')], () => {
|
|
||||||
clearDetail()
|
|
||||||
filters.value = emptyFilters()
|
filters.value = emptyFilters()
|
||||||
appliedFilters.value = emptyFilters()
|
appliedFilters.value = emptyFilters()
|
||||||
if (page.value === 1) void load()
|
if (page.value === 1) void load()
|
||||||
@@ -158,50 +126,48 @@ watch([page, pageSize], ([nextPage, nextSize], [previousPage, previousSize]) =>
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="customer-audit-panel admin-density admin-workbench">
|
<section class="customer-audit-panel admin-density">
|
||||||
<div class="panel-title"><div><h2>操作日志</h2></div><ScrollText :size="19" /></div>
|
<div class="panel-title"><div><h2>操作日志</h2><p>{{ customerName }}已归属当前客户的档案与业务操作记录</p></div><ScrollText :size="19" /></div>
|
||||||
<div v-if="!access.can('platform:audit:list')" class="module-empty"><ScrollText :size="30" /><strong>暂无操作日志查看权限</strong><p>请联系管理员开通平台操作日志查看权限。</p></div>
|
<div v-if="!access.can('platform:audit:list')" class="module-empty"><ScrollText :size="30" /><strong>暂无操作日志查看权限</strong><p>请联系管理员开通平台操作日志查看权限。</p></div>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<QueryToolbar v-model="filters" class="audit-query workbench-query" ariaLabel="客户操作日志筛选" :fields="queryFields" preference-key="customer-audit-logs-query" @search="applyFilters" />
|
<QueryToolbar v-model="filters" class="audit-query" ariaLabel="客户操作日志筛选" :fields="queryFields" preference-key="customer-audit-logs-query" @search="applyFilters" />
|
||||||
<LoadErrorState v-if="loadError" title="客户操作日志加载失败" :message="loadError.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="loadError" /></template></LoadErrorState>
|
<LoadErrorState v-if="loadError" title="客户操作日志加载失败" :message="loadError.message" :loading="loading" @retry="load"><template #details><ApiErrorMeta :details="loadError" /></template></LoadErrorState>
|
||||||
<div class="workbench-table" v-else><DataTable v-model:page="page" v-model:page-size="pageSize" :data="rows" :columns="columns" :loading="loading" :total="total" row-key="id" aria-label="客户操作日志列表" empty-text="当前客户暂无操作日志" preference-key="customer-audit-logs" border stripe>
|
<DataTable v-else v-model:page="page" v-model:page-size="pageSize" :data="rows" :columns="columns" :loading="loading" :total="total" row-key="id" aria-label="客户操作日志列表" empty-text="当前客户暂无操作日志" preference-key="customer-audit-logs" border stripe>
|
||||||
<template #actions="{ row }"><el-button class="density-action" size="small" :aria-label="`查看操作日志:${auditEventLabel((row as PlatformAuditLogListItem).eventType)},${formatDate((row as PlatformAuditLogListItem).occurredAt)}`" @click="openDetail(row as PlatformAuditLogListItem)">详情</el-button></template>
|
<template #actions="{ row }"><el-button class="density-action" size="small" :aria-label="`查看操作日志${(row as PlatformAuditLogListItem).id}详情`" @click="openDetail(row as PlatformAuditLogListItem)">详情</el-button></template>
|
||||||
<template #description="{ row }"><el-tooltip :content="auditDescriptionLabel((row as PlatformAuditLogListItem).description)" placement="top" :show-after="400"><span class="cell-clamp">{{ auditDescriptionLabel((row as PlatformAuditLogListItem).description) }}</span></el-tooltip></template>
|
<template #description="{ row }"><el-tooltip :content="auditDescriptionLabel((row as PlatformAuditLogListItem).description)" placement="top" :show-after="400"><span class="cell-clamp">{{ auditDescriptionLabel((row as PlatformAuditLogListItem).description) }}</span></el-tooltip></template>
|
||||||
<template #clientIp="{ row }">{{ display((row as PlatformAuditLogListItem).clientIp) }}</template>
|
<template #clientIp="{ row }">{{ display((row as PlatformAuditLogListItem).clientIp) }}</template>
|
||||||
<template #eventType="{ row }"><el-tooltip :content="(row as PlatformAuditLogListItem).eventType" placement="top" :show-after="500"><span class="event-label workbench-badge is-toned">{{ auditEventLabel((row as PlatformAuditLogListItem).eventType) }}</span></el-tooltip></template>
|
<template #eventType="{ row }"><el-tooltip :content="(row as PlatformAuditLogListItem).eventType" placement="top" :show-after="500"><span class="event-label">{{ auditEventLabel((row as PlatformAuditLogListItem).eventType) }}</span></el-tooltip></template>
|
||||||
<template #username="{ row }">{{ auditOperatorLabel((row as PlatformAuditLogListItem).username) }}</template>
|
<template #username="{ row }">{{ auditOperatorLabel((row as PlatformAuditLogListItem).username) }}</template>
|
||||||
<template #serviceName="{ row }"><el-tooltip :content="display((row as PlatformAuditLogListItem).serviceName)" placement="top" :show-after="500"><span class="service-label">{{ auditServiceLabel((row as PlatformAuditLogListItem).serviceName) }}</span></el-tooltip></template>
|
<template #serviceName="{ row }"><el-tooltip :content="display((row as PlatformAuditLogListItem).serviceName)" placement="top" :show-after="500"><span class="service-label">{{ auditServiceLabel((row as PlatformAuditLogListItem).serviceName) }}</span></el-tooltip></template>
|
||||||
<template #success="{ row }"><el-tag :type="(row as PlatformAuditLogListItem).success ? 'success' : 'danger'">{{ (row as PlatformAuditLogListItem).success ? '成功' : '失败' }}</el-tag></template>
|
<template #success="{ row }"><el-tag :type="(row as PlatformAuditLogListItem).success ? 'success' : 'danger'">{{ (row as PlatformAuditLogListItem).success ? '成功' : '失败' }}</el-tag></template>
|
||||||
<template #occurredAt="{ row }">{{ formatDate((row as PlatformAuditLogListItem).occurredAt) }}</template>
|
<template #occurredAt="{ row }">{{ formatDate((row as PlatformAuditLogListItem).occurredAt) }}</template>
|
||||||
<template #pagination-left>共 {{ total }} 条客户操作记录</template>
|
<template #pagination-left>共 {{ total }} 条客户操作记录</template>
|
||||||
</DataTable></div>
|
</DataTable>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<AppDrawer class="customer-audit-drawer admin-density-drawer admin-density-drawer--detail admin-workbench is-drawer" v-model="detailOpen" :title="detailTitle" size="min(920px, 96vw)" :loading="detailLoading" :show-footer="false">
|
<AppDrawer class="customer-audit-drawer admin-density-drawer" v-model="detailOpen" title="操作日志详情" size="min(920px, 96vw)" :loading="detailLoading" :show-footer="false">
|
||||||
<LoadErrorState v-if="detailError" title="详情加载失败" :message="detailError.message" :loading="detailLoading" @retry="loadDetail"><template #details><ApiErrorMeta :details="detailError" /></template></LoadErrorState>
|
<LoadErrorState v-if="detailError" title="详情加载失败" :message="detailError.message" :loading="detailLoading"><template #details><ApiErrorMeta :details="detailError" /></template></LoadErrorState>
|
||||||
<div v-else-if="detail" class="density-dialog-sections">
|
<template v-else-if="detail">
|
||||||
<section class="density-dialog-section" data-tone="source">
|
<section class="audit-detail-hero" :class="detail.success ? 'is-success' : 'is-failed'">
|
||||||
<h3 class="density-dialog-section__title">{{ auditEventLabel(detail.eventType) }} <el-tag :type="detail.success ? 'success' : 'danger'" effect="light">{{ detail.success ? '操作成功' : '操作失败' }}</el-tag></h3>
|
<span class="result-icon" aria-hidden="true"><CircleCheck v-if="detail.success" :size="22" /><CircleX v-else :size="22" /></span>
|
||||||
<p class="audit-event-description">{{ auditDescriptionLabel(detail.description) }}</p>
|
<div class="hero-copy"><span>事件类型</span><h3>{{ auditEventLabel(detail.eventType) }}</h3><p>{{ auditDescriptionLabel(detail.description) }}</p></div>
|
||||||
|
<el-tag :type="detail.success ? 'success' : 'danger'" effect="light">{{ detail.success ? '操作成功' : '操作失败' }}</el-tag>
|
||||||
</section>
|
</section>
|
||||||
<section class="density-dialog-section workbench-evidence" data-tone="source">
|
|
||||||
<h3 class="density-dialog-section__title">操作信息</h3>
|
<section class="audit-detail-grid" aria-label="操作日志基础信息">
|
||||||
<table class="density-table audit-detail-table" aria-label="操作日志基础信息"><tbody>
|
<div><span>操作人</span><strong>{{ auditOperatorLabel(detail.username) }}</strong></div>
|
||||||
<tr><th scope="row">操作人</th><td>{{ auditOperatorLabel(detail.username) }}</td><th scope="row">发生时间</th><td>{{ formatDate(detail.occurredAt) }}</td></tr>
|
<div><span>发生时间</span><strong>{{ formatDate(detail.occurredAt) }}</strong></div>
|
||||||
<tr><th scope="row">来源服务</th><td>{{ auditServiceLabel(detail.serviceName) }}<small class="audit-service-code density-dialog-note">{{ display(detail.serviceName) }}</small></td><th scope="row">客户端 IP</th><td>{{ display(detail.clientIp) }}</td></tr>
|
<div><span>来源服务</span><strong>{{ auditServiceLabel(detail.serviceName) }}</strong><small>{{ display(detail.serviceName) }}</small></div>
|
||||||
<tr><th scope="row">业务资源</th><td>{{ auditResourceLabel(detail.resourceType) }}</td><th scope="row">处理耗时</th><td>{{ detail.durationMs == null ? '—' : `${detail.durationMs} ms` }}</td></tr>
|
<div><span>客户端 IP</span><strong>{{ display(detail.clientIp) }}</strong></div>
|
||||||
<tr><th scope="row">请求地址</th><td colspan="3"><span class="audit-request"><el-tag size="small" effect="plain">{{ auditHttpMethodLabel(detail.httpMethod) }}</el-tag><code>{{ display(detail.requestUri) }}</code></span></td></tr>
|
<div><span>业务资源</span><strong>{{ auditResourceLabel(detail.resourceType) }}</strong><small>{{ display(detail.resourceId) }}</small></div>
|
||||||
<tr><th scope="row">请求标识</th><td colspan="3"><code>{{ display(detail.requestId) }}</code></td></tr>
|
<div><span>处理耗时</span><strong>{{ detail.durationMs == null ? '—' : `${detail.durationMs} ms` }}</strong></div>
|
||||||
<tr v-if="!detail.success && detail.errorCode"><th scope="row">错误码(诊断)</th><td colspan="3"><code>{{ detail.errorCode }}</code></td></tr>
|
<div class="wide request-cell"><span>请求地址</span><div><el-tag size="small" effect="plain">{{ auditHttpMethodLabel(detail.httpMethod) }}</el-tag><code>{{ display(detail.requestUri) }}</code></div></div>
|
||||||
<tr v-if="detail.traceId"><th scope="row">链路标识</th><td colspan="3"><code>{{ detail.traceId }}</code></td></tr>
|
<div class="wide identity-cell"><span>请求标识</span><strong>{{ display(detail.requestId) }}</strong><small v-if="detail.traceId">链路标识:{{ detail.traceId }}</small></div>
|
||||||
</tbody></table>
|
|
||||||
</section>
|
</section>
|
||||||
<el-alert v-if="!detail.success" type="error" :closable="false" show-icon :title="detail.errorMessage || '操作失败,请查看诊断信息'" />
|
|
||||||
<div class="audit-snapshots">
|
<el-alert v-if="!detail.success" class="failure-alert" type="error" :closable="false" show-icon :title="display(detail.errorMessage || detail.errorCode)" />
|
||||||
<section class="density-dialog-section" data-tone="source"><h3 class="density-dialog-section__title">操作前快照</h3><pre class="density-code-block">{{ formatSnapshot(detail.beforeData) }}</pre></section>
|
<div class="snapshot-grid"><section><h3>操作前快照</h3><p>操作执行前保留的业务数据</p><pre>{{ formatSnapshot(detail.beforeData) }}</pre></section><section><h3>操作结果快照</h3><p>操作执行后返回或保存的业务数据</p><pre>{{ formatSnapshot(detail.afterData) }}</pre></section></div>
|
||||||
<section class="density-dialog-section" data-tone="source"><h3 class="density-dialog-section__title">操作结果快照</h3><pre class="density-code-block">{{ formatSnapshot(detail.afterData) }}</pre></section>
|
</template>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</AppDrawer>
|
</AppDrawer>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
@@ -210,15 +176,10 @@ watch([page, pageSize], ([nextPage, nextSize], [previousPage, previousSize]) =>
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
.customer-audit-panel { min-width:0; }.panel-title { display:flex; align-items:flex-start; justify-content:space-between; gap:var(--admin-space-6, 16px); margin-bottom:var(--admin-space-3, 8px); padding-bottom:var(--admin-space-3, 8px); border-bottom:1px solid var(--workbench-border); }.panel-title h2 { margin:0; color:var(--workbench-text); font-size:var(--admin-font-section, 14px); }.panel-title p { margin:5px 0 0; color:var(--workbench-muted); font-size:var(--admin-font-caption, 12px); }.panel-title > svg { color:var(--workbench-primary); }.audit-query { margin-bottom:var(--admin-space-5, 12px); }.module-empty { display:flex; min-height:var(--admin-empty-height, 64px); align-items:center; justify-content:center; flex-direction:column; gap:7px; color:var(--workbench-muted); text-align:center; }.module-empty strong { color:var(--workbench-text); font-size:var(--admin-font-body, 13px); }.module-empty p { margin:0; color:var(--workbench-muted); font-size:var(--admin-font-caption, 12px); }
|
.customer-audit-panel { min-width:0; }.panel-title { display:flex; align-items:flex-start; justify-content:space-between; gap:var(--admin-space-6, 16px); margin-bottom:var(--admin-space-3, 8px); padding-bottom:var(--admin-space-3, 8px); border-bottom:1px solid var(--cc-border); }.panel-title h2 { margin:0; color:#344054; font-size:var(--admin-font-section, 14px); }.panel-title p { margin:5px 0 0; color:var(--cc-muted); font-size:var(--admin-font-caption, 12px); }.panel-title > svg { color:var(--cc-primary); }.audit-query { margin-bottom:var(--admin-space-5, 12px); }.module-empty { display:flex; min-height:var(--admin-empty-height, 64px); align-items:center; justify-content:center; flex-direction:column; gap:7px; color:#98a2b3; text-align:center; }.module-empty strong { color:#475467; font-size:var(--admin-font-body, 13px); }.module-empty p { margin:0; color:var(--cc-muted); font-size:var(--admin-font-caption, 12px); }
|
||||||
.cell-clamp { display:-webkit-box; overflow:hidden; -webkit-box-orient:vertical; -webkit-line-clamp:2; line-height:1.45; overflow-wrap:anywhere; }.event-label { display:inline-flex; overflow:hidden; line-height:1.35; text-overflow:ellipsis; white-space:nowrap; }.service-label { display:block; overflow:hidden; color:var(--workbench-text); text-overflow:ellipsis; white-space:nowrap; }
|
.cell-clamp { display:-webkit-box; overflow:hidden; -webkit-box-orient:vertical; -webkit-line-clamp:2; line-height:1.45; overflow-wrap:anywhere; }.event-label { display:inline-flex; max-width:100%; padding:3px 9px; overflow:hidden; border:1px solid #dbeafe; border-radius:999px; background:#eff6ff; color:#1d4ed8; font-size:var(--admin-font-caption, 12px); line-height:1.35; text-overflow:ellipsis; white-space:nowrap; }.service-label { display:block; overflow:hidden; color:#475467; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
.audit-event-description { margin:0; overflow-wrap:anywhere; }
|
.audit-detail-hero { display:flex; align-items:flex-start; gap:13px; padding:var(--admin-space-3, 8px) var(--admin-space-4, 10px); border:1px solid #d1fadf; border-radius:0; background:#f6fef9; }.audit-detail-hero.is-failed { border-color:#fee4e2; background:#fff7f6; }.result-icon { display:grid; width:38px; height:var(--admin-tab-height, 38px); flex:0 0 auto; place-items:center; border-radius:50%; background:#dcfae6; color:#079455; }.is-failed .result-icon { background:#fee4e2; color:#d92d20; }.hero-copy { min-width:0; flex:1; }.hero-copy > span { color:#667085; font-size:var(--admin-font-caption, 12px); }.hero-copy h3 { margin:3px 0 var(--admin-space-1, 4px); color:#101828; font-size:var(--admin-font-section, 14px); }.hero-copy p { margin:0; color:#475467; font-size:var(--admin-font-body, 13px); line-height:1.55; }
|
||||||
.audit-detail-table { table-layout:fixed; }
|
.audit-detail-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); margin-top:var(--admin-space-6, 16px); overflow:hidden; border:1px solid #e4e7ec; border-radius:0; background:var(--admin-surface, #fff); }.audit-detail-grid > div { display:flex; min-width:0; min-height:var(--admin-row-height, 36px); flex-direction:column; justify-content:center; gap:5px; padding:var(--admin-space-2, 6px) var(--admin-space-4, 10px); border-right:1px solid #eaecf0; border-bottom:1px solid #eaecf0; }.audit-detail-grid > div:nth-child(3n) { border-right:0; }.audit-detail-grid > div.wide { grid-column:1/-1; border-right:0; }.audit-detail-grid > div:last-child { border-bottom:0; }.audit-detail-grid span { color:#667085; font-size:var(--admin-font-caption, 12px); }.audit-detail-grid strong { overflow-wrap:anywhere; color:#1d2939; font-size:var(--admin-font-section, 14px); font-weight:600; }.audit-detail-grid small { overflow-wrap:anywhere; color:#98a2b3; font-size:var(--admin-font-caption, 12px); }.request-cell > div { display:flex; min-width:0; align-items:center; gap:9px; }.request-cell code { min-width:0; overflow-wrap:anywhere; color:#344054; font:12px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace; }.failure-alert { margin-top:var(--admin-space-6, 16px); }
|
||||||
.audit-detail-table th { width:92px; }
|
.snapshot-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:var(--admin-space-6, 16px); margin-top:18px; }.snapshot-grid section { min-width:0; padding:var(--admin-space-4, 10px); border:1px solid #e4e7ec; border-radius:0; background:var(--admin-surface, #fff); }.snapshot-grid h3 { margin:0; color:#344054; font-size:var(--admin-font-section, 14px); }.snapshot-grid p { margin:var(--admin-space-1, 4px) 0 var(--admin-space-4, 10px); color:#98a2b3; font-size:var(--admin-font-caption, 12px); }.snapshot-grid pre { min-height:160px; max-height:360px; margin:0; padding:14px; overflow:auto; border:1px solid #eaecf0; border-radius:8px; background:var(--admin-label-bg, #f8fafc); color:#344054; font:12px/1.65 ui-monospace,SFMono-Regular,Consolas,monospace; white-space:pre-wrap; overflow-wrap:anywhere; }
|
||||||
.audit-service-code { display:block; }
|
@media(max-width:720px){.audit-detail-grid{grid-template-columns:1fr}.audit-detail-grid>div,.audit-detail-grid>div:nth-child(3n){border-right:0}.audit-detail-grid>div.wide{grid-column:auto}.snapshot-grid{grid-template-columns:1fr}.audit-detail-hero{align-items:flex-start}.audit-detail-hero>.el-tag{flex:0 0 auto}}
|
||||||
.audit-request { display:flex; align-items:center; gap:var(--admin-space-3); }
|
|
||||||
.audit-request code { min-width:0; }
|
|
||||||
.audit-snapshots { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:var(--admin-space-5); }
|
|
||||||
.audit-snapshots > .density-dialog-section { margin-bottom:0; }
|
|
||||||
@media(max-width:720px) { .audit-snapshots { grid-template-columns:1fr; } }
|
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
# Admin 登录模块指引
|
|
||||||
|
|
||||||
## 路径基准与读取顺序
|
|
||||||
|
|
||||||
- 本文件适用于 `src/modules/auth/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`。
|
|
||||||
- 模块只有一个页面 `pages/LoginView.vue`;认证状态、Token 刷新与路由守卫在 `../../core/auth/` 与 `../../shared/api/AGENTS.md`,本模块不复制这些逻辑。
|
|
||||||
- 后端只查 `auth/`(登录、刷新、退出、改密)。
|
|
||||||
|
|
||||||
## 页面与入口
|
|
||||||
|
|
||||||
| 目标 | 页面/入口 | API 与后端 |
|
|
||||||
|---|---|---|
|
|
||||||
| 平台员工登录页、表单校验与错误提示 | `pages/LoginView.vue` | `../../core/auth/auth.ts` → `../../shared/api/http.ts`;`auth/` |
|
|
||||||
| 登录态与路由跳转 | 页面不持有状态 | `../../core/auth/auth.ts`、`../../core/access/` |
|
|
||||||
| 401 刷新与重放 | 页面不处理 | `../../shared/api/http.ts`、`../../shared/api/AGENTS.md` |
|
|
||||||
|
|
||||||
## 关键边界
|
|
||||||
|
|
||||||
- 页面不读写 Token、不拼 `Authorization`、不自行持久化密码;令牌与刷新编排只在 `src/core/auth/` 与 `src/shared/api/http.ts`。
|
|
||||||
- 认证失败提示按服务端返回的 `code` 与文案展示,不把 401/403 混为同一种提示。
|
|
||||||
- 登录成功后跳转由路由守卫决定,页面不硬编码默认落地页。
|
|
||||||
- 记住账号类能力只保存登录标识,不持久化密码或 Token。
|
|
||||||
|
|
||||||
## 验证
|
|
||||||
|
|
||||||
- 定向:`pnpm test src/modules/auth/<目标测试>`;登录或守卫变化同时核对 `src/core/auth/` 与 `src/shared/api/http.ts`。
|
|
||||||
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
# 平台登录页逐操作矩阵
|
|
||||||
|
|
||||||
依据:2026-10-20 用户确认全 Admin 推广清爽蓝白风格;视觉参考为工作区 `docs/界面参考/蓝白卡片式工作台风格参考.md` 与其中的用户参考图。当前页面入口为 `pages/LoginView.vue`;本轮只调整展示,不改变认证状态、接口和路由跳转。
|
|
||||||
|
|
||||||
| 页面 | 操作 | 当前承载与依据 | 本轮结论与验证 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| 平台员工登录 | 输入账号、密码与提交 | `LoginView.vue` 的 `el-form` 与 `submit`;独立登录页,品牌区与表单左右布局 | 接入公共蓝白面板、图标和主题;保留原 `large` 表单尺寸、账号密码字段、自动完成、密码显隐与回车提交,不新增文案或字段 |
|
|
||||||
| 平台员工登录 | 必填校验与加载 | 原 `rules`、`loading` 与表单标签 | 原必填提示及提交加载保持;不增加验证码或改变认证步骤 |
|
|
||||||
| 平台员工登录 | 登录失败 | 原 `loginError`、`ApiErrorMeta` 与 `role="alert"` | 错误区域复用公共提示外观,服务端错误文案、诊断信息和可恢复表单保持 |
|
|
||||||
| 平台员工登录 | 登录成功后跳转 | 原 `auth.login`、`initializeAfterLogin` 与 `sanitizeInternalPath` | 成功提示、安全跳转、首个授权入口及无权限回退均保持,不修改 router/store |
|
|
||||||
| 平台员工登录 | 已有窄屏品牌布局 | 原 `960px`、`360px` 响应式规则 | 保留既有窄屏能力,不新增多视口验收范围 |
|
|
||||||
| 平台员工登录 | 详情、新增、编辑、审核、文件预览、删除 | 当前页面无上述操作 | 不新增操作或浮层 |
|
|
||||||
|
|
||||||
自动回归入口:`pages/LoginView.test.ts`。本模块未独立执行检查,统一由本轮总控完成。视觉待人工 `1920×1080`、浏览器缩放 `100%` 截图确认。
|
|
||||||
@@ -43,18 +43,14 @@ describe('LoginView authentication lifecycle', () => {
|
|||||||
expect(loginSource).not.toContain('demo-tip')
|
expect(loginSource).not.toContain('demo-tip')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('uses the shared blue-white theme and preserves the existing compact brand layout', () => {
|
it('uses the admin design tokens and keeps the brand visible at 320px', () => {
|
||||||
expect(loginSource).toContain("import '@/styles/adminWorkbench.css'")
|
expect(loginSource).toContain('<h1>柏悦物流管理后台</h1>')
|
||||||
expect(loginSource).toContain('class="login-page admin-workbench"')
|
expect(loginSource).toContain('class="login-mobile-brand"')
|
||||||
expect(loginSource).toContain('<h1 class="workbench-title">柏悦物流管理后台</h1>')
|
|
||||||
expect(loginSource).toContain('class="login-mobile-brand workbench-brand-mark"')
|
|
||||||
expect(loginSource).toContain('class="login-card workbench-panel"')
|
|
||||||
expect(loginSource).toContain('class="login-error workbench-notice workbench-tone" data-tone="rose"')
|
|
||||||
expect(loginSource).toContain('aria-label="平台员工登录"')
|
expect(loginSource).toContain('aria-label="平台员工登录"')
|
||||||
expect(loginSource).toContain('label-position="top" size="large"')
|
|
||||||
expect(loginSource).toContain('autocomplete="username" maxlength="100" autofocus')
|
expect(loginSource).toContain('autocomplete="username" maxlength="100" autofocus')
|
||||||
expect(loginSource).toContain('aria-live="polite"')
|
expect(loginSource).toContain('aria-live="polite"')
|
||||||
expect(loginSource).not.toContain('var(--cc-navy)')
|
expect(loginSource).toContain('background: var(--cc-surface-muted)')
|
||||||
|
expect(loginSource).toContain('border-radius: var(--cc-radius-lg)')
|
||||||
expect(loginSource).toContain('@media (max-width: 360px)')
|
expect(loginSource).toContain('@media (max-width: 360px)')
|
||||||
expect(loginSource).not.toContain('让跨境物流管理')
|
expect(loginSource).not.toContain('让跨境物流管理')
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
|||||||
import { sanitizeInternalPath } from '@/core/routing/accessDecision'
|
import { sanitizeInternalPath } from '@/core/routing/accessDecision'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
import { useAuthStore } from '@/core/auth/auth'
|
||||||
import '@/styles/adminWorkbench.css'
|
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
@@ -55,25 +54,25 @@ async function submit() {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="login-page admin-workbench">
|
<div class="login-page">
|
||||||
<section class="login-intro">
|
<section class="login-intro">
|
||||||
<div class="login-brand workbench-brand-mark"><img class="login-brand-logo" :src="baiyueLogoWhite" alt="柏悦物流" /></div>
|
<div class="login-brand"><img class="login-brand-logo" :src="baiyueLogoWhite" alt="柏悦物流" /></div>
|
||||||
<div class="workbench-heading">
|
<div>
|
||||||
<h1 class="workbench-title">柏悦物流管理后台</h1>
|
<h1>柏悦物流管理后台</h1>
|
||||||
<p class="login-intro-copy workbench-note">平台内部运营与管理系统</p>
|
<p class="intro-copy">平台内部运营与管理系统</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="login-security-note workbench-meta">
|
<div class="security-note">
|
||||||
<ShieldCheck :size="22" aria-hidden="true" />
|
<ShieldCheck :size="22" />
|
||||||
<span>平台内部系统,请使用授权账号登录</span>
|
<span>平台内部系统,请使用授权账号登录</span>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="login-panel">
|
<section class="login-panel">
|
||||||
<div class="login-card workbench-panel">
|
<div class="login-card">
|
||||||
<div class="login-mobile-brand workbench-brand-mark"><img :src="baiyueLogoWhite" alt="柏悦物流" /></div>
|
<div class="login-mobile-brand"><img :src="baiyueLogoWhite" alt="柏悦物流" /></div>
|
||||||
<div class="login-card-icon workbench-icon"><LockKeyhole :size="24" aria-hidden="true" /></div>
|
<div class="login-card-icon"><LockKeyhole :size="24" /></div>
|
||||||
<h2 class="workbench-title">登录管理后台</h2>
|
<h2>登录管理后台</h2>
|
||||||
<p class="workbench-note">使用平台内部员工账号登录</p>
|
<p>使用平台内部员工账号登录</p>
|
||||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" size="large" aria-label="平台员工登录" @submit.prevent="submit">
|
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" size="large" aria-label="平台员工登录" @submit.prevent="submit">
|
||||||
<el-form-item label="账号" prop="account" required>
|
<el-form-item label="账号" prop="account" required>
|
||||||
<el-input v-model.trim="form.account" placeholder="请输入账号" :prefix-icon="UserRound" autocomplete="username" maxlength="100" autofocus />
|
<el-input v-model.trim="form.account" placeholder="请输入账号" :prefix-icon="UserRound" autocomplete="username" maxlength="100" autofocus />
|
||||||
@@ -85,43 +84,38 @@ async function submit() {
|
|||||||
登录 <ArrowRight :size="17" />
|
登录 <ArrowRight :size="17" />
|
||||||
</el-button>
|
</el-button>
|
||||||
</el-form>
|
</el-form>
|
||||||
<div v-if="loginError" class="login-error workbench-notice workbench-tone" data-tone="rose" role="alert" aria-live="polite"><p>{{ loginError.message }}</p><ApiErrorMeta :details="loginError" /></div>
|
<div v-if="loginError" class="login-error" role="alert" aria-live="polite"><p>{{ loginError.message }}</p><ApiErrorMeta :details="loginError" /></div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.login-page { display: grid; min-width: 0; min-height: 100svh; grid-template-columns: minmax(420px, 1.05fr) minmax(420px, .95fr); background: var(--workbench-surface); color: var(--workbench-text); }
|
.login-page { min-width: 0; min-height: 100svh; background: var(--cc-surface); color: var(--cc-text); }
|
||||||
.login-intro { display: flex; min-width: 0; flex-direction: column; justify-content: space-between; padding: 46px clamp(42px, 7vw, 100px); }
|
.login-intro { min-width: 0; background: var(--cc-navy); }
|
||||||
.login-brand { display: flex; width: fit-content; min-height: 64px; align-items: center; padding: 8px 20px; }
|
.login-intro h1 { max-width: 560px; margin: 16px 0 14px; font-size: 40px; line-height: 1.2; overflow-wrap: anywhere; }
|
||||||
.login-brand-logo { display: block; width: 205px; height: 64px; object-fit: contain; object-position: left center; }
|
.intro-copy { margin: 0; color: #cbd5e1; font-size: 15px; line-height: 1.7; overflow-wrap: anywhere; }
|
||||||
.login-intro h1 { max-width: 560px; }
|
.login-panel { min-width: 0; background: var(--cc-surface-muted); }
|
||||||
.login-intro-copy { max-width: 560px; }
|
.login-card { min-width: 0; padding: 32px; border: 1px solid var(--cc-border); border-radius: var(--cc-radius-lg); background: var(--cc-surface); box-shadow: var(--cc-shadow-md); }
|
||||||
.login-security-note > svg { flex: 0 0 auto; }
|
.login-card-icon { border-radius: var(--cc-radius-lg); background: var(--cc-primary-soft); }
|
||||||
.login-panel { display: grid; min-width: 0; place-items: center; padding: 48px; background: var(--workbench-surface-tint); }
|
.login-card h2, .login-card > p { overflow-wrap: anywhere; }
|
||||||
.login-card.workbench-panel { width: min(410px, 100%); min-width: 0; padding: 32px; }
|
|
||||||
.login-card h2 { margin-top: 22px; }
|
|
||||||
.login-card > p { margin: 8px 0 30px; }
|
|
||||||
.login-mobile-brand { display: none; }
|
.login-mobile-brand { display: none; }
|
||||||
.login-submit { width: 100%; min-height: 44px; }
|
.login-submit { min-height: 44px; }
|
||||||
.login-submit :deep(> span) { display: flex; align-items: center; gap: 8px; }
|
.login-error { min-width: 0; padding: 12px 14px; border: 1px solid #fecdca; border-radius: var(--cc-radius-md); background: var(--cc-danger-soft); color: var(--cc-danger); overflow-wrap: anywhere; }
|
||||||
.login-error.workbench-notice { min-width: 0; margin-top: 14px; }
|
|
||||||
.login-error > p { margin: 0; }
|
|
||||||
.login-error :deep(*) { max-width: 100%; overflow-wrap: anywhere; }
|
.login-error :deep(*) { max-width: 100%; overflow-wrap: anywhere; }
|
||||||
|
.login-card :deep(.el-input__wrapper:focus-within) { box-shadow: 0 0 0 1px var(--cc-primary) inset, 0 0 0 3px var(--cc-primary-soft); }
|
||||||
|
|
||||||
@media (max-width: 960px) {
|
@media (max-width: 960px) {
|
||||||
.login-page { grid-template-columns: 1fr; }
|
|
||||||
.login-intro { display: none; }
|
|
||||||
.login-panel { align-items: start; padding: 24px; }
|
.login-panel { align-items: start; padding: 24px; }
|
||||||
.login-card.workbench-panel { width: min(440px, 100%); margin: auto; padding: 28px; }
|
.login-card { width: min(440px, 100%); margin: auto; padding: 28px; }
|
||||||
.login-mobile-brand { display: flex; width: fit-content; min-height: 52px; align-items: center; margin-bottom: 28px; padding: 8px 16px; }
|
.login-mobile-brand { display: flex; min-height: 52px; align-items: center; margin: -28px -28px 28px; padding: 12px 20px; border-radius: var(--cc-radius-lg) var(--cc-radius-lg) 0 0; background: var(--cc-navy); }
|
||||||
.login-mobile-brand img { display: block; width: 154px; height: 48px; object-fit: contain; object-position: left center; }
|
.login-mobile-brand img { display: block; width: 154px; height: 48px; object-fit: contain; object-position: left center; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 360px) {
|
@media (max-width: 360px) {
|
||||||
.login-panel { padding: 12px; }
|
.login-panel { padding: 12px; }
|
||||||
.login-card.workbench-panel { padding: 20px; }
|
.login-card { padding: 20px; }
|
||||||
.login-mobile-brand { margin-bottom: 24px; }
|
.login-mobile-brand { margin: -20px -20px 24px; padding-inline: 16px; }
|
||||||
|
.login-card h2 { font-size: 24px; }
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
# Admin 货柜模块指引
|
|
||||||
|
|
||||||
## 路径基准与读取顺序
|
|
||||||
|
|
||||||
- 本文件适用于 `src/modules/container-loading/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`,页面/接口细则见 `../../../docs/business-index.md`。
|
|
||||||
- 先按下表定位页面,再沿 `routes.ts`、页面 import 与 `api/` 追踪;接口、状态、金额或权限变化时再读详细索引命中行。
|
|
||||||
- 后端只查直接消费方:`firstleg/`(`loading/`、`customs/container/`、`terminaldrayage/`、`oceanbooking/`)、`lastleg-service/`(柜级到仓与尾程)、`file/`、`print/`。纯页面与文案不读后端。
|
|
||||||
|
|
||||||
## 页面与入口
|
|
||||||
|
|
||||||
| 目标 | 页面/路由 | API 与后端 |
|
|
||||||
|---|---|---|
|
|
||||||
| 国内装柜列表、模拟柜、订舱关联 | `pages/ContainersView.vue`、`pages/DomesticContainersView.vue`;`container-loading/domestic` | `api/platformContainerLoading.ts`;`components/ContainerSimulationCreate.vue`、`components/OceanBookingLinkDialog.vue`;`firstleg/loading/` |
|
|
||||||
| 送柜报关详情、装柜清单页签、报关、出仓 | `pages/DomesticContainerDetailView.vue`、共享 `pages/ContainerDetailView.vue`;`container-loading/domestic/:containerId` | `components/ContainerOverviewPanel.vue`、`components/ContainerCustomsPanel.vue`;`api/platformContainerCustoms.ts`;`firstleg/customs/container/`、`file/` |
|
|
||||||
| 智能装柜工作台、柜次容量与分配 | `pages/SmartLoadingWorkbenchView.vue`;`container-loading/domestic/:containerId/smart-loading` | `api/platformContainerLoading.ts`;`../unified-orders/workflows/components/SmartLoadingWorkbench.vue`;`firstleg/service/SmartLoadingService.java` |
|
|
||||||
| 全局智能装柜弹框、入仓码候选与箱数 | `pages/GlobalSmartLoadingView.vue`(内嵌,无独立路由)、`components/SmartLoadingDialog.vue`、`components/SmartLoadingCandidateInbounds.vue` | `smartLoadingChannelGroups.ts`、`smartLoadingItems.ts`、`smartLoadingPlanGroups.ts`;后端 `/inbound-candidates`、`/containers`、`/inbound-assignments` |
|
|
||||||
| 海外清关提柜工作台、船节点、清关与 DO/PU | `pages/OverseasContainersView.vue`;`container-loading/overseas` | `api/platformContainerLoading.ts`;`firstleg/` 船节点与 `customs/`;`components/ContainerOverviewPanel.vue` |
|
|
||||||
| 目的港码头拖车、车队与还空 | `pages/OverseasContainerDetailView.vue`(薄包装)、共享 `pages/ContainerDetailView.vue`(实际内容);`container-loading/overseas/:containerId` | `api/terminalDrayages.ts` 由共享详情调用;`firstleg/terminaldrayage/`(`TerminalDrayageService.java`、`DirectDeliveryService.java`) |
|
|
||||||
| 整柜预计/实际到仓 | 列表与详情“到仓”列 | `api/containerArrivalTimes.ts`;`lastleg-service/` 柜级订单 |
|
|
||||||
| 装柜照片与证据的展示/读取(上传在 PDA 与 Firstleg) | `components/ContainerOverviewPanel.vue` | 证据读取走 `file/`;生产与上传见 `firstleg/loading/service/CabinetLoadingEvidenceService.java` 与国内 PDA |
|
|
||||||
| 海外柜费用 | `components/ContainerLastLegFeesPanel.vue` | `api/overseasContainerFees.ts`;`finance/`、`firstleg/` 费用来源 |
|
|
||||||
|
|
||||||
`pages/ContainerWorkbenchView.vue` 是工作台外壳,按权限在“国内装柜”“清关提柜”间切换;`pages/ContainersView.vue` 与 `ContainerDetailView.vue` 为共享实现,改两份前先确认是否同源。
|
|
||||||
|
|
||||||
## 关键边界
|
|
||||||
|
|
||||||
- 列表范围由服务端 `scope=ACTIVE/HISTORY` 分页,写资格只取服务端 `allowedActions`;不用浏览器筛选、本地推导或柜内明细数量代替。
|
|
||||||
- 创建柜次时自动生成唯一预装计划;订舱关联允许真实集装箱号为空,但**确认预装和创建 PDA 任务前必须补齐**,历史上已建缺号任务可在预装详情首次补录。
|
|
||||||
- 还空截止、超时天数只展示服务端按权威卸柜完成时间加 72 小时计算的结果,前端不重算、不用拖车状态当阻断门禁。
|
|
||||||
- 国内“送柜报关”只消费 `/containers/domestic`,海外“清关提柜”只消费 `/containers/overseas`;两端统一用 `containerBookingId`,禁止混用两套列表接口。
|
|
||||||
- 智能装柜候选状态只作筛选展示,按钮资格以服务端 `canAssign` 为准;计划箱数只消费 `totalPackageCount/remainingPackageCount`,不从候选页或本地规格重算。
|
|
||||||
- 前端不计算托数、不逐票建计划、不预占托盘;柜级转换必须原样回传服务端 `snapshotVersion/snapshotHash`,冲突后重新预览。
|
|
||||||
|
|
||||||
## 验证
|
|
||||||
|
|
||||||
- 定向:`pnpm test src/modules/container-loading/<目标测试>`;API 或类型变化同时运行 `pnpm typecheck`。
|
|
||||||
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`;离线检查不代替真实 HTTP 与人工截图验收。
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
import { http } from '@/shared/api/http'
|
import { http } from '@/shared/api/http'
|
||||||
import { createDeclarationBatch, submitDeclarationBatch, recordClearanceResult, type DeclarationBatch } from './platformContainerCustoms'
|
import { recordClearanceResult, type DeclarationBatch } from './platformContainerCustoms'
|
||||||
import { completeAllBuyContainerCustoms, downloadContainerCustomsReceipt, downloadContainerCustomsDocument, getContainerCustoms, sendContainerCustomsToBroker, startContainerCustoms, uploadContainerCustomsReceipt } from './platformContainerCustoms'
|
import { completeAllBuyContainerCustoms, downloadContainerCustomsReceipt, downloadContainerCustomsDocument, getContainerCustoms, sendContainerCustomsToBroker, startContainerCustoms, uploadContainerCustomsReceipt } from './platformContainerCustoms'
|
||||||
|
|
||||||
const customs = {
|
const customs = {
|
||||||
@@ -15,22 +15,6 @@ const customs = {
|
|||||||
describe('platform container customs API', () => {
|
describe('platform container customs API', () => {
|
||||||
beforeEach(() => vi.restoreAllMocks())
|
beforeEach(() => vi.restoreAllMocks())
|
||||||
|
|
||||||
it('preserves the server batch number when creating and submitting a declaration', async () => {
|
|
||||||
const batch = { id: '123', customsContainerId: '456', loadingPlanId: '789', batchNo: 'DECL202610200001', sourceVersion: 1, version: 0, results: [] }
|
|
||||||
const post = vi.spyOn(http, 'post').mockResolvedValue({ code: '200', data: batch })
|
|
||||||
const created = await createDeclarationBatch('789', 3)
|
|
||||||
expect(created.batchNo).toBe('DECL202610200001')
|
|
||||||
expect(post.mock.calls[0]?.slice(0, 2)).toEqual([
|
|
||||||
'/platform/v1/customs/loading-plans/789/declaration-batches', { expectedVersion: 3, remark: null },
|
|
||||||
])
|
|
||||||
const submitted = await submitDeclarationBatch(created, ' CUSTOMS-EXTERNAL-1 ')
|
|
||||||
expect(submitted.batchNo).toBe(created.batchNo)
|
|
||||||
expect(post.mock.calls[1]?.slice(0, 2)).toEqual([
|
|
||||||
'/platform/v1/customs/loading-plans/declaration-batches/123/submit',
|
|
||||||
{ expectedVersion: 0, customsEntryNo: 'CUSTOMS-EXTERNAL-1', remark: null },
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('records domestic customs time in Shanghai even when UTC falls on the previous day', async () => {
|
it('records domestic customs time in Shanghai even when UTC falls on the previous day', async () => {
|
||||||
vi.useFakeTimers()
|
vi.useFakeTimers()
|
||||||
try {
|
try {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user