feat: 仓储模块前端、菜单同步扩展及相关页面优化

新增仓储模块页面与 API、店铺授权/店铺订单页面及路由权限目录;
扩展菜单管理同步能力支持二级子菜单与三级按钮;优化公告、仓库地址、下单等页面。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-07-11 15:19:35 +08:00
parent 43209625d0
commit 5191d1981f
53 changed files with 6329 additions and 550 deletions

View File

@ -1,5 +1,9 @@
# VITE_API_BASE_URL='http://localhost:5173/'
# 本地开发统一走线上 Admin API(与 /rbac、/order 等 Vite 代理一致)
VITE_OMS_ADMIN_URL=http://api.nanafa.com/admin
VITE_API_ADMIN_URL=http://api.nanafa.com/admin
# 智谱 AI(接口映射脚本生成)
# 在 https://open.bigmodel.cn 申请 API Key
VITE_ZHIPU_API_KEY=85bbbef6bafd4ca383eef04189decd07.lKVQHcLGtYE8oUn5

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,602 @@
# 订单全链路自动化测试方案
> **版本**:v1.0
> **日期**:2026-07-08
> **适用范围**:OMS 订单从创建 → 预报 → 入库 → 支付 → 出库 → 轨迹 → 签收(设计态)
> **关联文档**:`oms系统设计-050801.md` §4、§6、§10.3;`物流下单协议.md`;`订单批量处理与异步队列方案0707.md`
---
## 1. 目标与范围
### 1.1 目标
建立一套**可重复执行、可接入 CI** 的自动化测试流程,覆盖订单主 happy path:
```
下单预报 → 入库收货 → 客户支付 → 出库发货 → 轨迹同步 → 签收完成
```
并验证各阶段:
- **订单状态**(`OrderStatus`)与时间字段(`ReceiveTime` / `PayTime` / `ShipTime` / `SignTime`)
- **费用**(预报 / 入库 / 出库阶段 `t_order_fee`)
- **客户余额与流水**(`t_customer.Balance`、`t_customer_account_flow`)
- **仓储操作记录**(`t_inbound_record` / `t_outbound_record`)
- **轨迹服务联动**(UpsertSmallBag,可 mock)
- **权限与数据范围**(客户只能看到自己的订单)
### 1.2 当前实现边界(必读)
| 阶段 | 状态码 | 后端是否已实现 | 自动化策略 |
|------|--------|----------------|------------|
| 小包创建 + 预报计费 | `predeclared` | ✅ | API 断言 |
| 入库扫描 | `pendingPayment` | ✅ | API 断言 |
| 支付 | `pendingShip` | ✅ | API + 余额断言 |
| 出库扫描 | `pendingOnline` | ✅ | API 断言 |
| 运输中 | `shipping` | ❌ 无写入逻辑 | **Phase 2**:mock 轨迹回调或手工 DB 置态 |
| 派送成功(签收) | `deliverySuccess` + `SignTime` | ❌ 无写入逻辑 | **Phase 2**:同上;或 Track 服务 `UpdateOrderStatus` |
| 问题件 / 理赔件 | `problematic` / `claimed` | ✅ | 分支用例 |
> **结论**:Phase 1 自动化覆盖到 **`pendingOnline`(待上网)** 为「OMS 内闭环」;签收段在 OMS 回写接口落地前,用 **Track 侧断言 + 预留 OMS 状态同步测试桩** 衔接。
---
## 2. 测试分层架构
```mermaid
flowchart TB
subgraph L4["L4 可选 UI E2E"]
UI[Playwright / Cypress<br/>关键页面冒烟]
end
subgraph L3["L3 API 全链路 E2E(推荐主战场)"]
E2E[OrderLifecycleE2ETests<br/>真实 MySQL + TestServer]
end
subgraph L2["L2 API 集成"]
INT[SimpleAdmin.Api.IntegrationTests<br/>路由注册 + Mock 依赖]
end
subgraph L1["L1 单元测试"]
UNIT[Oms.Tests<br/>计费 / 签名 / Batch 治理]
end
L1 --> L2 --> L3
L3 -.-> L4
```
| 层级 | 项目位置 | 依赖 | 运行频率 |
|------|----------|------|----------|
| L1 单元 | `oms0414-back/src/Oms.Tests` | 无 DB | 每次 PR |
| L2 集成 | `oms0414-back/src/SimpleAdmin.Api.IntegrationTests` | TestServer + 内存 RBAC | 每次 PR |
| L3 API E2E | **待建** `Oms.E2E.Tests` 或扩展现有 IntegrationTests | Docker MySQL + 可选 RabbitMQ/WireMock | 每日 / 合并前 |
| L4 UI E2E | **待建** `oms0414/e2e/` | 前端 dev + 后端 API | 发版前手动 / 夜间 |
---
## 3. 测试环境与配置
### 3.1 基础服务
| 组件 | 用途 | 本地 / CI 建议 |
|------|------|----------------|
| MySQL 8.x | 业务库 `oms_test` | `docker compose` 独立库,每次 E2E 前 migrate |
| SimpleAdmin.Api | OMS 后端 | `ASPNETCORE_ENVIRONMENT=Testing` |
| 前端 Vite | UI E2E 可选 | `localhost:5173` |
| RabbitMQ | 批量任务 E2E | 默认 **关闭**;批量专项用例单独 job 开启 |
| WireMock / MockServer | Track、itfx 下游 | E2E 默认 mock,避免外网依赖 |
### 3.2 后端配置项(`appsettings.Testing.json` 或环境变量)
```json
{
"ConnectionStrings": { "Default": "Server=127.0.0.1;Port=3306;Database=oms_test;..." },
"OrderBatch": {
"RabbitMq": { "Enabled": false }
},
"Oms": {
"TrackService": {
"Enabled": true,
"BaseUrl": "http://127.0.0.1:9090",
"AppKey": "TEST_KEY",
"AppSecret": "TEST_SECRET",
"TimeoutSeconds": 5
},
"Itfx": {
"BaseUrl": "http://127.0.0.1:9091",
"TimeoutSeconds": 5
}
},
"App": { "SendStartupNotification": false }
}
```
| 配置节 | 测试关注点 | Mock 策略 |
|--------|------------|-----------|
| `Oms:TrackService` | 创建订单后异步 `UpsertSmallBag` | WireMock 返回 200 + 固定 body |
| `Oms:Itfx` | 下游预报转发(可选步骤) | WireMock 或跳过 |
| `OrderBatch:RabbitMq` | 批量支付/入库等 | 主链路用同步 API;批量单独用例开启 |
### 3.3 数据库初始化顺序
```text
1. db.sql # 全量表结构
2. sql/migrate_*.sql # 增量迁移(issue_template、xhs 等按需)
3. scripts/order_batch_job_tables.sql
4. sql/seed_e2e_order_lifecycle.sql # 【待建】E2E 专用主数据(见 §4)
```
---
## 4. 主数据 Fixture(测试前置条件)
自动化执行前,库中须存在以下**稳定可引用**的数据。建议新增 `sql/seed_e2e_order_lifecycle.sql`,所有 E2E 用例共用同一套编码。
### 4.1 主数据清单
| 类别 | 表 / 模块 | 测试用固定值 | 说明 |
|------|-----------|--------------|------|
| 国家 | `t_country` | `US` / `CN` | 收件国用于分区计价 |
| 客户 | `t_customer` | `customerCode=E2E001`,`Balance >= 10000` | 支付前须余额充足 |
| RBAC 用户 | `user` | 客户主账号,绑定 `E2E001` | 登录拿 JWT |
| 仓库 | `t_warehouse_address` | `warehouseId=9001` | 下单、扫描共用 |
| 销售产品 | `t_sales_product` | `productCode=E2E-SP-01` | 已发布、已绑定规则/价格快照 |
| 服务渠道 | `t_service_channel` | `channelCode=E2E-CH-01` | 排货后可写入订单 |
| 价格 / 分区 | `t_sales_product_price*`、`t_kpi_area*` | 覆盖 US 分区 | 否则创建订单会 `draft` + `PredeclareFailReason` |
| 计重 / 进位 | `t_weight_rule`、`t_weight_rounding` | 匹配 1kg 标准件 | 入库/outbound 计费依赖 |
| 数据权限 | 数据范围 | 测试用户可见 E2E 客户 | 否则列表为空 |
### 4.2 登录与请求头
```http
POST /admin/auth/login
Content-Type: application/json
{ "userName": "e2e_customer", "password": "..." }
```
后续请求:
```http
Authorization: Bearer {accessToken}
```
客户会话下单时 **不传 `customerId`**(由 `OmsSessionHelper` 解析);内部运营账号测入库/出库时用 **运营 RBAC 账号**。
### 4.3 推荐双角色
| 角色 | 用途 | 权限前缀 |
|------|------|----------|
| `e2e_customer` | 下单、支付、查单 | `Order.PlaceOrder.*`、`Order.MyOrders.*` |
| `e2e_operator` | 入库、出库扫描 | `Operation.InboundScan.*`、`Operation.OutboundScan.*` |
---
## 5. 主流程用例设计(Happy Path)
### 5.1 流程总览
```mermaid
sequenceDiagram
participant C as 客户 API
participant O as OMS OrderService
participant W as 仓储 Operation
participant F as Finance
participant T as Track(Mock)
C->>O: POST /order/parcel/create
O-->>C: predeclared + serviceNo
O->>T: UpsertSmallBag (async)
C->>W: POST /operation/inbound/create
W->>O: ApplyReceiveBilling
W-->>C: pendingPayment + ReceiveTime
C->>O: POST /order/pay
O->>F: DebitOrderPay
O-->>C: pendingShip + PayTime
C->>W: POST /operation/outbound/create
W->>O: ApplyShipBilling
W-->>C: pendingOnline + ShipTime
Note over C,T: Phase 2 签收
T-->>O: (待实现) 状态回写
O-->>C: deliverySuccess + SignTime
```
### 5.2 分步用例表
| 步骤 | API | 方法 | 关键入参 | 期望 `OrderStatus` | 期望副作用 |
|------|-----|------|----------|-------------------|------------|
| 0 可选试算 | `/order/price-check` | POST | `productCode`, 件重尺, 收件国 | — | 返回价格 > 0 |
| 1 创建订单 | `/order/parcel/create` | POST | 见 §5.3 | `predeclared` | `t_order_fee` 预报应收;`ServiceNo` 生成 |
| 2 查详情 | `/order/detail` | GET | `id` | `predeclared` | 发件人/收件人/申报齐全 |
| 3 入库 | `/operation/inbound/create` | POST | `waybillNo`, 实重尺 | `pendingPayment` | `ReceiveTime` 非空;入库费 `ChargingStage=inbound` |
| 4 支付 | `/order/pay` | POST | `{ "id": orderId }` | `pendingShip` | `IsPaid=1`, `PayTime`;余额减少;`account_flow` |
| 5 出库 | `/operation/outbound/create` | POST | `waybillNo`, 实重尺 | `pendingOnline` | `ShipTime` 非空;出库费 |
| 6 列表 | `/order/list` | POST | `status=pendingOnline` | — | 包含该 `serviceNo` |
| 7 轨迹 | Mock 校验 | — | — | — | UpsertSmallBag 被调用 1 次 |
| 8 签收 | **Phase 2** | — | — | `deliverySuccess` | `SignTime` 非空 |
### 5.3 创建订单请求模板(E2E Fixture)
```json
{
"requestId": "e2e-{uuid}",
"clientNo": "E2E-CLIENT-{timestamp}",
"productCode": "E2E-SP-01",
"cargoAttribute": "general",
"warehouseId": 9001,
"length": 30,
"width": 20,
"height": 10,
"actualWeight": 1.2,
"quantity": 1,
"receiver": {
"name": "E2E Receiver",
"phone": "13800000001",
"countryCode": "US",
"state": "CA",
"city": "Los Angeles",
"address": "100 Test St",
"postcode": "90001"
},
"sender": {
"name": "E2E Sender",
"phone": "13900000001",
"countryCode": "CN",
"city": "Shenzhen",
"address": "Test Warehouse"
},
"items": [
{
"nameEn": "Test Goods",
"nameCn": "测试商品",
"quantity": 1,
"unitPrice": 10,
"weight": 1.2,
"hsCode": "6109100021"
}
]
}
```
### 5.4 入库 / 出库请求模板
```json
// POST /operation/inbound/create
{
"waybillNo": "{serviceNo}",
"weight": 1.2,
"length": 30,
"width": 20,
"height": 10,
"warehouseId": 9001
}
// POST /operation/outbound/create
{
"waybillNo": "{serviceNo}",
"weight": 1.2,
"length": 30,
"width": 20,
"height": 10,
"warehouseId": 9001
}
```
---
## 6. 功能模块与 API 映射
| 业务阶段 | 后端 Service | 前端模块 | 路由 | 权限(`pageButtonCatalog`) |
|----------|--------------|----------|------|---------------------------|
| 试算 / 下单 | `OrderService` | 物流下单 | `/order/placeOrder` | `Order.PlaceOrder.*` |
| 订单管理 | `OrderService` | 我的订单 | `/order/myOrders` | `Order.MyOrders.*` |
| 入库 | `InboundRecordService` | 入库扫描 | `/operation/inboundScan` | `Operation.InboundScan.Inbound` |
| 出库 | `OutboundRecordService` | 出库扫描 | `/operation/outboundScan` | `Operation.OutboundScan.Outbound` |
| 客户余额 | `CustomerBalanceMutator` | 客户管理 / 充值 | `/user/customer` | `User.Customer.*` |
| 应收应付 | `FinanceService` | 应收应付 | `/finance/receivablePayable` | `Finance.ReceivablePayable.Query` |
| 账户流水 | `CustomerAccountFlowService` | — | API | — |
| 渠道配置 | `SalesProductService` 等 | 销售产品 / 服务渠道 | `/channel/*` | 各模块 Query/Edit |
| 轨迹推送 | `SmallBagTrackOrderNotifier` | 我的订单-创建轨迹 | — | `Order.MyOrders.CreateTrackOrder` |
| 下游预报 | `OrderService.DownstreamForward` | 转发下游 | — | `Order.MyOrders.ForwardDownstreamCreate` |
| 批量任务 | `OrderBatchJobCoordinator` | 批量任务 | `/order/batchJobs` | `Order.BatchJobs.*` |
---
## 7. 断言检查点(每层必验)
### 7.1 HTTP 层
- 状态码 200(业务错误时 Fake 框架返回统一错误体,需断言 `message` 为空或 success 标志)
- 响应 JSON 关键字段类型与枚举值
### 7.2 订单主表 `t_order`
```sql
SELECT OrderStatus, IsPaid, ReceiveTime, PayTime, ShipTime, SignTime,
PredeclareFailReason, ChannelCode, ChargeableWeight
FROM t_order WHERE ServiceNo = @serviceNo;
```
| 步骤后 | OrderStatus | IsPaid | 时间字段 |
|--------|-------------|--------|----------|
| 创建 | `predeclared` | 0 | 全 NULL |
| 入库 | `pendingPayment` | 0 | ReceiveTime 有值 |
| 支付 | `pendingShip` | 1 | PayTime 有值 |
| 出库 | `pendingOnline` | 1 | ShipTime 有值 |
| 签收 | `deliverySuccess` | 1 | SignTime 有值 |
### 7.3 费用 `t_order_fee`
- 预报后:存在 `Type=receivable` 且 `ChargingStage` 含 forecast/predeclare
- 入库后:新增 `ChargingStage=inbound` 行(若产品配置入库计费)
- 出库后:新增 `ChargingStage=outbound` 行
- 支付金额 = 当前应收合计
### 7.4 客户财务
```sql
SELECT Balance FROM t_customer WHERE Id = @customerId;
SELECT * FROM t_customer_account_flow
WHERE BizType = 'orderPay' AND BizId = @orderId;
```
- 支付后:`Balance` 减少额 = 订单应收合计
- 流水 `Amount` 为负,`BalanceBefore/After` 连贯
### 7.5 仓储记录
```sql
SELECT * FROM t_inbound_record WHERE WaybillNo = @serviceNo;
SELECT * FROM t_outbound_record WHERE WaybillNo = @serviceNo;
```
### 7.6 轨迹 Mock
- WireMock 收到 `POST /OrderV2/UpsertSmallBag`
- 请求头含 `appKey`、`timestamp`、`sign`(签名算法见 `SmallBagTrackSignHelperTests`)
---
## 8. 负向与分支用例(摘要)
| 编号 | 场景 | 触发 | 期望 |
|------|------|------|------|
| N01 | 余额不足支付 | 客户 Balance < 应收 | `账户余额不足` |
| N02 | 未入库支付 | 跳过步骤 3 直接 pay | `当前订单状态不可支付` |
| N03 | 未支付出库 | 跳过步骤 4 直接 outbound | `订单未付款,禁止出库` |
| N04 | 重复支付 | pay 两次 | `订单已支付` |
| N05 | 价格未配置 | 错误 productCode | `draft` + `PredeclareFailReason` |
| N06 | 黑名单国家/客户 | 命中黑名单 | 创建失败,不落库或 draft |
| N07 | 拦截单出库 | intercept 后 outbound | 按业务规则拒绝或警告 |
| B01 | 问题件流程 | mark-problematic | `problematic` + `handleStatus=pending` |
| B02 | 处理完成 | handle-status/update | `handleStatus=processed` |
| B03 | 批量支付 | `/order/batch/pay` + RabbitMQ | Job 全部 success(独立 job) |
---
## 9. 自动化实现建议
### 9.1 推荐新建项目结构(后端)
```text
oms0414-back/
src/
Oms.E2E.Tests/ # 新建
Fixtures/
OrderLifecycleFixture.cs # 登录、种子数据、清理
WireMockTrackServer.cs
Scenarios/
OrderLifecycleHappyPathTests.cs
OrderLifecycleNegativeTests.cs
sql/
seed_e2e_order_lifecycle.sql
assert_order_state.sql
appsettings.E2E.json
```
### 9.2 技术选型
| 能力 | 库 |
|------|-----|
| API 宿主 | 复用 `SimpleAdminApiTestHost` 或 `WebApplicationFactory` + 真实 MySQL |
| DB 断言 | `Dapper` / 直接 `SqlSugar` 查询 |
| HTTP 客户端 | `HttpClient` + `System.Text.Json` |
| Mock 外服 | `WireMock.Net` |
| 测试框架 | xUnit + FluentAssertions(与现有一致) |
### 9.3 示例测试类骨架(伪代码)
```csharp
[Collection("OrderLifecycle")]
public class OrderLifecycleHappyPathTests
{
[Fact]
public async Task Step01_To_Step05_PendingOnline_ShouldSucceed()
{
var token = await Fixture.LoginAsCustomerAsync();
var create = await Fixture.Api.PostJsonAsync("/admin/order/parcel/create", body, token);
create.OrderStatus.Should().Be("predeclared");
var serviceNo = create.ServiceNo;
await Fixture.Api.PostJsonAsync("/admin/operation/inbound/create", inboundBody, operatorToken);
await Fixture.AssertOrderStatusAsync(serviceNo, "pendingPayment");
await Fixture.Api.PostJsonAsync("/admin/order/pay", new { id = create.Id }, token);
await Fixture.AssertOrderStatusAsync(serviceNo, "pendingShip");
await Fixture.AssertBalanceDebitedAsync(create.CustomerId, create.Id);
await Fixture.Api.PostJsonAsync("/admin/operation/outbound/create", outboundBody, operatorToken);
await Fixture.AssertOrderStatusAsync(serviceNo, "pendingOnline");
Fixture.TrackMock.VerifyUpsertCalledOnce(serviceNo);
}
}
```
### 9.4 数据隔离策略
| 策略 | 做法 |
|------|------|
| **A 每用例独立 clientNo** | `E2E-{guid}`,不删库,靠唯一键隔离(推荐) |
| **B 事务回滚** | SqlSugar 难包裹跨 HTTP 请求,不推荐 |
| **C 每 job 重建库** | CI 慢但最干净;夜间全量 E2E 使用 |
---
## 10. CI/CD 流水线设计
```mermaid
flowchart LR
PR[PR / Push] --> L1[dotnet test Oms.Tests]
L1 --> L2[dotnet test IntegrationTests]
L2 --> E2E{main 分支?}
E2E -->|是| Docker[启动 MySQL + WireMock]
Docker --> Seed[执行 seed_e2e_order_lifecycle.sql]
Seed --> L3[dotnet test Oms.E2E.Tests]
L3 --> Report[测试报告 / 飞书通知]
```
### 10.1 GitHub Actions 示例(片段)
```yaml
jobs:
unit-and-integration:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: dotnet test src/Oms.Tests
- run: dotnet test src/SimpleAdmin.Api.IntegrationTests
order-lifecycle-e2e:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
services:
mysql:
image: mysql:8.0
env:
MYSQL_ROOT_PASSWORD: test
MYSQL_DATABASE: oms_test
steps:
- run: mysql -h 127.0.0.1 -uroot -ptest oms_test < db.sql
- run: mysql -h 127.0.0.1 -uroot -ptest oms_test < sql/seed_e2e_order_lifecycle.sql
- run: dotnet test src/Oms.E2E.Tests --filter Category=E2E
```
### 10.2 本地一键脚本(建议 `scripts/run-order-e2e.ps1`)
```powershell
docker compose -f docker-compose.e2e.yml up -d
dotnet test src/Oms.E2E.Tests
docker compose -f docker-compose.e2e.yml down
```
---
## 11. Phase 2:签收段衔接方案
OMS 尚未实现 `shipping` → `deliverySuccess` 回写时,任选其一:
| 方案 | 说明 | 适用 |
|------|------|------|
| **P2-A Track 侧完成** | 调 `trackApi/Track/Order/UpdateOrderStatus` 置 `isCompleted=true` | 验证轨迹系统闭环 |
| **P2-B 测试专用 API** | 新增 `[TestingOnly] POST /order/test/mark-delivered` | 仅 Testing 环境注册 |
| **P2-C SQL 置态** | E2E 直接 `UPDATE t_order SET OrderStatus='deliverySuccess', SignTime=NOW()` | 临时;不验 API |
| **P2-D 实现正式回调** | Track Webhook → OMS Consumer | 生产方案,纳入同一 E2E |
**推荐路径**:先 **P2-B** unblock E2E,上线前替换为 **P2-D** 并删除测试 API。
---
## 12. 实施路线图
| 阶段 | 交付物 | 工时估 |
|------|--------|--------|
| **P0** | 本文档 + `seed_e2e_order_lifecycle.sql` | 1d |
| **P1** | `Oms.E2E.Tests` Happy Path(至 pendingOnline) | 2–3d |
| **P1** | WireMock Track + 负向用例 N01–N04 | 1d |
| **P2** | 签收置态 / Webhook + 完整端到签收 | 2d |
| **P3** | Playwright 冒烟(下单页 + 扫描页) | 2d |
| **P3** | CI nightly + 测试报告 | 1d |
---
## 13. 关键代码与文档索引
### 后端
| 路径 | 说明 |
|------|------|
| `Oms.Domain/OrdersAggregate/Consts/OrderStatusCodes.cs` | 订单状态枚举 |
| `Oms.Application/Services/Orders/OrderService.ParcelBilling.cs` | 创建、入库/出库计费 |
| `Oms.Application/Services/Orders/OrderService.cs` | 支付、列表 |
| `Oms.Application/Services/Operations/InboundRecordService.cs` | 入库 |
| `Oms.Application/Services/Operations/OutboundRecordService.cs` | 出库 |
| `Oms.Application/Shared/CustomerBalanceMutator.cs` | 支付扣款 |
| `Oms.Application/Integrations/SmallBagTrack/` | 轨迹推送 |
| `SimpleAdmin.Api.IntegrationTests/Support/SimpleAdminApiTestHost.cs` | 集成测试宿主 |
| `Oms.Tests/ParcelBillingCalculatorTests.cs` | 计费单元测试 |
### 前端
| 路径 | 说明 |
|------|------|
| `src/constants/orderStatus.ts` | 状态常量 |
| `src/api/order/index.ts` | 订单 API |
| `src/api/operation/index.ts` | 仓储 API |
| `src/views/order/placeOrder/index.vue` | 下单页 |
| `src/views/operation/inboundScan/index.vue` | 入库 |
| `src/views/operation/outboundScan/index.vue` | 出库 |
### 文档
| 路径 | 说明 |
|------|------|
| `docs/oms系统设计-050801.md` | 主设计(§4 订单、§6 操作、§10.3 状态码) |
| `docs/物流下单协议.md` | parcel/create 协议 |
| `docs/订单批量处理与异步队列方案0707.md` | 批量异步 |
---
## 14. 附录:手动冒烟检查清单(5 分钟)
自动化未就绪时,可按此手工验证主链路:
- [ ] 客户登录,余额 ≥ 100
- [ ] 销售产品 `E2E-SP-01` 已发布且 US 有价格
- [ ] `POST /order/parcel/create` → 返回 `predeclared`
- [ ] `POST /operation/inbound/create` → 订单变 `pendingPayment`
- [ ] `POST /order/pay` → `pendingShip`,余额减少
- [ ] `POST /operation/outbound/create` → `pendingOnline`
- [ ] `GET /order/detail` → `ReceiveTime`、`PayTime`、`ShipTime` 均有值
- [ ] (可选)Track Mock 日志有 UpsertSmallBag
---
## 15. 已落地实现(2026-07-08)
| 交付物 | 路径 |
|--------|------|
| E2E 主数据种子 | `oms0414-back/sql/seed_e2e_order_lifecycle.sql` |
| E2E 测试项目 | `oms0414-back/src/Oms.E2E.Tests/` |
| Happy Path 用例 | `Scenarios/OrderLifecycleHappyPathTests.cs` |
| 一键脚本 | `oms0414-back/scripts/run-order-e2e.ps1` |
**运行方式:**
```powershell
$env:OMS_E2E_ENABLED = "1"
$env:OMS_E2E_CONNECTION = "Server=127.0.0.1;Port=3306;Database=oms;Uid=root;Pwd=你的密码;CharSet=utf8mb4;"
cd oms0414-back
.\scripts\run-order-e2e.ps1
```
未设置 `OMS_E2E_ENABLED` 时,E2E 用例自动跳过(不失败)。
---
**维护说明**:OMS 实现签收回写后,更新 §1.2 边界表、§5 步骤 8、§11,并将 Phase 2 用例并入 P1 必跑集。

View File

@ -0,0 +1,664 @@
# 订单批量处理与异步队列方案
> **文档定位**:梳理 OMS 后端现有订单批量相关 API、执行模式与可复用资产,并给出统一异步队列改造建议。
> **对照仓库**:`C:\Users\wilso\Desktop\oms0414-back`(`SimpleAdmin.sln`)
> **前端对照**:`E:\oms0414\src\views\order\myOrders\index.vue`
> **关联文档**:`docs/oms系统设计-050801.md`(订单章)、`docs/rbac系统设计-060801.md`(权限)
> **编写日期**:2026-07-07
> **技术决策**:**选用 RabbitMQ** 作为订单批量异步队列方案(v2.0)
---
## 1 导读
### 1.1 这份文档解决什么问题?
1. **盘点**当前后端所有「批量处理订单」相关 HTTP 接口(含原生批量与前端循环伪批量)。
2. **说明**各接口入参/出参、Service 实现位置、同步/异步执行方式。
3. **指出**现有最接近队列的组件(`t_order_task`、`SmallBagTrackOrderNotifier`)及其局限。
4. **建议**按业务类型划分异步队列、统一批量 Job API 草案与落地优先级。
5. **定义**基于 **RabbitMQ** 的交换机/队列拓扑、消息契约、Consumer 与 Fake 框架集成方式(**已定稿**)。
### 1.2 技术决策
| 项 | 决策 |
| --- | --- |
| 消息中间件 | **RabbitMQ** |
| .NET 接入 | 优先复用 Fake 生态 **`Fake.RabbitMQ`**(连接池/通道池);订单 Job 使用 **Work Queue 模式** 自建 Publisher/Consumer |
| 与 `Fake.EventBus.RabbitMQ` 关系 | 事件总线用于**跨模块集成事件**(如 Job 完成通知);**订单子任务投递不走 EventBus**,走专用 Work Queue |
| 状态持久化 | MySQL **`t_order_batch_job` / `t_order_batch_job_item`** 为权威进度;MQ 仅负责调度与重试 |
| 宿主部署 | `SimpleAdmin.Api` 进程内注册 Consumer(`IHostedService`);后期可拆独立 Worker 项目 |
### 1.3 现状结论(摘要)
| 维度 | 现状 |
| --- | --- |
| API 暴露 | `OrderService`(partial class)上 `[HttpPost]` / `[HttpGet]`,Fake 动态 API,**无手写 Controller** |
| 原生批量 API | 异常件 3 个 + 小包 `batch-create` + Excel 导入 + 条件导出,共 **5 类** |
| 伪批量 | My Orders 页 **8 个单票 API**,前端 `for` 循环逐条调用 |
| 队列基础设施 | **规划 RabbitMQ**(项目基线已约定 MQ,见 `oms0414-back/开发复刻说明.md`);当前代码**尚未引用** `Fake.RabbitMQ` |
| 轻量异步 | `SmallBagTrackOrderNotifier` 使用 `Task.Run`(无持久化、无重试) |
| 任务表 | `t_order_task` 记录 Excel 导入进度,但处理仍在 **HTTP 请求内同步完成** |
| 权限 | 前端 `Order.MyOrders.*`;**后端 API 未做细粒度 PermissionCode 校验** |
---
## 2 接口总览
```mermaid
flowchart LR
subgraph api [SimpleAdmin.Api]
HTTP["/order/batch/jobs"]
OS[OrderService]
end
subgraph db [MySQL]
JOB[t_order_batch_job]
ITEM[t_order_batch_job_item]
end
subgraph rmq [RabbitMQ]
EX["exchange: oms.order.batch"]
QD["queue: order.batch.integration"]
QA["queue: order.batch.account"]
QB["queue: order.batch.state"]
QC["queue: order.batch.exception"]
QE["queue: order.batch.document"]
QF["queue: order.batch.create"]
DLX["DLX: oms.order.batch.dlx"]
end
subgraph consumers [Consumers IHostedService]
CD[IntegrationConsumer]
CA[AccountConsumer]
CB[StateConsumer]
CC[ExceptionConsumer]
CE[DocumentConsumer]
CF[CreateConsumer]
end
HTTP --> JOB
HTTP --> EX
EX --> QD & QA & QB & QC & QE & QF
QD & QA & QB & QC & QE & QF --> consumers
consumers --> ITEM
consumers --> OS
QD & QA & QB & QC & QE & QF -.失败.-> DLX
```
### 2.1 分类一览(改造后目标)
```mermaid
flowchart TB
subgraph native [原生批量 API]
EP["/order/mark-problematic<br/>/order/mark-claimed<br/>/order/handle-status/update"]
PCB["/order/parcel/batch-create"]
UP["/order/upload + task/*"]
EX["/order/export"]
end
subgraph pseudo [伪批量 - 前端循环单票 API]
PAY["/order/pay"]
PD["/order/pre-declare"]
INT["/order/intercept / cancel-intercept"]
DEL["/order/delete"]
PRT["/order/print"]
TRK["/order/track-upsert-small-bag"]
DS["/order/downstream-forward-create-one"]
end
subgraph svc [OrderService 同步处理]
OS[OrderService partial]
end
subgraph async_hint [现有轻量异步]
OT[t_order_task 仅记录]
STN[SmallBagTrackOrderNotifier Task.Run]
end
native --> OS
pseudo --> OS
UP --> OT
PCB --> STN
```
### 2.2 原生批量 API 清单
| 路由 | 方法 | Service 方法 | 文件 | 批量语义 | 上限 | 执行模式 |
| --- | --- | --- | --- | --- | --- | --- |
| `/order/mark-problematic` | POST | `MarkProblematicAsync` | `OrderService.Exception.cs` | `List<int> OrderIds` | 200 | 同步 foreach,部分成功 |
| `/order/mark-claimed` | POST | `MarkClaimedAsync` | 同上 | `List<int> OrderIds` | 200 | 同上 |
| `/order/handle-status/update` | POST | `UpdateHandleStatusAsync` | 同上 | `List<int> OrderIds` | 200 | 同上(仅 `processed`) |
| `/order/parcel/batch-create` | POST | `BatchCreateParcelAsync` | `OrderService.cs` | `List<OrderParcelCreateInput>` | 2000 | 同步 for,逐条明细 |
| `/order/upload` | POST | `UploadAsync` → `ImportOrdersAsync` | `OrderService.Helpers.cs` | Excel 多行 | — | 同步逐行 + 写 `OrderTask` |
| `/order/task/list` | GET | `GetTaskListAsync` | `OrderService.Helpers.cs` | 查询导入任务 | — | 只读 |
| `/order/task/detail` | GET | `GetTaskDetailAsync` | 同上 | 含失败行 | — | 只读 |
| `/order/export` | POST | `ExportAsync` | `OrderService.cs` | 筛选条件全量 | — | 同步生成 xlsx |
### 2.3 伪批量 API 清单(单票入参,前端循环)
| 路由 | 方法 | Service 方法 | 文件 | 业务特点 | 前端权限码(参考) |
| --- | --- | --- | --- | --- | --- |
| `/order/pay` | POST | `PayAsync` | `OrderService.cs` | **扣客户余额**,需事务/幂等 | `Order.MyOrders.Pay` |
| `/order/pre-declare` | POST | `PreDeclareAsync` | 同上 | 改订单状态 | `Order.MyOrders.PreDeclare` |
| `/order/intercept` | POST | `InterceptAsync` | 同上 | `IsIntercept=1` | `Order.MyOrders.Intercept` |
| `/order/cancel-intercept` | POST | `CancelInterceptAsync` | 同上 | `IsIntercept=0` | `Order.MyOrders.CancelIntercept` |
| `/order/delete` | POST | `DeleteAsync` | 同上 | 软删 + 物理删 | `Order.MyOrders.Delete` |
| `/order/print` | POST | `PrintAsync` | `OrderService.Helpers.cs` | 生成打印 HTML | `Order.MyOrders.Print` / `BatchPrint` |
| `/order/track-upsert-small-bag` | POST | `TrackUpsertSmallBagAsync` | `OrderService.ParcelBilling.cs` | HTTP 调轨迹服务 | `Order.MyOrders.CreateTrack` |
| `/order/downstream-forward-create-one` | POST | `DownstreamForwardCreateOneAsync` | `OrderService.DownstreamForward.cs` | HTTP 调下游 itfx | `Order.MyOrders.ForwardDownstream` |
**公共入参** `OrderActionInput`:
```csharp
public class OrderActionInput
{
[Required] public int Id { get; set; }
[StringLength(64)] public string? RequestId { get; set; }
}
```
**辅助只读**:
| 路由 | 方法 | 说明 |
| --- | --- | --- |
| `/order/downstream-create-one-body` | GET | 预览下游请求体,不实际转发 |
### 2.4 单票编辑类 API(详情抽屉,非列表批量)
| 路由 | 方法 | Service 方法 | 文件 |
| --- | --- | --- | --- |
| `/order/update` | POST | `UpdateOrderDetailAsync` | `OrderService.OrderEdit.cs` |
| `/order/weight/update` | POST | `UpdateOrderWeightsAsync` | 同上 |
| `/order/fee/recalculate-receivable` | POST | `RecalculateReceivableFeesAsync` | 同上 |
| `/order/fee/recalculate-payable` | POST | `RecalculatePayableFeesAsync` | 同上 |
| `/order/fee/add` | POST | `AddOrderFeeAsync` | 同上 |
| `/order/parcel/create` | POST | `CreateParcelAsync` | `OrderService.cs` / `ParcelBilling.cs` |
### 2.5 非 OrderIds 的「批量数据处理」
| 路由 | 方法 | 说明 |
| --- | --- | --- |
| `/order/price-check` | POST | 多产品 × 多仓库运费试算,同步嵌套循环 |
| `/order/list` | POST | 分页列表 |
| `/order/status-counts` | GET | 状态 Tab 计数 |
---
## 3 DTO 与出参模型
### 3.1 异常件批量(推荐复用为队列 Job 汇总出参)
**文件**:`Oms.Application/Dtos/Orders/OrderExceptionDtos.cs`
```csharp
// 统一批量出参
public class OrderBatchActionResultOutput
{
public int SuccessCount { get; set; }
public List<OrderBatchActionFailureOutput> Failures { get; set; } = [];
}
public class OrderBatchActionFailureOutput
{
public int OrderId { get; set; }
public string? ServiceNo { get; set; }
public string Reason { get; set; } = string.Empty;
}
// 问题件
public class OrderMarkProblematicInput
{
public List<int> OrderIds { get; set; } = [];
public int? IssueTemplateId { get; set; }
public string? IssueType { get; set; }
public string? Title { get; set; }
public string? Content { get; set; }
public string? Remark { get; set; }
}
// 理赔件
public class OrderMarkClaimedInput
{
public List<int> OrderIds { get; set; } = [];
public string? ClaimType { get; set; }
public decimal? ClaimAmount { get; set; }
public string? ClaimCurrency { get; set; }
public string? ClaimReason { get; set; }
public string? Remark { get; set; }
}
// 标记已处理
public class OrderHandleStatusUpdateInput
{
public List<int> OrderIds { get; set; } = [];
public string? HandleStatus { get; set; }
public string? Remark { get; set; }
}
```
**内部约束**:`MaxExceptionBatchSize = 200`(`OrderService.Exception.cs`)。
### 3.2 小包批量创建
**文件**:`Oms.Application/Dtos/Orders/OrderParcelBatchCreateInput.cs` 等
- **入参**:`OrderParcelBatchCreateInput` 继承 `List<OrderParcelCreateInput>`,单条结构与 `/order/parcel/create` 一致。
- **出参**:`OrderParcelBatchCreateOutput { BatchNo, SuccessCount, FailCount, Items[] }`
- **上限**:`ParcelBatchMaxCount = 2000`(`OrderService.ParcelBilling.cs`)
### 3.3 Excel 导入
| DTO | 字段 |
| --- | --- |
| `OrderUploadInput` | `File` (IFormFile), `TemplateId` |
| `OrderUploadOutput` | `TaskId` |
| `OrderTaskListInput` | 分页查询参数 |
| `OrderTaskOutput` / `OrderTaskDetailOutput` | 任务汇总 + 失败明细 `FailList` |
### 3.4 条件导出
| DTO | 字段 |
| --- | --- |
| `OrderExportInput` | `status`, `keyword`, `createTimeStart`, `createTimeEnd` |
| `OrderExportOutput` | `downloadUrl`, `expireAt`(24h 过期) |
---
## 4 现有执行模式详解
### 4.1 异常件批量(已实现部分成功)
**调用链**:
```
MarkProblematicAsync / MarkClaimedAsync / UpdateHandleStatusAsync
→ NormalizeOrderIds(去重、非空、≤200)
→ ExecuteProblematicBatchAsync / ExecuteExceptionBatchAsync
→ 逐条 try/catch,成功 SuccessCount++,失败写入 Failures
```
**问题件单条逻辑**:`OrderExceptionWorkflowService.TryMarkProblematicAsync`(`Issues/OrderExceptionWorkflowService.cs`),含通知(`OrderIssueNotificationService`)。
### 4.2 小包批量创建
```
BatchCreateParcelAsync
→ 生成 BatchNo
→ for each OrderParcelCreateInput
→ CreateParcelCoreAsync(预报、计费、落库)
→ 成功则 EnqueueSmallBagTrackUpsertAsync(轨迹)
→ 返回逐条 Items 明细
```
### 4.3 Excel 导入(有任务表,非真异步)
```
UploadAsync → ImportOrdersAsync
→ Insert OrderTask(Status=processing)
→ foreach Excel 行
→ CreateImportOrderAsync 或记录 OrderTaskFail
→ 更新 task Quantity / SuccessCount / FailCount / Status=completed
→ 返回 { taskId }
```
**局限**:整个导入阻塞当前 HTTP 请求;`Status=processing` 仅为记录,无独立 Consumer。
### 4.4 轨迹轻量异步(现有唯一 fire-and-forget)
**文件**:`Oms.Application/Integrations/SmallBagTrack/SmallBagTrackOrderNotifier.cs`
```csharp
public void Enqueue(SmallBagTrackUpsertRequest request)
{
_ = Task.Run(async () =>
{
using var scope = scopeFactory.CreateScope();
var client = scope.ServiceProvider.GetRequiredService<ISmallBagTrackOrderClient>();
await client.UpsertAsync(request);
});
}
```
**性质**:单票、内存队列、无持久化、无重试、进程重启即丢失。
### 4.5 前端伪批量行为
**文件**:`src/views/order/myOrders/index.vue`
- 勾选多行后,对 `pay` / `pre-declare` / `intercept` 等 **逐条 POST** `OrderActionInput`。
- 支付等操作:**任一失败即中断**,无部分成功汇总(与异常件 API 不同)。
- 批量打印 / 轨迹 / 下游:循环调用后前端汇总结果弹窗。
---
## 5 现有基础设施盘点
| 组件 | 是否存在 | 说明 |
| --- | --- | --- |
| RabbitMQ Work Queue | ❌ 未接入 | **本期建设** |
| `Fake.RabbitMQ` | ❌ 未引用 | 连接池/通道池,见 `SPEC.md` §9.3 |
| `Fake.EventBus.RabbitMQ` | ❌ 未引用 | 可选,用于 Job 完成等集成事件 |
| 订单专用 `IHostedService` | ❌ | 无 |
| `BackgroundService` | ✅ 1 个 | 仅 `XhsScheduledPublishWorker`(小红书定时发布) |
| `Task.Run` | ✅ | 轨迹 UpsertSmallBag、导出文件清理等 |
| `t_order_task` | ✅ | 导入任务记录 + `t_order_task_fail` 失败行 |
| `SmallBagTrackOrderNotifier` | ✅ | 内存 fire-and-forget |
### 5.1 OrderTask 实体(可演进为通用批量 Job 表)
**表**:`t_order_task`
**实体**:`Oms.Domain/OrdersAggregate/Entities/OrderTask.cs`
| 字段 | 说明 |
| --- | --- |
| `TaskName` | 如 `批量下单_yyyyMMddHHmmss` |
| `Quantity` | 总条数 |
| `SuccessCount` / `FailCount` | 成功/失败计数 |
| `Status` | `processing` → `completed` |
| `TemplateId` | Excel 模板 Id |
| `CustomerId` | 客户归属 |
**演进建议**:扩展 `Action`、`PayloadJson`、`StartedAt`、`FinishedAt`,或新建 `t_order_batch_job` 与之并存。
---
## 6 RabbitMQ 队列分组(与业务 Action 映射)
按 **业务风险 + 耗时 + 外部依赖** 划分 **6 条业务队列** + **1 条死信队列**:
| 队列组 | RabbitMQ Queue | Routing Key | 包含 Action | 并发建议 | Prefetch |
| --- | --- | --- | --- | --- | --- |
| **D. 外部集成** | `oms.order.batch.integration` | `integration.*` | `track-upsert-small-bag`, `downstream-forward-create-one` | 中(限流防打爆下游) | 5 |
| **F. 订单创建** | `oms.order.batch.create` | `create.*` | `parcel-create`, `import-row` | 中 | 10 |
| **A. 账务** | `oms.order.batch.account` | `account.*` | `pay` | **低**(按 CustomerId 串行) | 1 |
| **B. 状态变更** | `oms.order.batch.state` | `state.*` | `pre-declare`, `intercept`, `cancel-intercept`, `delete`, `handle-status-update` | 高 | 20 |
| **C. 异常工作流** | `oms.order.batch.exception` | `exception.*` | `mark-problematic`, `mark-claimed` | 中 | 10 |
| **E. 文档生成** | `oms.order.batch.document` | `document.*` | `print`, `export` | 低 | 3 |
| **死信** | `oms.order.batch.dlx` | — | 超过最大重试的子任务 | — | — |
**Exchange**:`oms.order.batch`(类型 **topic**,持久化 `durable=true`)。
### 6.1 落地顺序建议
1. **D(外部集成)** — 轨迹、下游预报最阻塞 HTTP,且已有 `SmallBagTrackOrderNotifier` 可替换为 Publisher。
2. **F(创建/导入)** — `OrderTask` 表与失败明细已就绪,补 Worker 即可真异步。
3. **A(支付)** — 资金类须严格幂等与对账。
4. **B / C / E** — 按产品优先级迭代。
---
## 7 统一批量 Job API 草案
### 7.1 路由设计
| 路由 | 方法 | 说明 |
| --- | --- | --- |
| `/order/batch/jobs` | POST | 创建批量任务,写 DB 并 Publish 到 RabbitMQ,立即返回 `jobId` |
| `/order/batch/jobs/{id}` | GET | 查询进度与汇总结果 |
| `/order/batch/jobs/{id}/items` | GET | 逐条明细(成功/失败/进行中) |
| `/order/batch/jobs/{id}/cancel` | POST | 取消未执行子任务(可选) |
| `/order/batch/jobs/{id}/retry-failed` | POST | 将 failed 子任务重新 Publish(可选) |
### 7.2 入参草案
```csharp
public class OrderBatchJobCreateInput
{
/// <summary>
/// pay | pre-declare | intercept | cancel-intercept | delete |
/// print | track-upsert-small-bag | downstream-forward-create-one |
/// mark-problematic | mark-claimed | handle-status-update | export | ...
/// </summary>
public string Action { get; set; } = string.Empty;
public List<int> OrderIds { get; set; } = [];
public JsonElement? Payload { get; set; }
public string? RequestId { get; set; }
}
```
### 7.3 出参草案
```csharp
public class OrderBatchJobOutput
{
public long JobId { get; set; }
public string Action { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
public int Total { get; set; }
public int SuccessCount { get; set; }
public int FailCount { get; set; }
public DateTime? StartedAt { get; set; }
public DateTime? FinishedAt { get; set; }
}
```
单条明细复用 `OrderBatchActionFailureOutput`,扩展 `Status`:`pending` / `running` / `success` / `failed`。
---
## 8 RabbitMQ 实施方案(已定稿)
### 8.1 为何选 RabbitMQ
| 能力 | 说明 |
| --- | --- |
| 持久化队列 | 进程重启不丢任务(配合 `delivery_mode=2`) |
| 死信 + 延迟重试 | 业务失败与系统失败分离治理 |
| 多队列隔离 | 支付、外部 HTTP、导入互不阻塞 |
| 水平扩展 | 多 API/Worker 实例共享 Consumer |
| 与项目基线一致 | `开发复刻说明.md` 已约定 RabbitMQ;Fake 提供 `Fake.RabbitMQ` 连接池 |
**不采用 Hangfire / DB 轮询的原因**:订单批量含大量外部 HTTP 与长耗时导入,需要独立队列削峰与跨实例消费;DB 轮询难以优雅做按客户串行与 DLX。
### 8.2 NuGet 与模块依赖
在 `SimpleAdmin.Api` / `Oms.Application` 增加:
```xml
<PackageReference Include="Fake.RabbitMQ" Version="$(FakePackageVersion)" />
<!-- 可选:Job 完成集成事件 -->
<PackageReference Include="Fake.EventBus.RabbitMQ" Version="$(FakePackageVersion)" />
```
模块依赖(`OmsApplicationModule` 或新建 `OmsRabbitMqModule`):
```csharp
[DependsOn(typeof(FakeRabbitMqModule))]
public class OmsRabbitMqModule : FakeModule { }
```
### 8.3 配置(appsettings / Consul)
```json
{
"RabbitMQ": {
"Connections": {
"Default": {
"HostName": "rabbitmq",
"Port": 5672,
"UserName": "oms",
"Password": "***",
"VirtualHost": "/oms"
}
}
}
}
```
队列声明在应用启动时由 `OrderBatchQueueInitializer`(`IHostedService`)执行:创建 Exchange、6 条业务 Queue、DLX、绑定关系。
### 8.4 消息契约
**队列消息体** `OrderBatchJobMessage`(JSON,Newtonsoft 驼峰):
```csharp
public class OrderBatchJobMessage
{
public long JobId { get; set; }
public long JobItemId { get; set; }
public string Action { get; set; } = string.Empty; // pay, delete, track-upsert-small-bag, ...
public int OrderId { get; set; }
public int? CustomerId { get; set; } // A 组串行键
public string? PayloadJson { get; set; } // Action 专用参数
public int OperatorUserId { get; set; }
public string MessageId { get; set; } = string.Empty; // 幂等键
public int RetryCount { get; set; }
}
```
**发布流程**:
```
POST /order/batch/jobs
→ 写 t_order_batch_job + items(status=pending)
→ 按 Action 映射 routingKey,逐条 Publish 到 oms.order.batch
→ 立即返回 { jobId }
```
**消费流程**:
```
Consumer 收到消息
→ 查 item 是否已成功(幂等跳过)
→ item.status=running
→ IOrderBatchActionExecutor.ExecuteAsync(message)
→ 成功:item.status=success,更新 job 计数
→ 业务失败:item.status=failed + reason,ACK
→ 系统失败:NACK requeue;RetryCount>=3 → DLX
→ job 全部终态后 status=completed
```
### 8.5 与现有组件的替换关系
| 现有 | 改造后 |
| --- | --- |
| `SmallBagTrackOrderNotifier`(`Task.Run`) | Publish 到 `oms.order.batch.integration`,routingKey=`integration.track-upsert` |
| `ImportOrdersAsync` 同步 foreach | 上传存文件/OSS → 写 job → 每行一条消息到 `oms.order.batch.create` |
| 前端 My Orders 循环 `pay` 等 | 统一 `POST /order/batch/jobs`,轮询 `GET /order/batch/jobs/{id}` |
| 异常件 API `mark-problematic` 等 | **兼容期保留同步 API**;新增 `async=true` 或独立 Job API 走 MQ |
### 8.6 重试与死信策略
| 场景 | 策略 |
| --- | --- |
| 下游 HTTP 超时/5xx | NACK + requeue,指数退避(`x-message-ttl` + DLX 延迟队列,或 Consumer 内 `Task.Delay` 后重发) |
| 业务校验失败(已支付、状态不允许) | 记 failed,**ACK 不重试** |
| 消息重复消费 | `MessageId` + DB 唯一约束,已 success 则直接 ACK |
| DLX 堆积 | 告警 + 管理端「重新投递」接口 |
建议队列参数:
```
x-dead-letter-exchange: oms.order.batch.dlx
x-dead-letter-routing-key: dead
```
### 8.7 部署拓扑
```mermaid
flowchart TB
subgraph prod [生产环境]
API1[SimpleAdmin.Api 实例 1]
API2[SimpleAdmin.Api 实例 2]
RMQ[RabbitMQ Cluster]
MySQL[(MySQL)]
end
API1 & API2 -->|Publish/Consume| RMQ
API1 & API2 --> MySQL
FE[oms0414 前端] -->|创建 Job / 轮询进度| API1
```
- **第一期**:Consumer 与 API 同进程(`IHostedService`),减少运维复杂度。
- **第二期**:拆 `Oms.OrderWorker` 独立控制台项目,仅引用 `Oms.Application` + Consumers。
### 8.8 本地开发
`docker-compose` 增加 RabbitMQ 服务(管理台 15672):
```yaml
rabbitmq:
image: rabbitmq:3.13-management
ports:
- "5672:5672"
- "15672:15672"
environment:
RABBITMQ_DEFAULT_USER: oms
RABBITMQ_DEFAULT_PASS: oms123
RABBITMQ_DEFAULT_VHOST: /oms
```
### 8.9 Consumer 执行原则
1. **复用现有 Service**:`IOrderBatchActionExecutor` 按 `action` 分发,内部调用抽离后的单条逻辑。
2. **幂等**:`MessageId = {jobId}:{orderId}:{action}`;DB 唯一键 `(JobId, OrderId, Action)`;支付额外校验 `IsPaid`。
3. **部分成功**:业务失败 ACK 并写 `failed`;系统失败 NACK requeue,超次进 DLX。
4. **并发**:A 组 `prefetch=1` + `customerId` 串行;D 组全局限流。
5. **可观测**:日志带 `JobId/OrderId/Action`;可选 `OrderBatchJobCompletedEto` 走 `Fake.EventBus.RabbitMQ`。
---
## 9 关键文件索引(规划新增)
| 文件(规划路径) | 职责 |
| --- | --- |
| `Oms.Application/Messaging/OrderBatchJobMessage.cs` | MQ 消息契约 |
| `Oms.Application/Messaging/IOrderBatchJobPublisher.cs` | Publish 抽象 |
| `Oms.Application/Messaging/OrderBatchQueueInitializer.cs` | 启动声明 Exchange/Queue |
| `Oms.Application/Workers/OrderBatch/*Consumer.cs` | 6 组 RabbitMQ Consumer |
| `Oms.Application/Services/Orders/Batch/IOrderBatchActionExecutor.cs` | Action 执行分发 |
| `Oms.Application/Services/Orders/OrderService.cs` | pay/delete/export/batch-create/upload 等主 API |
| `Oms.Application/Services/Orders/OrderService.Exception.cs` | 原生 `OrderIds` 批量异常件 API |
| `Oms.Application/Services/Orders/OrderService.ParcelBilling.cs` | 小包创建、轨迹同步 |
| `Oms.Application/Services/Orders/OrderService.DownstreamForward.cs` | 下游预报转发 |
| `Oms.Application/Services/Orders/OrderService.Helpers.cs` | Excel 导入、打印、任务查询 |
| `Oms.Application/Integrations/SmallBagTrack/SmallBagTrackOrderNotifier.cs` | 待替换为 MQ Publisher |
| `Oms.Domain/OrdersAggregate/Entities/OrderBatchJob.cs` | Job 实体(规划) |
| `src/views/order/myOrders/index.vue` | 前端伪批量循环(待改 Job API) |
---
## 10 与主设计文档的关系
- 订单状态机、费用、模板字段详见 **`docs/oms系统设计-050801.md` 第 4 章**。
- 客户隔离、`CustomerId` 解析见 **OMS 设计 §1.4** 与 **RBAC 设计文档**。
- Fake 框架 RabbitMQ 能力见 **`oms0414-back/SPEC.md` §9.3**(`Fake.RabbitMQ`、`Fake.EventBus.RabbitMQ`)。
---
## 11 后续工作清单(RabbitMQ 实施)
### 阶段一:基础设施(D 组)
- [ ] `docker-compose` / 生产环境部署 RabbitMQ(vhost `/oms`)
- [ ] 引用 `Fake.RabbitMQ`,配置 `RabbitMQ:Connections:Default`
- [ ] 新建 `OmsRabbitMqModule`、`OrderBatchQueueInitializer`
- [ ] 新建 `t_order_batch_job` / `t_order_batch_job_item` 表
- [ ] 实现 `IOrderBatchJobPublisher` + `OrderBatchJobMessage`
- [ ] 实现 `IntegrationBatchConsumer`(轨迹、下游预报)
- [ ] 替换 `SmallBagTrackOrderNotifier` 为 MQ Publish
### 阶段二:创建与导入(F 组)
- [ ] `/order/upload` 改为上传落库 + 按行入队 `oms.order.batch.create`
- [ ] `parcel/batch-create` 改为创建 Job 后异步消费
- [ ] 复用/扩展 `OrderTask` 与 `OrderBatchJob` 关系(如需兼容旧前端)
### 阶段三:统一 Job API + 前端
- [ ] 新增 `/order/batch/jobs` 系列 API
- [ ] 前端 My Orders 批量操作改 Job API + 进度轮询
- [ ] 实现 B/C/E/A 组 Consumer 与 `IOrderBatchActionExecutor`
### 阶段四:治理与测试
- [ ] DLX 监控告警、`retry-failed` 管理接口
- [ ] 补充 `SimpleAdmin.Api.IntegrationTests`(Publish → Consume → DB 状态)
- [ ] 可选:拆 `Oms.OrderWorker` 独立进程
---
*文档版本:v2.0 | 技术决策:RabbitMQ | 2026-07-07*

67
scripts/scan-report.txt Normal file
View File

@ -0,0 +1,67 @@
# 深度扫描报告
已收录 parent 数: 61
扫描页面数: 54
需补充/遗漏: 10
## api/downstreamInterface
parent: Api.DownstreamInterface
inCatalog: true
页面按钮: + | cancel | ↻ | 保存 | 修改 | 刷新列表 | 刷新接口列表 | 参数配置 | 取消 | 填充到表单 | 操作 | 新增接口 | 新增服务商 | 智能填充 | 调试 | 返回配置
目录缺失: + | cancel | ↻ | 操作
## api/upstreamInterface
parent: Api.UpstreamInterface
inCatalog: true
页面按钮: + | AI脚本 | ↻ | 保存 | 删除 | 前置脚本 | 发布 | 取消 | 后置脚本 | 回滚 | 回滚到此版本 | 导入 | 操作 | 新增 | 新增参数 | 新增系统参数 | 格式化 | 温馨提示 | 生成脚本 | 确定 | 解析 | 调试
目录缺失: + | ↻ | 操作 | 温馨提示
## channel/autoTrigger
parent: Channel.AutoTrigger
inCatalog: true
页面按钮: 上一页 | 新增
目录缺失: 上一页
## channel/issueTemplate
parent: Channel.IssueTemplate
inCatalog: true
页面按钮: 上一页 | 新增
目录缺失: 上一页
## system/dataPerm/templates
parent: Rbac.DataPerm.Template
inCatalog: true
页面按钮: 保存 | 写入角色权限 | 删 | 刷新列表 | 套用到用户 | 新建模板 | 普通销售 | 添加明细行 | 添加示例配置 | 请从左侧选择模板,或点击新建
目录缺失: 删 | 普通销售 | 请从左侧选择模板,或点击新建
## system/dataPerm/users
parent: Rbac.DataPerm
inCatalog: true
页面按钮: 刷新列表 | 请从左侧选择用户
目录缺失: 请从左侧选择用户
## system/dict
parent: System.Dict
inCatalog: true
页面按钮: submit') | 下载 OMS 预置字典 | 下载模板 | 取消 | 批量导入字典
目录缺失: submit')
## system/permission/role
parent: Rbac.Roles
inCatalog: true
页面按钮: 一级菜单 | 三级按钮 | 二级菜单 | 保存 | 保存权限 | 全选 | 刷新列表 | 取消全选 | 新增角色 | 请从左侧选择角色,或点击新增
目录缺失: 一级菜单 | 三级按钮 | 二级菜单 | 请从左侧选择角色,或点击新增
## system/xhsAiAssistant
parent: Xhs.Ai
inCatalog: true
页面按钮: ✎ | 保存 | 刷新 | 取消 | 清空
目录缺失: ✎
## xhs/skills
parent: Xhs.Skills
inCatalog: true
页面按钮: okText | ⎘ | ▶ | ✎ | 导入官方示例 | 搭配新技能 | 生成名称
目录缺失: okText | ⎘ | ▶ | ✎
# 完全未收录的 parentPermissionCode

View File

@ -0,0 +1,47 @@
import { axiosInstance } from '@/api/rbac'
import { assertBusinessOk, omsUrl, parseListPayload, unwrapData } from '@/api/oms/common'
function postList(path: string, body: Record<string, unknown>) {
return axiosInstance.post(omsUrl(path), body).then((res) => parseListPayload(res.data))
}
function postOk(path: string, body: Record<string, unknown>) {
return axiosInstance.post(omsUrl(path), body).then((res) => {
assertBusinessOk(res.data)
return unwrapData(res.data)
})
}
function getData(path: string, params?: Record<string, unknown>) {
return axiosInstance.get(omsUrl(path), { params }).then((res) => unwrapData(res.data))
}
// Platform store
export const getPlatformStoreList = (body: Record<string, unknown>) =>
postList('/order/platform-store/list', body)
export const getPlatformStoreAuthUrl = (body: Record<string, unknown>) =>
postOk('/order/platform-store/auth-url', body)
export const savePlatformStore = (body: Record<string, unknown>) => postOk('/order/platform-store/save', body)
export const deletePlatformStore = (ids: number[]) => postOk('/order/platform-store/delete', { ids })
// Platform store order
export const getPlatformStoreOrderList = (body: Record<string, unknown>) =>
postList('/order/platform-store-order/list', body)
export const getPlatformStoreOrderDetail = (id: number, customerId?: number) =>
getData('/order/platform-store-order/detail', { id, customerId })
export const getPlatformStoreOrderSummary = (params?: Record<string, unknown>) =>
getData('/order/platform-store-order/summary', params)
export const syncPlatformStoreOrderStatus = (ids: number[], customerId?: number) =>
postOk('/order/platform-store-order/sync-status', { ids, customerId })
export const readyToShipPlatformStoreOrder = (ids: number[], customerId?: number) =>
postOk('/order/platform-store-order/ready-to-ship', { ids, customerId })
export const matchPlatformStoreOrderInventory = (body: Record<string, unknown>) =>
postOk('/order/platform-store-order/match-inventory', body)
export const batchMatchPlatformStoreOrderInventory = (body: Record<string, unknown>) =>
postOk('/order/platform-store-order/batch-match-inventory', body)
export const fetchPlatformStoreOrderLabel = (id: number, customerId?: number) =>
postOk('/order/platform-store-order/fetch-label', { id, customerId })
export const togglePlatformStoreOrderSuspend = (body: Record<string, unknown>) =>
postOk('/order/platform-store-order/toggle-suspend', body)
export const deletePlatformStoreOrder = (ids: number[], customerId?: number) =>
postOk('/order/platform-store-order/delete', { ids, customerId })

View File

@ -0,0 +1,57 @@
import { axiosInstance } from '@/api/rbac'
import { assertBusinessOk, omsUrl, parseListPayload, unwrapData } from '@/api/oms/common'
function postList(path: string, body: Record<string, unknown>) {
return axiosInstance.post(omsUrl(path), body).then((res) => parseListPayload(res.data))
}
function postOk(path: string, body: Record<string, unknown>) {
return axiosInstance.post(omsUrl(path), body).then((res) => {
assertBusinessOk(res.data)
return unwrapData(res.data)
})
}
function getData(path: string, params?: Record<string, unknown>) {
return axiosInstance.get(omsUrl(path), { params }).then((res) => unwrapData(res.data))
}
// SKU
export const getWarehouseSkuList = (body: Record<string, unknown>) => postList('/warehouse/sku/list', body)
export const getWarehouseSkuDetail = (id: number, customerId?: number) =>
getData('/warehouse/sku/detail', { id, customerId })
export const saveWarehouseSku = (body: Record<string, unknown>) => postOk('/warehouse/sku/save', body)
export const deleteWarehouseSku = (id: number) => postOk('/warehouse/sku/delete', { id })
export const bindWarehouseSkuMapping = (body: Record<string, unknown>) =>
postOk('/warehouse/sku/bind-mapping', body)
// Bin location
export const getWarehouseBinLocationList = (body: Record<string, unknown>) =>
postList('/warehouse/bin-location/list', body).then((r) => ({ items: r.items, total: r.items.length }))
export const saveWarehouseBinLocation = (body: Record<string, unknown>) =>
postOk('/warehouse/bin-location/save', body)
// Inbound
export const getWarehouseInboundList = (body: Record<string, unknown>) => postList('/warehouse/inbound/list', body)
export const getWarehouseInboundDetail = (id: number, customerId?: number) =>
getData('/warehouse/inbound/detail', { id, customerId })
export const saveWarehouseInbound = (body: Record<string, unknown>) => postOk('/warehouse/inbound/save', body)
export const deleteWarehouseInbound = (id: number) => postOk('/warehouse/inbound/delete', { id })
export const confirmWarehouseInboundReceive = (body: Record<string, unknown>) =>
postOk('/warehouse/inbound/confirm-receive', body)
export const getWarehouseInboundSummary = (params?: Record<string, unknown>) =>
getData('/warehouse/inbound/summary', params)
// Parcel
export const getWarehouseParcelList = (body: Record<string, unknown>) => postList('/warehouse/parcel/list', body)
export const saveWarehouseParcel = (body: Record<string, unknown>) => postOk('/warehouse/parcel/save', body)
export const deleteWarehouseParcel = (id: number) => postOk('/warehouse/parcel/delete', { id })
export const putawayWarehouseParcel = (body: Record<string, unknown>) => postOk('/warehouse/parcel/putaway', body)
// Inventory
export const getWarehouseInventoryList = (body: Record<string, unknown>) =>
postList('/warehouse/inventory/list', body)
export const getWarehouseInventoryBinDetail = (skuId: number, warehouseId: number, customerId?: number) =>
getData('/warehouse/inventory/bin-detail', { skuId, warehouseId, customerId })
export const relocateWarehouseInventory = (body: Record<string, unknown>) =>
postOk('/warehouse/inventory/relocate', body)

View File

@ -96,6 +96,10 @@
persistColumnOrderKey?: string;
// 禁止拖拽的列 key
lockedColumnKeys?: string[];
// 是否启用表头搜索框
enableHeaderSearch?: boolean;
// 是否启用表头筛选/排序下拉
enableColumnFilter?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
@ -121,6 +125,8 @@
columnOrder: undefined,
persistColumnOrderKey: '',
lockedColumnKeys: () => [],
enableHeaderSearch: true,
enableColumnFilter: true,
});
// 确保 total 始终是数字类型(用于内部使用)
@ -287,7 +293,7 @@
// 操作列(在前面)
if (props.showActionColumn && props.actionColumnPosition === 'start') {
columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htCenter', headerClassName: 'htLeft' });
columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htLeft', headerClassName: 'htLeft' });
headerTexts.push(props.actionColumnHeader);
currentDataIndex++;
}
@ -298,7 +304,7 @@
type: 'text',
readOnly: true,
width: props.enableColumnOrderConfig ? 76 : 60,
className: 'htCenter',
className: 'htLeft',
headerClassName: 'htLeft',
renderer: ellipsisRenderer
});
@ -310,7 +316,7 @@
effectiveColumns.value.forEach((col, index) => {
// beforeLast:在倒数第二列后插入操作列
if (props.showActionColumn && props.actionColumnPosition === 'beforeLast' && index === dataColCount - 1) {
columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htCenter', headerClassName: 'htLeft' });
columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htLeft', headerClassName: 'htLeft' });
headerTexts.push(props.actionColumnHeader);
currentDataIndex++;
}
@ -328,7 +334,7 @@
// 操作列(在后面,非 beforeLast 时)
if (props.showActionColumn && props.actionColumnPosition === 'end') {
columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htCenter', headerClassName: 'htLeft' });
columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htLeft', headerClassName: 'htLeft' });
headerTexts.push(props.actionColumnHeader);
currentDataIndex++;
}
@ -424,8 +430,8 @@
horizontal: true,
vertical: true
},
filters: { enabled: true },
dropdownMenu: {
filters: props.enableColumnFilter ? { enabled: true } : false,
dropdownMenu: props.enableColumnFilter ? {
items: {
sort_asc: { name: '升序排序' },
sort_desc: { name: '降序排序' },
@ -501,8 +507,8 @@
}
},
},
},
columnSorting: true,
} : false,
columnSorting: props.enableColumnFilter,
beforeColumnMove: (movedColumns: number[]) => {
if (!props.enableColumnReorder) return false;
// 仅允许移动数据列(复选框/操作/序号列禁止)
@ -561,6 +567,7 @@
const label = col === serialColIndex ? props.serialNoHeader : props.actionColumnHeader;
TH.innerHTML = '';
TH.classList.add('ht-header-simple');
TH.style.textAlign = 'left';
const span = document.createElement('span');
span.className = 'ht-header-simple-text';
span.textContent = label;
@ -610,6 +617,17 @@
const searchField = colDef.searchField || props.columnToSearchFieldMap[col];
const headerText = colDef.label;
if (!props.enableHeaderSearch) {
TH.innerHTML = '';
TH.classList.add('ht-header-simple');
TH.style.textAlign = 'left';
const span = document.createElement('span');
span.className = 'ht-header-simple-text';
span.textContent = headerText;
TH.appendChild(span);
return;
}
// 检查是否已经创建了搜索框
if (TH.querySelector('.header-search-input')) {
return;
@ -794,7 +812,7 @@
// 操作列(在前面)
if (col === actionColStartIndex && row >= 0 && row < props.data.length) {
td.style.textAlign = 'center';
td.style.textAlign = 'left';
td.style.overflow = 'visible';
const rowData = props.data[row];
if (props.actionRenderer) {
@ -811,7 +829,7 @@
// 序号列
if (col === serialColIndex) {
td.style.textAlign = 'center';
td.style.textAlign = 'left';
td.innerHTML = value || '';
td.style.color = '#8c8c8c';
td.style.fontWeight = '500';
@ -820,7 +838,7 @@
// 操作列(在后面)
if (col === actionColEndIndex && row >= 0 && row < props.data.length) {
td.style.textAlign = 'center';
td.style.textAlign = 'left';
td.style.overflow = 'visible';
const rowData = props.data[row];
if (props.actionRenderer) {
@ -1746,6 +1764,7 @@
font-size: 12px;
font-weight: 500;
color: #1d2129;
text-align: left !important;
}
}
@ -1764,16 +1783,19 @@
:deep(.ht-header-simple) {
padding: 0 !important;
vertical-align: middle;
text-align: left !important;
}
:deep(.ht-header-simple .ht-header-simple-text) {
display: block;
text-align: left;
width: 100%;
text-align: left !important;
font-size: 12px;
font-weight: 500;
color: #1d2129;
padding: 4px 6px;
white-space: nowrap;
overflow: visible;
box-sizing: border-box;
}
:deep(.ht-header-order-config .ht-header-order-config-wrap) {

View File

@ -65,7 +65,6 @@ const loadNotice = async () => {
page: 1,
pageSize: 1,
noticeType: 'notice',
receiverType: 'user',
});
noticeCount.value = total;
} catch (error) {
@ -81,7 +80,6 @@ const loadNotification = async () => {
page: 1,
pageSize: 1,
noticeType: 'message',
receiverType: 'user',
});
notificationCount.value = total;
} catch (error) {

View File

@ -481,6 +481,37 @@ const CORE_GROUPS: PageButtonGroup[] = [
{ code: 'Retry', name: '重试失败' },
{ code: 'Cancel', name: '取消待处理' },
]),
B('Order.PlatformStore', [
{ code: 'Query', name: '查询' },
{ code: 'Save', name: '保存' },
{ code: 'Delete', name: '删除' },
{ code: 'Auth', name: '授权' },
]),
B('Order.PlatformStoreOrder', [
{ code: 'Query', name: '查询' },
{ code: 'MatchInventory', name: '匹配库存' },
{ code: 'ToggleSuspend', name: '搁置/恢复' },
{ code: 'Delete', name: '删除' },
]),
B('Warehouse.Sku', [
{ code: 'Query', name: '查询' },
{ code: 'Save', name: '保存' },
{ code: 'Delete', name: '删除' },
]),
B('Warehouse.Inventory', [
{ code: 'Query', name: '查询' },
{ code: 'Relocate', name: '换库位' },
]),
B('Warehouse.Parcel', [
{ code: 'Query', name: '查询' },
{ code: 'Save', name: '保存' },
{ code: 'Delete', name: '删除' },
]),
B('Warehouse.InboundNotice', [
{ code: 'Query', name: '查询' },
{ code: 'Save', name: '保存' },
{ code: 'Delete', name: '删除' },
]),
// ── 渠道 ──
B('Channel.SalesProducts', [

View File

@ -83,6 +83,167 @@ export default {
'menu.order.templateMapping': 'Template Mapping',
'menu.order.myOrders': 'My Orders',
'menu.order.batchJobs': 'Batch Jobs',
'menu.order.platformStore': 'Platform Stores',
'menu.order.platformStoreOrder': 'Store Orders',
'menu.warehouse': 'Warehouse',
'menu.warehouse.parcel': 'My Parcels',
'menu.warehouse.inventory': 'My Inventory',
'menu.warehouse.sku': 'My SKU',
'menu.warehouse.inboundNotice': 'Inbound Notice',
'warehouse.common.search': 'Search',
'warehouse.common.add': 'Add',
'warehouse.common.edit': 'Edit',
'warehouse.common.delete': 'Delete',
'warehouse.common.save': 'Save',
'warehouse.common.cancel': 'Cancel',
'warehouse.common.confirm': 'Confirm',
'warehouse.common.detail': 'Detail',
'warehouse.common.warehouse': 'Warehouse',
'warehouse.sku.table.skuCode': 'SKU Code',
'warehouse.sku.table.skuName': 'SKU Name',
'warehouse.sku.table.totalQty': 'Qty',
'warehouse.sku.table.weightG': 'Weight(g)',
'warehouse.sku.table.remark': 'Remark',
'warehouse.sku.search.keyword': 'Code / Name',
'warehouse.sku.form.skuCode': 'SKU Code',
'warehouse.sku.form.skuName': 'SKU Name',
'warehouse.sku.form.weightG': 'Weight(g)',
'warehouse.sku.form.remark': 'Remark',
'warehouse.sku.modal.add': 'Add SKU',
'warehouse.sku.modal.edit': 'Edit SKU',
'warehouse.sku.actions.delete': 'Delete SKU',
'warehouse.sku.message.loadFailed': 'Failed to load SKU list',
'warehouse.sku.message.saveSuccess': 'Saved',
'warehouse.sku.message.saveFailed': 'Save failed',
'warehouse.sku.message.deleteSuccess': 'Deleted',
'warehouse.sku.message.deleteFailed': 'Delete failed',
'warehouse.sku.message.deleteConfirm': 'Delete {code}?',
'warehouse.sku.message.required': 'SKU code and name are required',
'warehouse.inventory.table.skuCode': 'SKU Code',
'warehouse.inventory.table.skuName': 'SKU Name',
'warehouse.inventory.table.warehouseId': 'Warehouse',
'warehouse.inventory.table.totalQty': 'Total Qty',
'warehouse.inventory.table.binCount': 'Bins',
'warehouse.inventory.table.binCode': 'Bin',
'warehouse.inventory.table.qty': 'Qty',
'warehouse.inventory.search.keyword': 'Code / Name',
'warehouse.inventory.actions.binDetail': 'Bin Detail',
'warehouse.inventory.actions.relocate': 'Relocate',
'warehouse.inventory.drawer.binDetail': 'Bin Detail',
'warehouse.inventory.modal.relocate': 'Relocate',
'warehouse.inventory.form.sourceBin': 'Source Bin ID',
'warehouse.inventory.form.targetBin': 'Target Bin ID',
'warehouse.inventory.form.qty': 'Qty',
'warehouse.inventory.message.loadFailed': 'Failed to load inventory',
'warehouse.inventory.message.binDetailFailed': 'Failed to load bin detail',
'warehouse.inventory.message.relocateRequired': 'Fill relocate fields',
'warehouse.inventory.message.relocateSuccess': 'Relocated',
'warehouse.inventory.message.relocateFailed': 'Relocate failed',
'warehouse.parcel.status.all': 'All',
'warehouse.parcel.status.inTransit': 'In Transit',
'warehouse.parcel.status.arrived': 'Arrived',
'warehouse.parcel.status.stored': 'Stored',
'warehouse.parcel.table.trackingNo': 'Tracking No',
'warehouse.parcel.table.carrierName': 'Carrier',
'warehouse.parcel.table.lifecycleStatus': 'Status',
'warehouse.parcel.table.warehouseId': 'Warehouse',
'warehouse.parcel.table.remark': 'Remark',
'warehouse.parcel.search.trackingNo': 'Tracking No',
'warehouse.parcel.form.trackingNo': 'Tracking No',
'warehouse.parcel.form.carrierName': 'Carrier',
'warehouse.parcel.form.productName': 'Product',
'warehouse.parcel.form.quantity': 'Qty',
'warehouse.parcel.modal.add': 'Add Parcel',
'warehouse.parcel.actions.delete': 'Delete Parcel',
'warehouse.parcel.message.loadFailed': 'Failed to load parcels',
'warehouse.parcel.message.saveSuccess': 'Saved',
'warehouse.parcel.message.saveFailed': 'Save failed',
'warehouse.parcel.message.deleteSuccess': 'Deleted',
'warehouse.parcel.message.required': 'Warehouse and tracking no required',
'warehouse.inbound.status.all': 'All',
'warehouse.inbound.status.forecasted': 'Forecasted',
'warehouse.inbound.status.completed': 'Completed',
'warehouse.inbound.table.noticeNo': 'Notice No',
'warehouse.inbound.table.markReference': 'Mark Ref',
'warehouse.inbound.table.receiptStatus': 'Status',
'warehouse.inbound.table.boxCount': 'Boxes',
'warehouse.inbound.table.plannedQty': 'Planned Qty',
'warehouse.inbound.table.createTime': 'Created',
'warehouse.inbound.search.keyword': 'Notice / Mark',
'warehouse.inbound.form.markReference': 'Mark Ref',
'warehouse.inbound.form.markBoxNo': 'Box No',
'warehouse.inbound.form.sku': 'SKU',
'warehouse.inbound.form.plannedQty': 'Planned Qty',
'warehouse.inbound.modal.add': 'Add Inbound',
'warehouse.inbound.drawer.detail': 'Inbound Detail',
'warehouse.inbound.box': 'Box',
'warehouse.inbound.line.skuCode': 'SKU',
'warehouse.inbound.line.plannedQty': 'Planned',
'warehouse.inbound.line.receivedQty': 'Received',
'warehouse.inbound.actions.delete': 'Delete',
'warehouse.inbound.message.loadFailed': 'Failed to load inbound list',
'warehouse.inbound.message.saveSuccess': 'Saved',
'warehouse.inbound.message.saveFailed': 'Save failed',
'warehouse.inbound.message.deleteSuccess': 'Deleted',
'warehouse.inbound.message.required': 'Select warehouse and SKU',
'warehouse.inbound.message.detailFailed': 'Failed to load detail',
'order.platformStore.platform.manual': 'Manual',
'order.platformStore.table.platform': 'Platform',
'order.platformStore.table.nickname': 'Nickname',
'order.platformStore.table.account': 'Account',
'order.platformStore.table.authStatus': 'Auth Status',
'order.platformStore.table.tokenExpire': 'Token Expire',
'order.platformStore.search.platform': 'Platform',
'order.platformStore.search.nickname': 'Nickname',
'order.platformStore.form.platform': 'Platform',
'order.platformStore.form.nickname': 'Nickname',
'order.platformStore.form.account': 'Account',
'order.platformStore.form.autoFulfill': 'Auto Fulfill',
'order.platformStore.modal.add': 'Add Store',
'order.platformStore.modal.edit': 'Edit Store',
'order.platformStore.actions.auth': 'Authorize',
'order.platformStore.actions.delete': 'Delete Store',
'order.platformStore.message.loadFailed': 'Failed to load stores',
'order.platformStore.message.saveSuccess': 'Saved',
'order.platformStore.message.saveFailed': 'Save failed',
'order.platformStore.message.deleteSuccess': 'Deleted',
'order.platformStore.message.required': 'Nickname is required',
'order.platformStore.message.authPlaceholder': 'OAuth placeholder',
'order.platformStore.message.authFailed': 'Failed to get auth URL',
'order.platformStoreOrder.status.all': 'All',
'order.platformStoreOrder.status.pending': 'Pending',
'order.platformStoreOrder.status.toShip': 'To Ship',
'order.platformStoreOrder.status.shipped': 'Shipped',
'order.platformStoreOrder.table.orderNo': 'Order No',
'order.platformStoreOrder.table.store': 'Store',
'order.platformStoreOrder.table.status': 'Status',
'order.platformStoreOrder.table.amount': 'Amount',
'order.platformStoreOrder.table.orderTime': 'Order Time',
'order.platformStoreOrder.table.linkedServiceNo': 'Linked Service No',
'order.platformStoreOrder.form.product': 'Sales Product',
'order.platformStoreOrder.search.orderNo': 'Order No',
'order.platformStoreOrder.summary.pending': 'Pending',
'order.platformStoreOrder.summary.toShip': 'To Ship',
'order.platformStoreOrder.drawer.detail': 'Order Detail',
'order.platformStoreOrder.line.sku': 'Platform SKU',
'order.platformStoreOrder.line.name': 'Product',
'order.platformStoreOrder.line.qty': 'Qty',
'order.platformStoreOrder.line.mappedSku': 'Mapped SKU',
'order.platformStoreOrder.actions.match': 'Match Inventory',
'order.platformStoreOrder.actions.batchMatch': 'Batch Match',
'order.platformStoreOrder.actions.suspend': 'Suspend',
'order.platformStoreOrder.actions.resume': 'Resume',
'order.platformStoreOrder.actions.delete': 'Delete',
'order.platformStoreOrder.message.loadFailed': 'Failed to load orders',
'order.platformStoreOrder.message.detailFailed': 'Failed to load detail',
'order.platformStoreOrder.message.matchSuccess': 'Inventory matched',
'order.platformStoreOrder.message.matchFailed': 'Match failed',
'order.platformStoreOrder.message.warehouseRequired': 'Select warehouse',
'order.platformStoreOrder.message.suspendSuccess': 'Status updated',
'order.platformStoreOrder.message.deleteSuccess': 'Deleted',
'order.platformStoreOrder.message.batchEmpty': 'No pending orders to match on this page',
'order.platformStoreOrder.message.batchConfirm': 'Match {count} pending orders on this page and create parcel orders?',
'order.platformStoreOrder.message.batchResult': 'Batch done: {success} succeeded, {fail} failed',
'menu.channel': 'Channel',
'menu.channel.channelGuide': 'Getting Started',
'menu.channel.salesProducts': 'Sales Products',
@ -1148,6 +1309,7 @@ export default {
'system.menu.actions.more': 'More',
'system.menu.actions.manageButton': 'Manage button',
'system.menu.actions.syncLevel3Buttons': 'Sync level-3 buttons',
'system.menu.actions.syncSubMenusAndButtons': 'Sync sub-menus & buttons',
'system.menu.status.enabled': 'Enabled',
'system.menu.status.disabled': 'Disabled',
'system.menu.table.title': 'Menu name',
@ -1171,10 +1333,18 @@ export default {
'system.menu.modal.okImport': 'Confirm import',
'system.menu.modal.syncLevel3Title': 'Sync level-3 buttons',
'system.menu.modal.syncLevel3Content': 'Sync level-3 buttons from the frontend catalog and permission tree for menu "{name}". Existing buttons will be skipped.',
'system.menu.modal.syncModuleTitle': 'Sync sub-menus & buttons',
'system.menu.modal.syncModuleContent':
'Sync level-2 page menus from route config for module "{name}", then sync level-3 buttons for each page. Existing menus/buttons will be skipped.',
'system.menu.modal.syncLevel3Ok': 'Sync now',
'system.menu.message.syncLevel3Success': 'Synced: {created} created, {skipped} skipped',
'system.menu.message.syncLevel3Skipped': 'Nothing to sync, {skipped} existing button(s) skipped',
'system.menu.message.syncLevel3Failed': 'Failed to sync level-3 buttons',
'system.menu.message.syncModuleSuccess':
'Synced: {level2Created} level-2 menu(s) created, {level2Skipped} skipped; {level3Created} level-3 button(s) created, {level3Skipped} skipped',
'system.menu.message.syncModuleSkipped':
'Nothing to sync, skipped {level2Skipped} level-2 menu(s) and {level3Skipped} level-3 button(s)',
'system.menu.message.syncModulePartialFailed': 'Some pages failed to sync level-3 buttons: {details}',
// System - Organization Management
'system.organization.actions.add': 'Add Organization',

View File

@ -83,6 +83,167 @@ export default {
'menu.order.templateMapping': '模板字段映射',
'menu.order.myOrders': '我的订单',
'menu.order.batchJobs': '批量任务',
'menu.order.platformStore': '店铺授权',
'menu.order.platformStoreOrder': '店铺订单',
'menu.warehouse': '仓储',
'menu.warehouse.parcel': '我的包裹',
'menu.warehouse.inventory': '我的库存',
'menu.warehouse.sku': '我的 SKU',
'menu.warehouse.inboundNotice': '入库预报',
'warehouse.common.search': '查询',
'warehouse.common.add': '新增',
'warehouse.common.edit': '编辑',
'warehouse.common.delete': '删除',
'warehouse.common.save': '保存',
'warehouse.common.cancel': '取消',
'warehouse.common.confirm': '确定',
'warehouse.common.detail': '详情',
'warehouse.common.warehouse': '仓库',
'warehouse.sku.table.skuCode': 'SKU 编码',
'warehouse.sku.table.skuName': 'SKU 名称',
'warehouse.sku.table.totalQty': '库存',
'warehouse.sku.table.weightG': '重量(g)',
'warehouse.sku.table.remark': '备注',
'warehouse.sku.search.keyword': '编码/名称',
'warehouse.sku.form.skuCode': 'SKU 编码',
'warehouse.sku.form.skuName': 'SKU 名称',
'warehouse.sku.form.weightG': '重量(g)',
'warehouse.sku.form.remark': '备注',
'warehouse.sku.modal.add': '新增 SKU',
'warehouse.sku.modal.edit': '编辑 SKU',
'warehouse.sku.actions.delete': '删除 SKU',
'warehouse.sku.message.loadFailed': '加载 SKU 列表失败',
'warehouse.sku.message.saveSuccess': '保存成功',
'warehouse.sku.message.saveFailed': '保存失败',
'warehouse.sku.message.deleteSuccess': '删除成功',
'warehouse.sku.message.deleteFailed': '删除失败',
'warehouse.sku.message.deleteConfirm': '确定删除 {code}?',
'warehouse.sku.message.required': '请填写 SKU 编码和名称',
'warehouse.inventory.table.skuCode': 'SKU 编码',
'warehouse.inventory.table.skuName': 'SKU 名称',
'warehouse.inventory.table.warehouseId': '仓库',
'warehouse.inventory.table.totalQty': '总数量',
'warehouse.inventory.table.binCount': '库位数',
'warehouse.inventory.table.binCode': '库位',
'warehouse.inventory.table.qty': '数量',
'warehouse.inventory.search.keyword': '编码/名称',
'warehouse.inventory.actions.binDetail': '库位明细',
'warehouse.inventory.actions.relocate': '换库位',
'warehouse.inventory.drawer.binDetail': '库位明细',
'warehouse.inventory.modal.relocate': '换库位',
'warehouse.inventory.form.sourceBin': '源库位 ID',
'warehouse.inventory.form.targetBin': '目标库位 ID',
'warehouse.inventory.form.qty': '数量',
'warehouse.inventory.message.loadFailed': '加载库存失败',
'warehouse.inventory.message.binDetailFailed': '加载库位明细失败',
'warehouse.inventory.message.relocateRequired': '请填写换库位信息',
'warehouse.inventory.message.relocateSuccess': '换库位成功',
'warehouse.inventory.message.relocateFailed': '换库位失败',
'warehouse.parcel.status.all': '全部',
'warehouse.parcel.status.inTransit': '在途',
'warehouse.parcel.status.arrived': '已到仓',
'warehouse.parcel.status.stored': '已上架',
'warehouse.parcel.table.trackingNo': '快递单号',
'warehouse.parcel.table.carrierName': '快递公司',
'warehouse.parcel.table.lifecycleStatus': '状态',
'warehouse.parcel.table.warehouseId': '仓库',
'warehouse.parcel.table.remark': '备注',
'warehouse.parcel.search.trackingNo': '快递单号',
'warehouse.parcel.form.trackingNo': '快递单号',
'warehouse.parcel.form.carrierName': '快递公司',
'warehouse.parcel.form.productName': '商品名称',
'warehouse.parcel.form.quantity': '数量',
'warehouse.parcel.modal.add': '新增包裹',
'warehouse.parcel.actions.delete': '删除包裹',
'warehouse.parcel.message.loadFailed': '加载包裹失败',
'warehouse.parcel.message.saveSuccess': '保存成功',
'warehouse.parcel.message.saveFailed': '保存失败',
'warehouse.parcel.message.deleteSuccess': '删除成功',
'warehouse.parcel.message.required': '请填写仓库和快递单号',
'warehouse.inbound.status.all': '全部',
'warehouse.inbound.status.forecasted': '预报',
'warehouse.inbound.status.completed': '已完成',
'warehouse.inbound.table.noticeNo': '预报单号',
'warehouse.inbound.table.markReference': '唛头',
'warehouse.inbound.table.receiptStatus': '状态',
'warehouse.inbound.table.boxCount': '箱数',
'warehouse.inbound.table.plannedQty': '计划数量',
'warehouse.inbound.table.createTime': '创建时间',
'warehouse.inbound.search.keyword': '单号/唛头',
'warehouse.inbound.form.markReference': '唛头',
'warehouse.inbound.form.markBoxNo': '箱号',
'warehouse.inbound.form.sku': 'SKU',
'warehouse.inbound.form.plannedQty': '计划数量',
'warehouse.inbound.modal.add': '新增入库预报',
'warehouse.inbound.drawer.detail': '入库详情',
'warehouse.inbound.box': '箱',
'warehouse.inbound.line.skuCode': 'SKU',
'warehouse.inbound.line.plannedQty': '计划',
'warehouse.inbound.line.receivedQty': '实收',
'warehouse.inbound.actions.delete': '删除预报',
'warehouse.inbound.message.loadFailed': '加载入库预报失败',
'warehouse.inbound.message.saveSuccess': '保存成功',
'warehouse.inbound.message.saveFailed': '保存失败',
'warehouse.inbound.message.deleteSuccess': '删除成功',
'warehouse.inbound.message.required': '请选择仓库和 SKU',
'warehouse.inbound.message.detailFailed': '加载详情失败',
'order.platformStore.platform.manual': '手工店铺',
'order.platformStore.table.platform': '平台',
'order.platformStore.table.nickname': '店铺昵称',
'order.platformStore.table.account': '账号',
'order.platformStore.table.authStatus': '授权状态',
'order.platformStore.table.tokenExpire': 'Token 过期',
'order.platformStore.search.platform': '平台',
'order.platformStore.search.nickname': '店铺昵称',
'order.platformStore.form.platform': '平台',
'order.platformStore.form.nickname': '店铺昵称',
'order.platformStore.form.account': '平台账号',
'order.platformStore.form.autoFulfill': '自动发货',
'order.platformStore.modal.add': '新增店铺',
'order.platformStore.modal.edit': '编辑店铺',
'order.platformStore.actions.auth': '授权',
'order.platformStore.actions.delete': '删除店铺',
'order.platformStore.message.loadFailed': '加载店铺失败',
'order.platformStore.message.saveSuccess': '保存成功',
'order.platformStore.message.saveFailed': '保存失败',
'order.platformStore.message.deleteSuccess': '删除成功',
'order.platformStore.message.required': '请填写店铺昵称',
'order.platformStore.message.authPlaceholder': 'OAuth 占位,待平台 SDK 接入',
'order.platformStore.message.authFailed': '获取授权地址失败',
'order.platformStoreOrder.status.all': '全部',
'order.platformStoreOrder.status.pending': '待处理',
'order.platformStoreOrder.status.toShip': '待发货',
'order.platformStoreOrder.status.shipped': '已发货',
'order.platformStoreOrder.table.orderNo': '平台订单号',
'order.platformStoreOrder.table.store': '店铺',
'order.platformStoreOrder.table.status': '状态',
'order.platformStoreOrder.table.amount': '金额',
'order.platformStoreOrder.table.orderTime': '下单时间',
'order.platformStoreOrder.table.linkedServiceNo': '关联服务单号',
'order.platformStoreOrder.form.product': '销售产品',
'order.platformStoreOrder.search.orderNo': '平台订单号',
'order.platformStoreOrder.summary.pending': '待处理',
'order.platformStoreOrder.summary.toShip': '待发货',
'order.platformStoreOrder.drawer.detail': '订单详情',
'order.platformStoreOrder.line.sku': '平台 SKU',
'order.platformStoreOrder.line.name': '商品',
'order.platformStoreOrder.line.qty': '数量',
'order.platformStoreOrder.line.mappedSku': '库内 SKU',
'order.platformStoreOrder.actions.match': '匹配库存',
'order.platformStoreOrder.actions.batchMatch': '批量匹配',
'order.platformStoreOrder.actions.suspend': '搁置',
'order.platformStoreOrder.actions.resume': '恢复',
'order.platformStoreOrder.actions.delete': '删除订单',
'order.platformStoreOrder.message.loadFailed': '加载订单失败',
'order.platformStoreOrder.message.detailFailed': '加载详情失败',
'order.platformStoreOrder.message.matchSuccess': '库存匹配成功',
'order.platformStoreOrder.message.matchFailed': '库存匹配失败',
'order.platformStoreOrder.message.warehouseRequired': '请选择发货仓库',
'order.platformStoreOrder.message.suspendSuccess': '状态已更新',
'order.platformStoreOrder.message.deleteSuccess': '删除成功',
'order.platformStoreOrder.message.batchEmpty': '当前页没有可匹配的待处理订单',
'order.platformStoreOrder.message.batchConfirm': '将匹配当前页 {count} 个待处理订单并创建小包单,是否继续?',
'order.platformStoreOrder.message.batchResult': '批量匹配完成:成功 {success},失败 {fail}',
'menu.channel': '渠道',
'menu.channel.channelGuide': '新手指引',
'menu.channel.salesProducts': '销售产品',
@ -1033,6 +1194,7 @@ export default {
'system.menu.actions.more': '更多',
'system.menu.actions.manageButton': '管理按钮',
'system.menu.actions.syncLevel3Buttons': '同步三级按钮',
'system.menu.actions.syncSubMenusAndButtons': '同步子菜单及按钮',
'system.menu.status.enabled': '启用',
'system.menu.status.disabled': '禁用',
'system.menu.table.title': '菜单名称',
@ -1056,10 +1218,18 @@ export default {
'system.menu.modal.okImport': '确定导入',
'system.menu.modal.syncLevel3Title': '同步三级按钮',
'system.menu.modal.syncLevel3Content': '将为菜单「{name}」同步前端目录与权限树中的三级按钮,已存在的按钮将跳过。',
'system.menu.modal.syncModuleTitle': '同步子菜单及按钮',
'system.menu.modal.syncModuleContent':
'将为模块「{name}」从路由配置同步二级页面菜单,并为每个页面同步三级按钮,已存在的菜单/按钮将跳过。',
'system.menu.modal.syncLevel3Ok': '开始同步',
'system.menu.message.syncLevel3Success': '同步完成:新增 {created} 个,跳过 {skipped} 个',
'system.menu.message.syncLevel3Skipped': '无需同步,已跳过 {skipped} 个已存在按钮',
'system.menu.message.syncLevel3Failed': '同步三级按钮失败',
'system.menu.message.syncModuleSuccess':
'同步完成:二级菜单新增 {level2Created} 个、跳过 {level2Skipped} 个;三级按钮新增 {level3Created} 个、跳过 {level3Skipped} 个',
'system.menu.message.syncModuleSkipped':
'无需同步,已跳过 {level2Skipped} 个二级菜单、{level3Skipped} 个三级按钮',
'system.menu.message.syncModulePartialFailed': '部分页面三级按钮同步失败:{details}',
// 系统 - 组织管理
'system.organization.actions.add': '新增组织',

View File

@ -70,6 +70,26 @@ const ORDER: AppRouteRecordRaw = {
permission: 'Order.BatchJobs.Query',
},
},
{
path: 'platformStore',
name: 'PlatformStore',
component: () => import('@/views/order/platformStore/index.vue'),
meta: {
locale: 'menu.order.platformStore',
requiresAuth: true,
permission: 'Order.PlatformStore.Query',
},
},
{
path: 'platformStoreOrder',
name: 'PlatformStoreOrder',
component: () => import('@/views/order/platformStoreOrder/index.vue'),
meta: {
locale: 'menu.order.platformStoreOrder',
requiresAuth: true,
permission: 'Order.PlatformStoreOrder.Query',
},
},
],
};

View File

@ -0,0 +1,58 @@
import { DEFAULT_LAYOUT } from '../base';
import { AppRouteRecordRaw } from '../types';
const WAREHOUSE: AppRouteRecordRaw = {
path: '/warehouse',
name: 'Warehouse',
component: DEFAULT_LAYOUT,
meta: {
locale: 'menu.warehouse',
icon: 'icon-storage',
requiresAuth: true,
order: 4,
},
children: [
{
path: 'parcel',
name: 'WarehouseParcel',
component: () => import('@/views/warehouse/parcel/index.vue'),
meta: {
locale: 'menu.warehouse.parcel',
requiresAuth: true,
permission: 'Warehouse.Parcel.Query',
},
},
{
path: 'inventory',
name: 'WarehouseInventory',
component: () => import('@/views/warehouse/inventory/index.vue'),
meta: {
locale: 'menu.warehouse.inventory',
requiresAuth: true,
permission: 'Warehouse.Inventory.Query',
},
},
{
path: 'sku',
name: 'WarehouseSku',
component: () => import('@/views/warehouse/sku/index.vue'),
meta: {
locale: 'menu.warehouse.sku',
requiresAuth: true,
permission: 'Warehouse.Sku.Query',
},
},
{
path: 'inboundNotice',
name: 'WarehouseInboundNotice',
component: () => import('@/views/warehouse/inboundNotice/index.vue'),
meta: {
locale: 'menu.warehouse.inboundNotice',
requiresAuth: true,
permission: 'Warehouse.InboundNotice.Query',
},
},
],
};
export default WAREHOUSE;

View File

@ -6,6 +6,13 @@ import {
normalizeResourcePermissionCode,
type PageButtonDef,
} from '@/constants/pageButtonCatalog';
import {
findModuleRouteByMenu,
findPageChildMenu,
getPageRoutesFromModule,
isModuleMenu,
type RoutePageMenuDef,
} from '@/utils/syncMenuRouteCatalog';
export interface SyncLevel3ButtonsResult {
created: number;
@ -14,6 +21,22 @@ export interface SyncLevel3ButtonsResult {
createdNames: string[];
}
export interface SyncLevel3Options {
/** 无三级按钮时不抛错,返回 created=0 */
allowEmpty?: boolean;
}
export interface SyncMenuTreeResult {
mode: 'module' | 'page';
level2Created: number;
level2Skipped: number;
level3Created: number;
level3Skipped: number;
level3FailedPages: string[];
}
export { isModuleMenu };
function permissionNodeToButton(
child: PermissionDefinitionDto,
order: number,
@ -137,10 +160,70 @@ function filterSyncTargets(
return buttons.filter((btn) => btn.permissionCode !== menuCode);
}
function findMenuById(tree: MenuTreeDto[], id: string): MenuTreeDto | null {
for (const node of tree) {
if (node.id === id) return node;
if (node.children?.length) {
const found = findMenuById(node.children, id);
if (found) return found;
}
}
return null;
}
async function reloadMenuNode(menuId: string): Promise<MenuTreeDto | null> {
const tree = await MenuService.getRbacMenuGetMenuTree();
return findMenuById(tree ?? [], menuId);
}
async function ensurePageMenu(
parentMenu: MenuTreeDto,
pageDef: RoutePageMenuDef,
): Promise<{ menu: MenuTreeDto; created: boolean }> {
const existing = findPageChildMenu(parentMenu, pageDef.route, pageDef.permissionCode);
if (existing?.id) {
return { menu: existing, created: false };
}
const createdMenu = await MenuService.postRbacMenuCreate({
pId: parentMenu.id,
name: pageDef.name,
type: 1,
permissionCode: pageDef.permissionCode,
icon: pageDef.icon,
route: pageDef.route,
component: pageDef.component,
order: pageDef.order,
isHidden: pageDef.isHidden,
isCached: false,
description: `同步二级菜单: ${pageDef.route}`,
});
return {
menu: {
id: createdMenu.id,
pId: parentMenu.id,
name: pageDef.name,
type: 1,
permissionCode: pageDef.permissionCode,
icon: pageDef.icon,
route: pageDef.route,
component: pageDef.component,
order: pageDef.order,
isHidden: pageDef.isHidden,
children: [],
},
created: true,
};
}
/**
* 将前端目录 + 权限树中的三级按钮同步为菜单子节点(type=2)
*/
export async function syncMenuLevel3Buttons(menu: MenuTreeDto): Promise<SyncLevel3ButtonsResult> {
export async function syncMenuLevel3Buttons(
menu: MenuTreeDto,
options?: SyncLevel3Options,
): Promise<SyncLevel3ButtonsResult> {
const parentPermissionCode = menu.permissionCode?.trim() || '';
if (!parentPermissionCode) {
throw new Error('当前菜单未配置权限编码,无法同步三级按钮');
@ -167,6 +250,9 @@ export async function syncMenuLevel3Buttons(menu: MenuTreeDto): Promise<SyncLeve
);
if (!targetButtons.length) {
if (options?.allowEmpty) {
return { created: 0, skipped: 0, total: 0, createdNames: [] };
}
const resourceCode = normalizeResourcePermissionCode(parentPermissionCode);
throw new Error(
`未找到可同步的三级按钮(菜单编码: ${parentPermissionCode}${resourceCode !== parentPermissionCode ? `,资源编码: ${resourceCode}` : ''})。请确认菜单 permissionCode 与权限树/前端目录一致。`,
@ -207,3 +293,85 @@ export async function syncMenuLevel3Buttons(menu: MenuTreeDto): Promise<SyncLeve
createdNames,
};
}
/**
* 同步菜单:一级模块同步二级子菜单 + 各页面三级按钮;二级页面仅同步三级按钮
*/
export async function syncMenuTree(menu: MenuTreeDto): Promise<SyncMenuTreeResult> {
if (!menu.id) {
throw new Error('菜单 ID 无效');
}
if (menu.type !== 1) {
throw new Error('仅支持对菜单类型节点执行同步');
}
if (!isModuleMenu(menu)) {
const result = await syncMenuLevel3Buttons(menu);
return {
mode: 'page',
level2Created: 0,
level2Skipped: 0,
level3Created: result.created,
level3Skipped: result.skipped,
level3FailedPages: [],
};
}
const moduleRoute = findModuleRouteByMenu(menu);
if (!moduleRoute) {
throw new Error('未找到匹配的路由模块,请确认菜单路由路径与前端路由配置一致');
}
const pageDefs = getPageRoutesFromModule(moduleRoute);
if (!pageDefs.length) {
throw new Error('路由模块下没有可同步的二级页面菜单');
}
let level2Created = 0;
let level2Skipped = 0;
let level3Created = 0;
let level3Skipped = 0;
const level3FailedPages: string[] = [];
let currentParent = menu;
for (const pageDef of pageDefs) {
const { menu: pageMenu, created } = await ensurePageMenu(currentParent, pageDef);
if (created) {
level2Created += 1;
const refreshedParent = await reloadMenuNode(menu.id);
if (refreshedParent) {
currentParent = refreshedParent;
}
} else {
level2Skipped += 1;
}
if (!pageMenu.permissionCode?.trim()) {
continue;
}
const pageNode =
findPageChildMenu(currentParent, pageDef.route, pageDef.permissionCode) || pageMenu;
const freshPage = pageNode.id ? await reloadMenuNode(pageNode.id) : null;
const targetPage = freshPage || pageNode;
try {
const btnResult = await syncMenuLevel3Buttons(targetPage, { allowEmpty: true });
level3Created += btnResult.created;
level3Skipped += btnResult.skipped;
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
level3FailedPages.push(`${pageDef.name}: ${message}`);
}
}
return {
mode: 'module',
level2Created,
level2Skipped,
level3Created,
level3Skipped,
level3FailedPages,
};
}

View File

@ -0,0 +1,128 @@
import i18n from '@/locale';
import { appRoutes } from '@/router/routes';
import type { AppRouteRecordRaw } from '@/router/routes/types';
import type { MenuTreeDto } from '@/api/rbac';
export interface RoutePageMenuDef {
name: string;
route: string;
component?: string;
permissionCode?: string;
icon?: string;
order: number;
isHidden: boolean;
}
function normalizeRoutePath(path: string): string {
const trimmed = path.trim().replace(/\/+$/, '');
return trimmed || '/';
}
function joinRoutePath(parentPath: string, childPath: string): string {
if (childPath.startsWith('/')) return normalizeRoutePath(childPath);
const base = normalizeRoutePath(parentPath);
return normalizeRoutePath(`${base}/${childPath}`);
}
export function extractComponentPath(component: unknown): string | undefined {
if (typeof component === 'string') {
return component;
}
if (typeof component === 'function') {
try {
const componentStr = component.toString();
const match = componentStr.match(/import\(['"]@\/views\/([^'"]+)\.vue['"]\)/);
if (match?.[1]) {
return `views/${match[1]}`;
}
} catch {
// ignore
}
}
return undefined;
}
export function resolveRouteMenuTitle(route: AppRouteRecordRaw): string {
const localeKey = route.meta?.locale as string | undefined;
if (localeKey) {
const title = i18n.global.t(localeKey);
if (title && title !== localeKey) return title;
}
return String(route.name || route.path);
}
function toRouteRecord(route: AppRouteRecordRaw): AppRouteRecordRaw {
return route;
}
export function findModuleRouteByMenu(menu: MenuTreeDto): AppRouteRecordRaw | undefined {
const menuRoute = normalizeRoutePath(menu.route || '');
if (menuRoute && menuRoute !== '/') {
for (const route of appRoutes as AppRouteRecordRaw[]) {
if (normalizeRoutePath(route.path) === menuRoute) {
return toRouteRecord(route);
}
}
}
const permissionPrefix = menu.permissionCode?.trim();
if (permissionPrefix) {
for (const route of appRoutes as AppRouteRecordRaw[]) {
const children = route.children || [];
const matched = children.some((child) => {
const code = (child.meta?.permission as string | undefined)?.trim();
return code?.startsWith(`${permissionPrefix}.`);
});
if (matched) return toRouteRecord(route);
}
}
return undefined;
}
export function getPageRoutesFromModule(moduleRoute: AppRouteRecordRaw): RoutePageMenuDef[] {
const parentPath = normalizeRoutePath(moduleRoute.path);
const pages: RoutePageMenuDef[] = [];
(moduleRoute.children || []).forEach((child) => {
if (!child.meta || child.meta.hideInMenu) return;
const routePath = joinRoutePath(parentPath, child.path);
pages.push({
name: resolveRouteMenuTitle(child),
route: routePath,
component: extractComponentPath(child.component),
permissionCode: (child.meta.permission as string | undefined)?.trim() || undefined,
icon: (child.meta.icon as string | undefined)?.trim() || undefined,
order: (child.meta.order as number | undefined) ?? 0,
isHidden: false,
});
});
return pages.sort((a, b) => a.order - b.order);
}
export function isModuleMenu(menu: MenuTreeDto): boolean {
if (menu.type !== 1) return false;
if ((menu.children || []).some((child) => child.type === 1)) {
return true;
}
const moduleRoute = findModuleRouteByMenu(menu);
return Boolean(moduleRoute?.children?.length);
}
export function findPageChildMenu(
parent: MenuTreeDto,
routePath: string,
permissionCode?: string,
): MenuTreeDto | undefined {
const normalizedRoute = normalizeRoutePath(routePath);
return (parent.children || []).find((child) => {
if (child.type !== 1) return false;
if (permissionCode && child.permissionCode?.trim() === permissionCode) return true;
if (normalizedRoute && normalizeRoutePath(child.route || '') === normalizedRoute) return true;
return false;
});
}

View File

@ -4,7 +4,6 @@ import {
FORMULA_MAX_LENGTH,
FORMULA_OPERATORS,
ORDER_TABLE_CATEGORIES,
OVERSIZE_EXAMPLE_FORMULA,
chipsByTable,
} from '../formulaMeta'
@ -50,10 +49,6 @@ function onInput(e: Event) {
updateValue(val)
}
function loadExample() {
updateValue(OVERSIZE_EXAMPLE_FORMULA)
}
watch(
() => props.modelValue,
(val) => {
@ -63,7 +58,7 @@ watch(
}
)
defineExpose({ loadExample, insertAtCursor })
defineExpose({ insertAtCursor })
</script>
<template>
@ -109,7 +104,7 @@ defineExpose({ loadExample, insertAtCursor })
type="button"
class="category-tab"
:class="{ active: activeCategory === cat.key }"
:title="cat.key === '_virtual' ? '常用聚合字段' : cat.key"
:title="cat.key"
@click="activeCategory = cat.key"
>
{{ cat.label }}

View File

@ -9,7 +9,6 @@ export const ORDER_TABLE_CATEGORIES: { key: string; label: string }[] = [
{ key: 't_order_weight', label: '件重尺' },
{ key: 't_order_fee', label: '费用' },
{ key: 't_customer', label: '客户' },
{ key: '_virtual', label: '常用' },
]
export type OrderTableFieldDef = {
@ -18,6 +17,8 @@ export type OrderTableFieldDef = {
/** 公式与按钮上使用的中文名称(唯一) */
label: string
valueType: FieldValueType
/** 非库表聚合字段 */
virtual?: boolean
}
export type FormulaFieldRef = {
@ -200,12 +201,12 @@ export const ORDER_TABLE_FIELDS: OrderTableFieldDef[] = [
{ table: 't_customer', field: 'CustomerGroup', label: '客户组', valueType: 'string' },
]
/** 虚拟/聚合字段(无直接库表列,后端按中文名解析) */
/** 聚合字段(无直接库表列,归入件重尺分类展示) */
export const VIRTUAL_FORMULA_FIELDS: OrderTableFieldDef[] = [
{ table: '_virtual', field: 'PieceMaxLength', label: '单件最大长度', valueType: 'number' },
{ table: '_virtual', field: 'PieceMaxWidth', label: '单件最大宽度', valueType: 'number' },
{ table: '_virtual', field: 'PieceMaxHeight', label: '单件最大高度', valueType: 'number' },
{ table: '_virtual', field: 'PieceSumLwh', label: '单件长宽高之和', valueType: 'number' },
{ table: 't_order_weight', field: 'PieceMaxLength', label: '单件最大长度', valueType: 'number', virtual: true },
{ table: 't_order_weight', field: 'PieceMaxWidth', label: '单件最大宽度', valueType: 'number', virtual: true },
{ table: 't_order_weight', field: 'PieceMaxHeight', label: '单件最大高度', valueType: 'number', virtual: true },
{ table: 't_order_weight', field: 'PieceSumLwh', label: '单件长宽高之和', valueType: 'number', virtual: true },
]
export type FormulaChip = {
@ -229,8 +230,8 @@ function buildInsert(def: OrderTableFieldDef): string {
}
function buildRefHint(def: OrderTableFieldDef): string {
if (def.table === '_virtual') {
return `虚拟字段 · ${def.field}`
if (def.virtual) {
return `聚合字段 · ${def.field}`
}
return `${def.table}.${def.field}`
}
@ -239,7 +240,7 @@ function buildChipsFromFields(fields: OrderTableFieldDef[]): FormulaChip[] {
return fields.map((def) => {
registerRef(
def.label,
def.table === '_virtual' ? virtualRef(def.field) : fieldRef(def.table, def.field)
def.virtual ? virtualRef(def.field) : fieldRef(def.table, def.field)
)
return {
table: def.table,

View File

@ -6,21 +6,20 @@ import HandsontablePro from '@/components/HandsontablePro/index.vue'
import { useTableContainerHeight } from '@/composables/useTableContainerHeight'
import ModalPro from '@/components/ModalPro/index.vue'
import useModal from '@/components/ModalPro/useModal'
import dayjs from 'dayjs'
import SelectPro from '@/components/SelectPro/index.vue'
import { Modal } from '@arco-design/web-vue'
import { getDictListAll } from '@/api/system/dict'
import { UserService } from '@/api/rbac'
import {
createAutoTrigger,
deleteAutoTrigger,
getAutoTriggerList,
testAutoTriggerFormula,
toggleAutoTriggerStatus,
updateAutoTrigger,
} from '@/api/channel/autoTrigger'
import FormulaConditionEditor from './components/FormulaConditionEditor.vue'
import {
formatConditionSummary,
getOversizeExampleFormula,
parseStoredCondition,
serializeStoredCondition,
validateFormulaExpression,
@ -37,7 +36,6 @@ type AutoTriggerRow = {
id: number
status: boolean
ruleName: string
priority: number
operation: string
triggerTiming: string
triggerCondition: string
@ -63,7 +61,6 @@ function mapRow(r: any): AutoTriggerRow {
id: r.id ?? r.Id,
status: (r.status ?? r.Status) === 1 || (r.status ?? r.Status) === true,
ruleName: (r.ruleName ?? r.RuleName ?? parsed.ruleName) || '',
priority: Number(r.priority ?? r.Priority ?? parsed.priority ?? 100) || 100,
operation: r.operation ?? r.Operation ?? '',
triggerTiming: r.triggerTiming ?? r.TriggerTiming ?? '',
triggerCondition,
@ -91,6 +88,7 @@ async function loadList() {
}
tableData.value = mapped
totalCount.value = Number(total || 0)
void ensureNotifierUserNames(mapped)
} catch (e: any) {
$baseMessage(e?.message || '加载失败', 'error')
tableData.value = []
@ -220,27 +218,62 @@ const editId = ref<number | null>(null)
const legacyConditionText = ref('')
const formulaText = ref('')
const formulaEditorRef = ref<InstanceType<typeof FormulaConditionEditor> | null>(null)
const testLoading = ref(false)
const testResult = ref<{ matched: boolean; error?: string } | null>(null)
const testSample = reactive({
consigneeCountry: 'GB',
customerName: '阿里国际站/深圳一达通',
productCode: 'EX_ASP_HKDHL_YD',
length: 65,
width: 40,
height: 30,
})
const notifierUserRef = ref<InstanceType<typeof SelectPro> | null>(null)
async function getRbacUserList(params: { pageIndex?: number; pageSize?: number; keyword?: string }) {
const res = await UserService.getRbacUserGetList(
params.keyword,
undefined,
params.pageIndex ?? 1,
params.pageSize ?? 30,
)
return { items: res?.items ?? [] }
}
function parseNotifierIds(notifier: string | undefined | null): string[] {
return String(notifier ?? '')
.split(/[,;,\s]+/)
.map((x) => x.trim())
.filter(Boolean)
}
function formatNotifierDisplay(notifier: string | undefined | null): string {
const ids = parseNotifierIds(notifier)
if (!ids.length) return ''
return ids
.map((id) => notifierUserNameMap.value[id] ?? id)
.join('、')
}
const notifierUserNameMap = ref<Record<string, string>>({})
async function ensureNotifierUserNames(rows: AutoTriggerRow[]) {
const ids = new Set<string>()
for (const row of rows) {
parseNotifierIds(row.notifier).forEach((id) => ids.add(id))
}
const missing = [...ids].filter((id) => !notifierUserNameMap.value[id])
if (!missing.length) return
await Promise.all(
missing.map(async (id) => {
try {
const user = await UserService.getRbacUserGet(id)
notifierUserNameMap.value[id] = user?.name ?? user?.account ?? id
} catch {
notifierUserNameMap.value[id] = id
}
}),
)
}
const formModel = reactive({
status: true,
ruleName: '',
priority: 100,
operationCode: 'intercept',
timingCode: 'forecast',
promptMessage: '',
notifier: '',
createTime: '',
creator: '',
notifierIds: [] as string[],
})
function resetFormModel() {
@ -249,70 +282,13 @@ function resetFormModel() {
Object.assign(formModel, {
status: true,
ruleName: '',
priority: 100,
operationCode: 'intercept',
timingCode: 'forecast',
promptMessage: '',
notifier: '',
createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
creator: '当前用户',
notifierIds: [],
})
}
function applyExampleRule() {
formulaText.value = getOversizeExampleFormula()
formModel.ruleName = '英国阿里超尺寸拦截'
formModel.priority = 100
formModel.timingCode = 'forecast'
formModel.operationCode = 'intercept'
formModel.promptMessage = '超尺寸,禁止下单'
Object.assign(testSample, {
consigneeCountry: 'GB',
customerName: '阿里国际站/深圳一达通',
productCode: 'EX_ASP_HKDHL_YD',
length: 65,
width: 40,
height: 30,
})
}
async function handleTestFormula() {
const validateErr = validateFormulaExpression(formulaText.value)
if (validateErr) {
$baseMessage(validateErr, 'warning')
return
}
testLoading.value = true
testResult.value = null
try {
const result = await testAutoTriggerFormula({
expression: formulaText.value.trim(),
sample: {
consigneeCountry: testSample.consigneeCountry?.trim() || undefined,
customerName: testSample.customerName?.trim() || undefined,
productCode: testSample.productCode?.trim() || undefined,
length: Number(testSample.length) || undefined,
width: Number(testSample.width) || undefined,
height: Number(testSample.height) || undefined,
},
})
testResult.value = { matched: !!result?.matched, error: result?.error }
$baseMessage(
result?.error
? result.error
: result?.matched
? t('channel.autoTrigger.form.testMatched')
: t('channel.autoTrigger.form.testNotMatched'),
result?.error ? 'warning' : result?.matched ? 'success' : 'info'
)
} catch (e: any) {
testResult.value = { matched: false, error: e?.message }
$baseMessage(e?.message || t('channel.autoTrigger.form.testFailed'), 'error')
} finally {
testLoading.value = false
}
}
async function openAddModal() {
modalMode.value = 'add'
editId.value = null
@ -330,13 +306,10 @@ async function openEditModal(row: AutoTriggerRow) {
Object.assign(formModel, {
status: row.status,
ruleName: parsed.ruleName || row.ruleName || '',
priority: row.priority ?? parsed.priority ?? 100,
operationCode: resolveOperationCode(row.operation),
timingCode: resolveTimingCode(row.triggerTiming),
promptMessage: row.promptMessage,
notifier: row.notifier,
createTime: row.createTime,
creator: row.creator,
notifierIds: parseNotifierIds(row.notifier),
})
modalMethods.setModalProps({ title: modalTitle.value, width: 1000 })
modalMethods.openModal(true)
@ -369,15 +342,14 @@ async function handleAutoTriggerModalOk() {
const payload = {
status: formModel.status ? 1 : 0,
ruleName: formModel.ruleName.trim(),
priority: Number(formModel.priority) || 100,
priority: 100,
operation: operationSaveValue(formModel.operationCode),
triggerTiming: timingSaveValue(formModel.timingCode),
triggerCondition: serializeStoredCondition(formulaText.value, {
ruleName: formModel.ruleName.trim(),
priority: Number(formModel.priority) || 100,
}),
promptMessage: formModel.promptMessage.trim(),
notifier: formModel.notifier?.trim() || '',
notifier: formModel.notifierIds.map((id) => String(id).trim()).filter(Boolean).join(','),
}
try {
if (modalMode.value === 'add') {
@ -419,7 +391,7 @@ const hotColumns = computed(() => [
{ key: 'triggerTiming', label: t('channel.autoTrigger.table.triggerTiming'), width: 90 },
{ key: 'conditionSummary', label: t('channel.autoTrigger.table.triggerCondition'), width: 360 },
{ key: 'promptMessage', label: t('channel.autoTrigger.table.promptMessage'), width: 200 },
{ key: 'notifier', label: t('channel.autoTrigger.table.notifier'), width: 100 },
{ key: 'notifier', label: t('channel.autoTrigger.table.notifier'), width: 140 },
{ key: 'createTime', label: t('channel.autoTrigger.table.createTime'), width: 160 },
{ key: 'creator', label: t('channel.autoTrigger.table.creator'), width: 100 },
])
@ -472,6 +444,11 @@ function customCellRenderer(row: number, col: number, value: any, rowData: AutoT
return `<span class="condition-summary-cell" title="${text.replace(/"/g, '&quot;')}">${text}</span>`
}
if (colKey === 'notifier') {
const text = formatNotifierDisplay(rowData.notifier) || rowData.notifier || '—'
return `<span title="${text.replace(/"/g, '&quot;')}">${text}</span>`
}
return null
}
@ -1004,28 +981,6 @@ onMounted(() => {
}
}
.test-sample-panel {
margin-top: 8px;
padding: 12px;
border: 1px dashed #e5e6eb;
border-radius: 6px;
background: #fafbfc;
.test-sample-title {
font-size: 13px;
font-weight: 500;
color: #4e5969;
margin-bottom: 8px;
}
.test-sample-grid {
margin-bottom: 8px;
}
.test-result-alert {
margin-top: 8px;
}
}
</style>
<template>
@ -1156,67 +1111,11 @@ onMounted(() => {
</a-option>
</a-select>
</div>
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.table.priority') }}</label>
<a-input-number
v-model="formModel.priority"
:min="1"
:max="9999"
hide-button
style="width: 100%"
/>
</div>
<div class="form-row" />
</div>
<div class="condition-section">
<div class="section-head">
<label class="form-label required">{{ t('channel.autoTrigger.table.triggerCondition') }}</label>
<div class="section-actions">
<a-button type="text" size="small" @click="applyExampleRule">
{{ t('channel.autoTrigger.form.loadExample') }}
</a-button>
<a-button type="text" size="small" :loading="testLoading" @click="handleTestFormula">
{{ t('channel.autoTrigger.form.testFormula') }}
</a-button>
</div>
</div>
<FormulaConditionEditor ref="formulaEditorRef" v-model="formulaText" />
<div class="test-sample-panel">
<div class="test-sample-title">{{ t('channel.autoTrigger.form.testSample') }}</div>
<div class="form-grid test-sample-grid">
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.form.sampleCountry') }}</label>
<a-input v-model="testSample.consigneeCountry" allow-clear />
</div>
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.form.sampleCustomer') }}</label>
<a-input v-model="testSample.customerName" allow-clear />
</div>
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.form.sampleProduct') }}</label>
<a-input v-model="testSample.productCode" allow-clear />
</div>
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.form.sampleLength') }}</label>
<a-input-number v-model="testSample.length" :min="0" hide-button style="width: 100%" />
</div>
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.form.sampleWidth') }}</label>
<a-input-number v-model="testSample.width" :min="0" hide-button style="width: 100%" />
</div>
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.form.sampleHeight') }}</label>
<a-input-number v-model="testSample.height" :min="0" hide-button style="width: 100%" />
</div>
</div>
<a-alert
v-if="testResult"
class="test-result-alert"
:type="testResult.error ? 'warning' : testResult.matched ? 'success' : 'info'"
:title="testResult.error || (testResult.matched ? t('channel.autoTrigger.form.testMatched') : t('channel.autoTrigger.form.testNotMatched'))"
/>
</div>
</div>
<div class="form-grid">
@ -1229,22 +1128,21 @@ onMounted(() => {
</div>
<div class="form-row full">
<label class="form-label">{{ t('channel.autoTrigger.table.notifier') }}</label>
<a-input
v-model="formModel.notifier"
<SelectPro
ref="notifierUserRef"
v-model="formModel.notifierIds"
class="w-100%"
clearable
immediate
:placeholder="t('channel.autoTrigger.form.notifierPlaceholder')"
allow-clear
:api="getRbacUserList"
:label-keys="['name']"
id-key="id"
search-key="name"
:is-page="true"
:multiple="true"
/>
</div>
<template v-if="modalMode === 'edit'">
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.table.createTime') }}</label>
<a-input v-model="formModel.createTime" disabled />
</div>
<div class="form-row">
<label class="form-label">{{ t('channel.autoTrigger.table.creator') }}</label>
<a-input v-model="formModel.creator" disabled />
</div>
</template>
</div>
</div>
</ModalPro>

View File

@ -5,6 +5,8 @@
defineProps<{
label: string;
hasValue?: boolean;
tooltip?: string;
required?: boolean;
}>();
const emit = defineEmits<{
@ -16,8 +18,8 @@
<template>
<div class="form-label-with-preview">
<label class="form-label">{{ label }}</label>
<a-tooltip :content="t('channel.salesProducts.referencePreview.view')">
<label class="form-label" :class="{ required }">{{ label }}</label>
<a-tooltip :content="tooltip || t('channel.salesProducts.referencePreview.view')">
<button
type="button"
class="label-preview-btn"
@ -33,16 +35,23 @@
<style lang="less" scoped>
.form-label-with-preview {
display: flex;
display: inline-flex;
align-items: center;
gap: 4px;
min-height: 22px;
white-space: nowrap;
}
.form-label {
font-size: 14px;
font-weight: 500;
color: #262626;
&.required::after {
content: '*';
color: #f53f3f;
margin-left: 4px;
}
}
.label-preview-btn {

View File

@ -58,7 +58,6 @@
page: 1,
pageSize: 8,
noticeType: 'notice',
receiverType: 'user',
});
list.value = items ?? [];
} catch {

View File

@ -93,7 +93,6 @@
page: 1,
pageSize: 50,
noticeType: 'notice',
receiverType: 'user',
});
const list = (items ?? []).filter(
(row) => row.id != null && isPopupNotice(row) && !readIds.has(String(row.id))

View File

@ -4,6 +4,8 @@
import { IconFile, IconDownload, IconDelete, IconPlus, IconEdit } from '@arco-design/web-vue/es/icon';
import ExcelFileIcon from '@/components/icons/ExcelFileIcon.vue';
import CustomTemplateModal from './components/CustomTemplateModal.vue';
import FormLabelWithPreview from '@/views/channel/salesProducts/components/FormLabelWithPreview.vue';
import CustomerGuideDrawer from '@/views/order/priceCheck/components/CustomerGuideDrawer.vue';
import { Message, Modal } from '@arco-design/web-vue';
import { useI18n } from 'vue-i18n';
import * as XLSX from 'xlsx';
@ -158,12 +160,13 @@
}
type SingleSelectOption = { value: string; label: string };
type SingleProductOption = SingleSelectOption & { productId?: number; productName?: string };
/** 9610简易申报默认字典编码(字典 export_customs_mode) */
const SAMPLE_EXPORT_CUSTOMS_MODE_CODE = '9610Simple';
const singleReferenceLoading = ref(false);
const singleSalesProductOptions = ref<SingleSelectOption[]>([]);
const singleSalesProductOptions = ref<SingleProductOption[]>([]);
const singleCargoAttributeOptions = ref<SingleSelectOption[]>([]);
const singleExportCustomsModeOptions = ref<SingleSelectOption[]>([]);
const singleWarehouseOptions = ref<SingleSelectOption[]>([]);
@ -173,7 +176,8 @@
function normalizeProductRow(row: any) {
const code = String(row?.productCode ?? row?.ProductCode ?? '').trim();
const name = String(row?.productName ?? row?.ProductName ?? '').trim();
return { code, name };
const id = Number(row?.id ?? row?.Id ?? 0);
return { code, name, productId: id > 0 ? id : undefined };
}
function normalizeCargoDictRow(row: any) {
@ -226,8 +230,6 @@
{ key: 'isCod', desc: '是否COD(true/false)', example: 'false' },
{ key: 'codCurrency', desc: 'COD币种', example: 'USD' },
{ key: 'codSum', desc: 'COD金额', example: '0' },
{ key: 'declaredCurrency', desc: '申报币种(字典currency)', example: 'USD' },
{ key: 'declaredSum', desc: '申报金额(可选)', example: '' },
{ key: 'quantity', desc: '包裹数量', example: '1' },
{ key: 'receiver.recipientsName', desc: '收件人名称', example: 'Tom' },
{ key: 'receiver.companyName', desc: '收件人公司', example: '' },
@ -261,15 +263,17 @@
{ key: 'sender.streetAddress2', desc: '发件地址2', example: '' },
{ key: 'sender.streetAddress3', desc: '发件地址3', example: '' },
{ key: 'sender.houseNumber', desc: '发件门牌号', example: '88' },
{ key: 'declaredCurrency', desc: '申报币种(字典currency,默认USD)', example: 'USD' },
{ key: 'declaredSum', desc: '申报总金额(可选,不填自动汇总各行总金额)', example: '' },
{ key: 'items[0].cnName', desc: '申报品名(中)', example: '手机壳' },
{ key: 'items[0].enName', desc: '申报品名(英)', example: 'Phone Case' },
{ key: 'items[0].sku', desc: 'SKU', example: 'SKU001' },
{ key: 'items[0].unit', desc: '单位', example: 'pcs' },
{ key: 'items[0].unitPrice', desc: '单价', example: '2.5' },
{ key: 'items[0].unitWeight', desc: '单重', example: '0.1' },
{ key: 'items[0].unitPrice', desc: '单价(元)', example: '2.5' },
{ key: 'items[0].unitWeight', desc: '单重(kg)', example: '0.1' },
{ key: 'items[0].quantity', desc: '申报数量', example: '2' },
{ key: 'items[0].amount', desc: '总金额', example: '5' },
{ key: 'items[0].weight', desc: '总重量', example: '0.2' },
{ key: 'items[0].amount', desc: '总金额(元,可选,不填自动计算=单价×数量)', example: '5' },
{ key: 'items[0].weight', desc: '总重量(kg,可选,不填自动计算=单重×数量)', example: '0.2' },
{ key: 'items[0].imHsCode', desc: '进口HsCode', example: '' },
{ key: 'items[0].exHsCode', desc: '出口HsCode', example: '' },
{ key: 'items[0].skuImage', desc: '商品图片URL', example: '' },
@ -324,6 +328,7 @@
COD金额: 'codSum',
申报币种: 'declaredCurrency',
申报金额: 'declaredSum',
申报总金额: 'declaredSum',
包裹数量: 'quantity',
收件人名称: 'receiver.recipientsName',
收件姓名: 'receiver.recipientsName',
@ -374,11 +379,15 @@
SKU: 'items[0].sku',
单位: 'items[0].unit',
单价: 'items[0].unitPrice',
单价元: 'items[0].unitPrice',
单重: 'items[0].unitWeight',
单重kg: 'items[0].unitWeight',
申报数量: 'items[0].quantity',
数量: 'items[0].quantity',
总金额: 'items[0].amount',
总金额元: 'items[0].amount',
总重量: 'items[0].weight',
总重量kg: 'items[0].weight',
进口HsCode: 'items[0].imHsCode',
出口HsCode: 'items[0].exHsCode',
进口HS编码: 'items[0].imHsCode',
@ -625,6 +634,39 @@
return '';
}
function applyBatchDeclarationDerivedFields(payload: Record<string, any>) {
if (!String(payload.declaredCurrency ?? '').trim()) {
payload.declaredCurrency = 'USD';
}
const items = Array.isArray(payload.items) ? payload.items : [];
let declaredTotal = 0;
let hasDeclaredTotal = false;
items.forEach((item: any) => {
const unitPrice = parseNumberValue(item?.unitPrice);
const unitWeight = parseNumberValue(item?.unitWeight);
const quantity = parseNumberValue(item?.quantity);
if (parseNumberValue(item?.amount) === undefined && unitPrice !== undefined && quantity !== undefined) {
item.amount = unitPrice * quantity;
}
if (parseNumberValue(item?.weight) === undefined && unitWeight !== undefined && quantity !== undefined) {
item.weight = unitWeight * quantity;
}
const amount = parseNumberValue(item?.amount);
if (amount !== undefined) {
declaredTotal += amount;
hasDeclaredTotal = true;
}
});
if (parseNumberValue(payload.declaredSum) === undefined && hasDeclaredTotal) {
payload.declaredSum = declaredTotal;
}
}
function buildOrderPayloadFromRow(row: Record<string, any>) {
const payload: Record<string, any> = {};
Object.entries(row).forEach(([key, rawValue]) => {
@ -636,6 +678,7 @@
if (!payload.sender) payload.sender = {};
if (!Array.isArray(payload.items)) payload.items = [];
if (!payload.items.length) payload.items = [{}];
applyBatchDeclarationDerivedFields(payload);
return omitEmptyOptionalOrderFields(payload);
}
@ -905,6 +948,7 @@
}
const singleCollapseKeys = ref<string[]>(['basic']);
const singleFormScrollRef = ref<HTMLElement | null>(null);
const customerGuideDrawerRef = ref<InstanceType<typeof CustomerGuideDrawer> | null>(null);
const singlePanelRefs = reactive<Record<string, HTMLElement | null>>({
basic: null,
sender: null,
@ -939,7 +983,7 @@
isCod: false,
codCurrency: '',
codSum: '',
declaredCurrency: '',
declaredCurrency: 'USD',
quantity: '1',
receiver: {
recipientsName: '',
@ -1009,10 +1053,65 @@
],
});
function resolveDefaultDeclaredCurrency() {
const opts = singleCurrencyOptions.value;
const usd = opts.find((o) => String(o.value).trim().toUpperCase() === 'USD');
if (usd) return usd.value;
return opts[0]?.value ?? 'USD';
}
function formatDerivedDeclarationNumber(value: number) {
if (Number.isInteger(value)) return String(value);
return value.toFixed(4).replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
}
function syncDeclarationRowDerivedFields(item: any) {
const unitPrice = parseNumberValue(item.unitPrice);
const unitWeight = parseNumberValue(item.unitWeight);
const quantity = parseNumberValue(item.quantity);
if (unitPrice !== undefined && quantity !== undefined) {
item.amount = formatDerivedDeclarationNumber(unitPrice * quantity);
} else {
item.amount = '';
}
if (unitWeight !== undefined && quantity !== undefined) {
item.weight = formatDerivedDeclarationNumber(unitWeight * quantity);
} else {
item.weight = '';
}
}
function syncAllDeclarationRowDerivedFields() {
(singleForm.items || []).forEach((item: any) => syncDeclarationRowDerivedFields(item));
}
function calcSingleDeclaredTotalAmount() {
const items = singleForm.items || [];
let total = 0;
let hasValue = false;
for (const item of items) {
const amount = parseNumberValue(item.amount);
if (amount !== undefined) {
total += amount;
hasValue = true;
}
}
return hasValue ? total : undefined;
}
const singleDeclaredTotalAmount = computed(() => {
const total = calcSingleDeclaredTotalAmount();
if (total === undefined) return '';
if (Number.isInteger(total)) return String(total);
return total.toFixed(4).replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
});
const singleDeclarationColumns: Array<{
key: string
label: string
type?: 'text' | 'number' | 'boolean'
/** 由单价/单重/数量自动计算,只读 */
derived?: boolean
/** 仅与 /order/parcel/create 请求体 JSON 行内「//必填」一致 */
required?: boolean
}> = [
@ -1020,11 +1119,11 @@
{ key: 'enName', label: '品名(英)', required: true },
{ key: 'sku', label: 'SKU' },
{ key: 'unit', label: '单位' },
{ key: 'unitPrice', label: '单价', type: 'number', required: true },
{ key: 'unitWeight', label: '单重', type: 'number', required: true },
{ key: 'unitPrice', label: '单价(元)', type: 'number', required: true },
{ key: 'unitWeight', label: '单重(kg)', type: 'number', required: true },
{ key: 'quantity', label: '数量', type: 'number', required: true },
{ key: 'amount', label: '总金额', type: 'number' },
{ key: 'weight', label: '总重量', type: 'number' },
{ key: 'amount', label: '总金额(元)', type: 'number', derived: true },
{ key: 'weight', label: '总重量(kg)', type: 'number', derived: true },
{ key: 'imHsCode', label: '进口HsCode' },
{ key: 'exHsCode', label: '出口HsCode' },
{ key: 'skuImage', label: '图片' },
@ -1044,6 +1143,20 @@
{ key: 'comment', label: '备注' },
];
function handleViewShippingCustomerGuide() {
const productCode = formTrim(singleForm.productCode);
if (!productCode) return;
const selected = singleSalesProductOptions.value.find((opt) => opt.value === productCode);
if (!selected?.productId) {
Message.warning(t('order.priceCheck.customerGuide.missingProduct'));
return;
}
customerGuideDrawerRef.value?.open({
productId: selected.productId,
shippingMethod: selected.productName || selected.label,
});
}
async function loadSingleFormReferenceOptions() {
singleReferenceLoading.value = true;
try {
@ -1059,7 +1172,12 @@
singleSalesProductOptions.value = (productRes.items ?? [])
.map(normalizeProductRow)
.filter((p) => p.code)
.map((p) => ({ value: p.code, label: p.name ? `${p.name} ${p.code}` : p.code }));
.map((p) => ({
value: p.code,
label: p.name ? `${p.name} ${p.code}` : p.code,
productId: p.productId,
productName: p.name || p.code,
}));
const cargoOpts = (cargoDictRows ?? [])
.map(normalizeCargoDictRow)
.filter((d) => d.code)
@ -1097,8 +1215,8 @@
.sort((a, b) => a.sort - b.sort || a.code.localeCompare(b.code))
.map((c) => ({ value: c.code, label: c.code }));
singleCurrencyOptions.value = curOpts;
if (curOpts.length && !String(singleForm.declaredCurrency ?? '').trim()) {
singleForm.declaredCurrency = curOpts[0].value;
if (!String(singleForm.declaredCurrency ?? '').trim()) {
singleForm.declaredCurrency = resolveDefaultDeclaredCurrency();
}
singleCountryOptions.value = (countryRes.items ?? [])
@ -1209,7 +1327,7 @@
) {
return { message: '请填写实重(kg)', section: 'basic' };
}
if (!formTrim(singleForm.declaredCurrency)) return { message: '请选择申报币种', section: 'basic' };
if (!formTrim(singleForm.declaredCurrency)) return { message: '请选择申报币种', section: 'declaration' };
if (!formTrim(String(singleForm.quantity ?? ''))) return { message: '请填写包裹数量', section: 'basic' };
const receiver = singleForm.receiver;
@ -1283,6 +1401,10 @@
})),
};
payload.exportCustomsMode = exportMode || resolveExportCustomsMode9610Simple();
const declaredTotal = calcSingleDeclaredTotalAmount();
if (declaredTotal !== undefined) {
payload.declaredSum = declaredTotal;
}
return omitEmptyOptionalOrderFields(payload);
}
@ -1342,7 +1464,7 @@
singleForm.isCod = false;
singleForm.codCurrency = 'USD';
singleForm.codSum = '0';
singleForm.declaredCurrency = singleCurrencyOptions.value[0]?.value ?? 'USD';
singleForm.declaredCurrency = resolveDefaultDeclaredCurrency();
singleForm.quantity = '1';
singleForm.sender.senderName = 'Demo Sender';
@ -1468,6 +1590,13 @@
}
});
watch(
() => (singleForm.items || []).map(
(item: any) => `${item.unitPrice ?? ''}|${item.unitWeight ?? ''}|${item.quantity ?? ''}`,
),
() => syncAllDeclarationRowDerivedFields(),
);
function handleSingleFlowClick(stepKey: string) {
focusSingleSection(stepKey);
}
@ -1757,7 +1886,16 @@
</span>
</template>
<div class="single-form-grid">
<a-form-item label="运输方式" required>
<a-form-item>
<template #label>
<FormLabelWithPreview
label="运输方式"
required
:has-value="!!formTrim(singleForm.productCode)"
:tooltip="t('order.placeOrder.single.viewCustomerGuide')"
@preview="handleViewShippingCustomerGuide"
/>
</template>
<a-select
v-model="singleForm.productCode"
allow-search
@ -1827,22 +1965,6 @@
<a-form-item label="宽(cm)"><a-input v-model="singleForm.width" /></a-form-item>
<a-form-item label="高(cm)"><a-input v-model="singleForm.height" /></a-form-item>
<a-form-item label="实重(kg)" required><a-input v-model="singleForm.actualWeight" /></a-form-item>
<a-form-item label="申报币种" required>
<a-select
v-model="singleForm.declaredCurrency"
allow-search
placeholder="请选择"
:loading="singleReferenceLoading"
>
<a-option
v-for="opt in singleCurrencyOptions"
:key="opt.value"
:value="opt.value"
>
{{ opt.label }}
</a-option>
</a-select>
</a-form-item>
<a-form-item label="包裹数量" required><a-input v-model="singleForm.quantity" /></a-form-item>
</div>
</a-collapse-item>
@ -1937,10 +2059,44 @@
:ref="(el) => (singlePanelRefs.declaration = (el as any)?.$el ?? null)"
>
<template #header>
<span class="single-section-header">
<div class="single-section-header declaration-section-header">
<span class="single-section-header-left">
<span class="single-section-index">4</span>
<span class="single-section-title">{{ t('order.placeOrder.single.stepDeclaration') }}</span>
</span>
<div class="single-section-header-right" @click.stop>
<div class="declaration-header-field">
<span class="declaration-header-label">申报总金额</span>
<a-input
class="declaration-header-input"
:model-value="singleDeclaredTotalAmount"
readonly
placeholder="自动汇总"
/>
</div>
<div class="declaration-header-field declaration-header-currency-row">
<span class="declaration-header-label required">申报币种</span>
<a-select
v-model="singleForm.declaredCurrency"
class="declaration-header-select"
allow-search
placeholder="请选择"
:loading="singleReferenceLoading"
>
<a-option
v-for="opt in singleCurrencyOptions"
:key="opt.value"
:value="opt.value"
>
{{ opt.label }}
</a-option>
</a-select>
<span class="declaration-header-hint">
{{ t('order.placeOrder.single.declaredCurrencyHint') }}
</span>
</div>
</div>
</div>
</template>
<div class="single-declaration-table-wrap">
<table class="single-declaration-table">
@ -1983,6 +2139,14 @@
v-model="item[col.key]"
size="small"
/>
<a-input
v-else-if="col.derived"
:model-value="item[col.key]"
readonly
:type="col.type === 'number' ? 'number' : 'text'"
size="small"
class="declaration-derived-input"
/>
<a-input
v-else
v-model="item[col.key]"
@ -2064,6 +2228,8 @@
:standard-template-options="standardTemplateMappingOptions"
@success="onTemplateModalSuccess"
/>
<CustomerGuideDrawer ref="customerGuideDrawerRef" />
</div>
</template>
@ -2853,6 +3019,84 @@
min-width: 0;
}
.declaration-section-header {
display: flex;
width: 100%;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.single-section-header-left {
display: inline-flex;
align-items: center;
gap: 10px;
min-width: 0;
flex-shrink: 0;
}
.single-section-header-right {
display: flex;
align-items: center;
gap: 16px;
flex-shrink: 0;
margin-left: auto;
}
.declaration-header-currency-row {
flex-wrap: nowrap;
}
.declaration-header-hint {
font-size: 12px;
line-height: 1.4;
color: #86909c;
white-space: nowrap;
margin-left: 4px;
}
.declaration-header-field {
display: flex;
align-items: center;
gap: 8px;
}
.declaration-header-label {
font-size: 13px;
color: #4e5969;
white-space: nowrap;
&.required::before {
content: '*';
color: #f53f3f;
margin-right: 4px;
}
}
.declaration-header-input {
width: 120px;
}
.declaration-header-select {
width: 100px;
}
.declaration-header-input,
.declaration-header-select {
:deep(.arco-input-wrapper),
:deep(.arco-select-view) {
min-height: 28px;
background: #fff;
}
}
.declaration-derived-input {
:deep(.arco-input-wrapper) {
background: #f7f8fa;
color: #4e5969;
}
}
.single-section-index {
width: 22px;
height: 22px;

View File

@ -0,0 +1,214 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Modal } from '@arco-design/web-vue'
import HandsontablePro from '@/components/HandsontablePro/index.vue'
import PaginationPro from '@/components/PaginationPro/index.vue'
import ModalPro from '@/components/ModalPro/index.vue'
import useModal from '@/components/ModalPro/useModal'
import FormPro from '@/components/FormPro/index.vue'
import { useTableContainerHeight } from '@/composables/useTableContainerHeight'
import { deletePlatformStore, getPlatformStoreAuthUrl, getPlatformStoreList, savePlatformStore } from '@/api/order/platformStore'
import { $baseMessage } from '@/utils'
import { hasPermission } from '@/utils/rbac-permission'
defineOptions({ name: 'PlatformStore' })
const { t } = useI18n()
const { tableContainerRef, tableHeight } = useTableContainerHeight()
const platformCode = ref<string>()
const keyword = ref('')
const listLoading = ref(false)
const tableRows = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(30)
const totalCount = ref(0)
const platformOptions = computed(() => [
{ label: 'Shopee', value: 'shopee' },
{ label: 'Lazada', value: 'lazada' },
{ label: 'TikTok', value: 'tiktok' },
{ label: 'Temu', value: 'temu' },
{ label: t('order.platformStore.platform.manual'), value: 'manual' },
])
const { visible: modalVisible, open: openModal, close: closeModal } = useModal()
const saving = ref(false)
const formModel = reactive({
id: 0,
platformCode: 'manual',
storeNickname: '',
platformAccount: '',
siteCountry: '',
isAutoFulfill: false,
remark: '',
})
const hotColumns = computed(() => [
{ key: 'platformName', label: t('order.platformStore.table.platform'), width: 100 },
{ key: 'storeNickname', label: t('order.platformStore.table.nickname'), width: 160 },
{ key: 'platformAccount', label: t('order.platformStore.table.account'), width: 140 },
{ key: 'authStatus', label: t('order.platformStore.table.authStatus'), width: 100 },
{ key: 'tokenExpireTime', label: t('order.platformStore.table.tokenExpire'), width: 170 },
])
async function loadList() {
listLoading.value = true
try {
const { items, total } = await getPlatformStoreList({
page: currentPage.value,
pageSize: pageSize.value,
platformCode: platformCode.value,
storeNickname: keyword.value || undefined,
})
tableRows.value = items || []
totalCount.value = Number(total || 0)
} catch (e: any) {
$baseMessage(e?.message || t('order.platformStore.message.loadFailed'), 'error')
} finally {
listLoading.value = false
}
}
function handleAdd() {
if (!hasPermission('Order.PlatformStore.Save')) return
Object.assign(formModel, { id: 0, platformCode: 'manual', storeNickname: '', platformAccount: '', siteCountry: '', isAutoFulfill: false, remark: '' })
openModal()
}
function handleEdit(row: any) {
if (!hasPermission('Order.PlatformStore.Save')) return
Object.assign(formModel, row)
openModal()
}
async function handleSave() {
if (!formModel.storeNickname.trim()) {
$baseMessage(t('order.platformStore.message.required'), 'warning')
return
}
saving.value = true
try {
await savePlatformStore({ ...formModel })
$baseMessage(t('order.platformStore.message.saveSuccess'), 'success')
closeModal()
await loadList()
} catch (e: any) {
$baseMessage(e?.message || t('order.platformStore.message.saveFailed'), 'error')
} finally {
saving.value = false
}
}
async function handleAuth(row: any) {
if (!hasPermission('Order.PlatformStore.Auth')) return
try {
const result = await getPlatformStoreAuthUrl({ platformCode: row.platformCode })
$baseMessage(result?.message || result?.authUrl || t('order.platformStore.message.authPlaceholder'), 'info')
} catch (e: any) {
$baseMessage(e?.message || t('order.platformStore.message.authFailed'), 'error')
}
}
function handleDelete(row: any) {
if (!hasPermission('Order.PlatformStore.Delete')) return
Modal.confirm({
title: t('order.platformStore.actions.delete'),
content: row.storeNickname,
onOk: async () => {
await deletePlatformStore([row.id])
$baseMessage(t('order.platformStore.message.deleteSuccess'), 'success')
await loadList()
},
})
}
function actionRenderer() {
const parts: string[] = []
if (hasPermission('Order.PlatformStore.Save')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="edit">${t('warehouse.common.edit')}</button>`)
}
if (hasPermission('Order.PlatformStore.Auth')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="auth">${t('order.platformStore.actions.auth')}</button>`)
}
if (hasPermission('Order.PlatformStore.Delete')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="delete">${t('warehouse.common.delete')}</button>`)
}
return parts.join('')
}
function handleActionClick(row: any, _i: number, action?: string) {
if (action === 'edit') handleEdit(row)
if (action === 'auth') handleAuth(row)
if (action === 'delete') handleDelete(row)
}
onMounted(loadList)
</script>
<template>
<div class="platform-store-container">
<div class="page-card">
<div class="table-toolbar">
<div class="toolbar-left">
<a-space wrap :size="8">
<a-select v-model="platformCode" allow-clear :placeholder="t('order.platformStore.search.platform')" :options="platformOptions" style="width: 160px" />
<a-input v-model="keyword" allow-clear :placeholder="t('order.platformStore.search.nickname')" style="width: 200px" />
<a-button type="primary" @click="() => { currentPage = 1; loadList() }">{{ t('warehouse.common.search') }}</a-button>
<a-button v-if="hasPermission('Order.PlatformStore.Save')" type="primary" @click="handleAdd">{{ t('warehouse.common.add') }}</a-button>
</a-space>
</div>
</div>
<div ref="tableContainerRef" class="list-wrap">
<HandsontablePro :columns="hotColumns" :data="tableRows" :height="tableHeight" :loading="listLoading" show-action-column :action-renderer="actionRenderer" @action-click="handleActionClick" />
</div>
<PaginationPro v-model:current="currentPage" v-model:page-size="pageSize" :total="totalCount" @change="loadList" @page-size-change="() => { currentPage = 1; loadList() }" />
</div>
<ModalPro v-model:visible="modalVisible" :title="formModel.id ? t('order.platformStore.modal.edit') : t('order.platformStore.modal.add')" :width="640" @cancel="closeModal">
<FormPro :model="formModel" layout="horizontal" :row-gutter="20" :default-span="12">
<a-form-item :label="t('order.platformStore.form.platform')" required>
<a-select v-model="formModel.platformCode" :options="platformOptions" :disabled="formModel.id > 0" />
</a-form-item>
<a-form-item :label="t('order.platformStore.form.nickname')" required>
<a-input v-model="formModel.storeNickname" />
</a-form-item>
<a-form-item :label="t('order.platformStore.form.account')">
<a-input v-model="formModel.platformAccount" />
</a-form-item>
<a-form-item :label="t('order.platformStore.form.autoFulfill')">
<a-switch v-model="formModel.isAutoFulfill" />
</a-form-item>
</FormPro>
<template #footer>
<a-button @click="closeModal">{{ t('warehouse.common.cancel') }}</a-button>
<a-button type="primary" :loading="saving" @click="handleSave">{{ t('warehouse.common.save') }}</a-button>
</template>
</ModalPro>
</div>
</template>
<style scoped lang="less">
.platform-store-container {
padding: 16px;
background: #f0f3f4;
min-height: 100%;
display: flex;
flex-direction: column;
}
.page-card {
background: #fff;
padding: 16px;
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
border-radius: 4px;
}
.list-wrap {
flex: 1;
min-height: 0;
margin-top: 12px;
}
</style>

View File

@ -0,0 +1,311 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Modal } from '@arco-design/web-vue'
import HandsontablePro from '@/components/HandsontablePro/index.vue'
import PaginationPro from '@/components/PaginationPro/index.vue'
import { useTableContainerHeight } from '@/composables/useTableContainerHeight'
import { getSalesProductList } from '@/api/channel/salesProduct'
import {
batchMatchPlatformStoreOrderInventory,
deletePlatformStoreOrder,
getPlatformStoreOrderDetail,
getPlatformStoreOrderList,
getPlatformStoreOrderSummary,
matchPlatformStoreOrderInventory,
togglePlatformStoreOrderSuspend,
} from '@/api/order/platformStore'
import { getWarehouseList } from '@/api/system/warehouse'
import { $baseMessage } from '@/utils'
import { hasPermission } from '@/utils/rbac-permission'
defineOptions({ name: 'PlatformStoreOrder' })
const { t } = useI18n()
const { tableContainerRef, tableHeight } = useTableContainerHeight()
const fulfillStatus = ref<string>()
const keyword = ref('')
const summary = ref<Record<string, number>>({})
const warehouseOptions = ref<Array<{ label: string; value: number }>>([])
const productOptions = ref<Array<{ label: string; value: string }>>([])
const listLoading = ref(false)
const tableRows = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(30)
const totalCount = ref(0)
const statusTabs = [
{ value: undefined, labelKey: 'order.platformStoreOrder.status.all' },
{ value: 'pending', labelKey: 'order.platformStoreOrder.status.pending' },
{ value: 'toShip', labelKey: 'order.platformStoreOrder.status.toShip' },
{ value: 'shipped', labelKey: 'order.platformStoreOrder.status.shipped' },
]
const detailVisible = ref(false)
const detailData = ref<any>(null)
const matchWarehouseId = ref<number>()
const matchProductCode = ref<string>()
const hotColumns = computed(() => [
{ key: 'platformOrderNo', label: t('order.platformStoreOrder.table.orderNo'), width: 160 },
{ key: 'storeNickname', label: t('order.platformStoreOrder.table.store'), width: 120 },
{ key: 'fulfillStatus', label: t('order.platformStoreOrder.table.status'), width: 90 },
{ key: 'linkedServiceNo', label: t('order.platformStoreOrder.table.linkedServiceNo'), width: 150 },
{ key: 'totalAmount', label: t('order.platformStoreOrder.table.amount'), width: 90 },
{ key: 'platformOrderTime', label: t('order.platformStoreOrder.table.orderTime'), width: 170 },
])
async function loadProducts() {
try {
const { items } = await getSalesProductList({ page: 1, pageSize: 200, status: 1 })
productOptions.value = (items || [])
.map((p: any) => {
const code = p.productCode || p.ProductCode || ''
const name = p.productName || p.ProductName || code
return { label: `${name} (${code})`, value: code }
})
.filter((p: { value: string }) => !!p.value)
if (productOptions.value.length && !matchProductCode.value) {
matchProductCode.value = productOptions.value[0].value
}
} catch {
productOptions.value = []
}
}
async function loadSummary() {
try {
const data = await getPlatformStoreOrderSummary()
summary.value = data || {}
} catch {
summary.value = {}
}
}
async function loadList() {
listLoading.value = true
try {
const { items, total } = await getPlatformStoreOrderList({
page: currentPage.value,
pageSize: pageSize.value,
fulfillStatus: fulfillStatus.value,
platformOrderNo: keyword.value || undefined,
})
tableRows.value = (items || []).map((r: any) => ({
...r,
fulfillStatus: t(`order.platformStoreOrder.status.${r.fulfillStatus}`, r.fulfillStatus),
linkedServiceNo: r.linkedServiceNo || '-',
_raw: r,
}))
totalCount.value = Number(total || 0)
} catch (e: any) {
$baseMessage(e?.message || t('order.platformStoreOrder.message.loadFailed'), 'error')
} finally {
listLoading.value = false
}
}
async function showDetail(row: any) {
try {
detailData.value = await getPlatformStoreOrderDetail(row._raw?.id || row.id)
detailVisible.value = true
} catch (e: any) {
$baseMessage(e?.message || t('order.platformStoreOrder.message.detailFailed'), 'error')
}
}
function buildMatchPayload(id: number) {
return {
id,
warehouseId: matchWarehouseId.value,
productCode: matchProductCode.value || undefined,
}
}
async function handleMatch(row: any) {
if (!hasPermission('Order.PlatformStoreOrder.MatchInventory')) return
if (!matchWarehouseId.value) {
$baseMessage(t('order.platformStoreOrder.message.warehouseRequired'), 'warning')
return
}
try {
const result = await matchPlatformStoreOrderInventory(buildMatchPayload(row._raw?.id || row.id))
$baseMessage(result?.message || t('order.platformStoreOrder.message.matchSuccess'), 'success')
await loadSummary()
await loadList()
} catch (e: any) {
$baseMessage(e?.message || t('order.platformStoreOrder.message.matchFailed'), 'error')
}
}
async function handleBatchMatch() {
if (!hasPermission('Order.PlatformStoreOrder.MatchInventory')) return
if (!matchWarehouseId.value) {
$baseMessage(t('order.platformStoreOrder.message.warehouseRequired'), 'warning')
return
}
const pendingIds = tableRows.value
.map((row) => row._raw || row)
.filter((raw) => raw.fulfillStatus === 'pending' && !raw.linkedOrderId)
.map((raw) => raw.id)
if (!pendingIds.length) {
$baseMessage(t('order.platformStoreOrder.message.batchEmpty'), 'warning')
return
}
Modal.confirm({
title: t('order.platformStoreOrder.actions.batchMatch'),
content: t('order.platformStoreOrder.message.batchConfirm', { count: pendingIds.length }),
onOk: async () => {
try {
const result = await batchMatchPlatformStoreOrderInventory({
ids: pendingIds,
warehouseId: matchWarehouseId.value,
productCode: matchProductCode.value || undefined,
})
$baseMessage(
t('order.platformStoreOrder.message.batchResult', {
success: result?.successCount ?? 0,
fail: result?.failCount ?? 0,
}),
(result?.failCount ?? 0) > 0 ? 'warning' : 'success',
)
await loadSummary()
await loadList()
} catch (e: any) {
$baseMessage(e?.message || t('order.platformStoreOrder.message.matchFailed'), 'error')
}
},
})
}
async function handleSuspend(row: any) {
if (!hasPermission('Order.PlatformStoreOrder.ToggleSuspend')) return
const raw = row._raw || row
await togglePlatformStoreOrderSuspend({ id: raw.id, isSuspended: !raw.isSuspended })
$baseMessage(t('order.platformStoreOrder.message.suspendSuccess'), 'success')
await loadList()
}
function handleDelete(row: any) {
if (!hasPermission('Order.PlatformStoreOrder.Delete')) return
Modal.confirm({
title: t('order.platformStoreOrder.actions.delete'),
content: row._raw?.platformOrderNo || row.platformOrderNo,
onOk: async () => {
await deletePlatformStoreOrder([row._raw?.id || row.id])
$baseMessage(t('order.platformStoreOrder.message.deleteSuccess'), 'success')
await loadList()
},
})
}
function actionRenderer(row: any) {
const parts = [`<button type="button" class="hot-action-btn" data-action="detail">${t('warehouse.common.detail')}</button>`]
const raw = row._raw || row
if (hasPermission('Order.PlatformStoreOrder.MatchInventory') && raw.fulfillStatus === 'pending' && !raw.linkedOrderId) {
parts.push(`<button type="button" class="hot-action-btn" data-action="match">${t('order.platformStoreOrder.actions.match')}</button>`)
}
if (hasPermission('Order.PlatformStoreOrder.ToggleSuspend')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="suspend">${raw.isSuspended ? t('order.platformStoreOrder.actions.resume') : t('order.platformStoreOrder.actions.suspend')}</button>`)
}
if (hasPermission('Order.PlatformStoreOrder.Delete')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="delete">${t('warehouse.common.delete')}</button>`)
}
return parts.join('')
}
function handleActionClick(row: any, _i: number, action?: string) {
if (action === 'detail') showDetail(row)
if (action === 'match') handleMatch(row)
if (action === 'suspend') handleSuspend(row)
if (action === 'delete') handleDelete(row)
}
onMounted(async () => {
const { items } = await getWarehouseList({ page: 1, pageSize: 200 }).catch(() => ({ items: [] }))
warehouseOptions.value = (items || []).map((w: any) => ({ label: w.warehouseName || `#${w.id}`, value: Number(w.id) }))
if (warehouseOptions.value.length) matchWarehouseId.value = warehouseOptions.value[0].value
await loadProducts()
await loadSummary()
await loadList()
})
</script>
<template>
<div class="platform-store-order-container">
<div class="page-card">
<a-tabs v-model:active-key="fulfillStatus" @change="() => { currentPage = 1; loadList() }">
<a-tab-pane v-for="tab in statusTabs" :key="tab.value ?? 'all'" :title="t(tab.labelKey)" />
</a-tabs>
<div class="table-toolbar">
<div class="toolbar-left">
<a-space wrap :size="8">
<a-select v-model="matchWarehouseId" :placeholder="t('warehouse.common.warehouse')" :options="warehouseOptions" style="width: 180px" />
<a-select v-model="matchProductCode" allow-clear :placeholder="t('order.platformStoreOrder.form.product')" :options="productOptions" style="width: 220px" />
<a-input v-model="keyword" allow-clear :placeholder="t('order.platformStoreOrder.search.orderNo')" style="width: 180px" />
<a-button type="primary" @click="() => { currentPage = 1; loadList() }">{{ t('warehouse.common.search') }}</a-button>
<a-button v-if="hasPermission('Order.PlatformStoreOrder.MatchInventory')" @click="handleBatchMatch">
{{ t('order.platformStoreOrder.actions.batchMatch') }}
</a-button>
</a-space>
</div>
<div class="toolbar-right">
<a-space :size="12">
<span>{{ t('order.platformStoreOrder.summary.pending') }}: {{ summary.pending ?? 0 }}</span>
<span>{{ t('order.platformStoreOrder.summary.toShip') }}: {{ summary.toShip ?? 0 }}</span>
</a-space>
</div>
</div>
<div ref="tableContainerRef" class="list-wrap">
<HandsontablePro :columns="hotColumns" :data="tableRows" :height="tableHeight" :loading="listLoading" show-action-column :action-renderer="actionRenderer" @action-click="handleActionClick" />
</div>
<PaginationPro v-model:current="currentPage" v-model:page-size="pageSize" :total="totalCount" @change="loadList" @page-size-change="() => { currentPage = 1; loadList() }" />
</div>
<a-drawer v-model:visible="detailVisible" :title="t('order.platformStoreOrder.drawer.detail')" :width="720">
<template v-if="detailData">
<p>{{ detailData.platformOrderNo }} · {{ detailData.storeNickname }}</p>
<p v-if="detailData.linkedServiceNo">
{{ t('order.platformStoreOrder.table.linkedServiceNo') }}: {{ detailData.linkedServiceNo }}
<span v-if="detailData.linkedOrderId">(#{{ detailData.linkedOrderId }})</span>
</p>
<a-table :data="detailData.lines || []" :pagination="false" size="small">
<template #columns>
<a-table-column :title="t('order.platformStoreOrder.line.sku')" data-index="platformSku" />
<a-table-column :title="t('order.platformStoreOrder.line.name')" data-index="productName" />
<a-table-column :title="t('order.platformStoreOrder.line.qty')" data-index="quantity" />
<a-table-column :title="t('order.platformStoreOrder.line.mappedSku')" data-index="mappedSkuCode" />
</template>
</a-table>
</template>
</a-drawer>
</div>
</template>
<style scoped lang="less">
.platform-store-order-container {
padding: 16px;
background: #f0f3f4;
min-height: 100%;
display: flex;
flex-direction: column;
}
.page-card {
background: #fff;
padding: 16px;
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
border-radius: 4px;
}
.list-wrap {
flex: 1;
min-height: 0;
margin-top: 12px;
}
</style>

File diff suppressed because it is too large Load Diff

View File

@ -75,8 +75,8 @@
size="small"
class="action-btn sync-btn"
:loading="syncLoadingId === record.id"
:title="t('system.menu.actions.syncLevel3Buttons')"
@click="handleSyncLevel3Buttons(record)"
:title="getSyncButtonTitle(record)"
@click="handleSyncMenu(record)"
>
<IconSync />
</a-button>
@ -189,7 +189,7 @@ import { MenuService } from '@/api/rbac'
import type { MenuDto, MenuTreeDto, MenuCreateDto, MenuUpdateDto, MenuType } from '@/api/rbac'
import { hasPermission } from '@/utils/rbac-permission'
import { handleApiError } from '@/utils/rbac-error-handler'
import { syncMenuLevel3Buttons } from '@/utils/syncMenuLevel3Buttons'
import { isModuleMenu, syncMenuTree } from '@/utils/syncMenuLevel3Buttons'
import MenuIconPicker from '@/components/MenuIconPicker/index.vue'
import { resolveArcoIcon, toPascalIconName } from '@/utils/menu-icon'
@ -400,11 +400,24 @@ async function handleDelete(id: string | undefined) {
}
}
function handleSyncLevel3Buttons(record: MenuTreeDto) {
function getSyncButtonTitle(record: MenuTreeDto) {
return isModuleMenu(record)
? t('system.menu.actions.syncSubMenusAndButtons')
: t('system.menu.actions.syncLevel3Buttons')
}
function handleSyncMenu(record: MenuTreeDto) {
if (!record.id) return
const moduleMode = isModuleMenu(record)
Modal.confirm({
title: t('system.menu.modal.syncLevel3Title'),
content: t('system.menu.modal.syncLevel3Content', {
title: moduleMode
? t('system.menu.modal.syncModuleTitle')
: t('system.menu.modal.syncLevel3Title'),
content: moduleMode
? t('system.menu.modal.syncModuleContent', {
name: record.name || record.permissionCode || '',
})
: t('system.menu.modal.syncLevel3Content', {
name: record.name || record.permissionCode || '',
}),
okText: t('system.menu.modal.syncLevel3Ok'),
@ -412,17 +425,45 @@ function handleSyncLevel3Buttons(record: MenuTreeDto) {
onOk: async () => {
syncLoadingId.value = record.id!
try {
const result = await syncMenuLevel3Buttons(record)
if (result.created > 0) {
const result = await syncMenuTree(record)
const hasChanges = result.level2Created > 0 || result.level3Created > 0
if (result.mode === 'module') {
if (hasChanges) {
Message.success(
t('system.menu.message.syncLevel3Success', {
created: result.created,
skipped: result.skipped,
t('system.menu.message.syncModuleSuccess', {
level2Created: result.level2Created,
level2Skipped: result.level2Skipped,
level3Created: result.level3Created,
level3Skipped: result.level3Skipped,
}),
)
await loadData()
} else {
Message.info(t('system.menu.message.syncLevel3Skipped', { skipped: result.skipped }))
Message.info(
t('system.menu.message.syncModuleSkipped', {
level2Skipped: result.level2Skipped,
level3Skipped: result.level3Skipped,
}),
)
}
if (result.level3FailedPages.length > 0) {
Message.warning(
t('system.menu.message.syncModulePartialFailed', {
details: result.level3FailedPages.join(';'),
}),
)
}
} else if (result.level3Created > 0) {
Message.success(
t('system.menu.message.syncLevel3Success', {
created: result.level3Created,
skipped: result.level3Skipped,
}),
)
await loadData()
} else {
Message.info(t('system.menu.message.syncLevel3Skipped', { skipped: result.level3Skipped }))
}
} catch (error: any) {
Message.error(error?.message || t('system.menu.message.syncLevel3Failed'))

View File

@ -7,57 +7,61 @@
<div class="card-grid">
<div v-for="item in list" :key="item.id" class="warehouse-card-shell">
<a-card class="warehouse-card-arco">
<a-card class="warehouse-card-arco" :bordered="false">
<template #title>
<div class="warehouse-card-title">
<span class="warehouse-card-icon" aria-hidden="true">
<icon-home />
</span>
<span class="warehouse-card-title-text">{{ item.warehouseName }}</span>
<span class="warehouse-card-title-text" :title="item.warehouseName">{{ item.warehouseName }}</span>
</div>
</template>
<template #extra>
<div class="card-extra">
<a-tag size="small" color="arcoblue" class="warehouse-card-type-tag">
{{ getWarehouseTypeDisplay(item) }}
</a-tag>
<div class="card-actions">
<a-tooltip :content="$t('system.warehouseAddress.actions.copy')">
<a-button type="text" size="small" class="action-icon-btn" @click.stop="handleCopy(item)">
<template #icon><icon-copy /></template>
</a-button>
</a-tooltip>
<a-tooltip :content="$t('system.warehouseAddress.actions.edit')">
<a-button type="text" size="small" class="action-icon-btn" @click.stop="handleEdit(item)">
<template #icon><icon-edit /></template>
</a-button>
</a-tooltip>
<a-tooltip :content="$t('system.warehouseAddress.actions.delete')">
<a-button type="text" size="small" class="action-icon-btn action-icon-btn--danger" @click.stop="handleDelete(item)">
<template #icon><icon-delete /></template>
</a-button>
</a-tooltip>
</div>
</div>
</template>
<div class="card-body">
<div class="card-body-scroll">
<div class="card-row">
<span class="label">{{ $t('system.warehouseAddress.fields.recipient') }}:</span>
<span class="value">{{ item.recipient || '-' }}</span>
<span class="label">{{ $t('system.warehouseAddress.fields.recipient') }}</span>
<span class="value" :title="displayRecipient(item)">{{ displayRecipient(item) }}</span>
</div>
<div class="card-row">
<span class="label">{{ $t('system.warehouseAddress.fields.contactPhone') }}:</span>
<span class="value">{{ item.contactPhone || '-' }}</span>
<span class="label">{{ $t('system.warehouseAddress.fields.contactPhone') }}</span>
<span class="value" :title="item.contactPhone || '-'">{{ item.contactPhone || '-' }}</span>
</div>
<div class="card-row">
<span class="label">{{ $t('system.warehouseAddress.fields.shippingAddress') }}:</span>
<span class="value">{{ item.shippingAddress || '-' }}</span>
</div>
</div>
<div class="card-actions">
<a-space>
<a-button type="text" size="small" @click.stop="handleCopy(item)">
{{ $t('system.warehouseAddress.actions.copy') }}
</a-button>
<a-button type="text" size="small" @click.stop="handleEdit(item)">
{{ $t('system.warehouseAddress.actions.edit') }}
</a-button>
<a-button type="text" size="small" status="danger" @click.stop="handleDelete(item)">
{{ $t('system.warehouseAddress.actions.delete') }}
</a-button>
</a-space>
<div class="card-row card-row--address">
<span class="label">{{ $t('system.warehouseAddress.fields.shippingAddress') }}</span>
<span class="value value-address" :title="displayShippingAddress(item)">{{ displayShippingAddress(item) }}</span>
</div>
</div>
</a-card>
</div>
<div class="warehouse-card-shell warehouse-card-shell--add">
<a-card class="warehouse-card-arco add-card" @click="handleAdd">
<a-card class="warehouse-card-arco add-card" :bordered="false" @click="handleAdd">
<div class="add-card-inner">
<icon-plus class="add-icon" />
<span>{{ $t('system.warehouseAddress.actions.add') }}</span>
<span class="add-text">{{ $t('system.warehouseAddress.actions.add') }}</span>
</div>
</a-card>
</div>
@ -107,9 +111,10 @@
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { IconPlus, IconHome } from '@arco-design/web-vue/es/icon';
import { IconPlus, IconHome, IconCopy, IconEdit, IconDelete } from '@arco-design/web-vue/es/icon';
import { Modal } from '@arco-design/web-vue';
import { $baseMessage } from '@/utils';
import { resolveCurrentCustomer } from '@/api/customer/resolve';
import { getDictListAll } from '@/api/system/dict';
import {
createWarehouse,
@ -117,8 +122,11 @@ import {
getWarehouseList,
updateWarehouse,
} from '@/api/system/warehouse';
import { useRbacUserStore } from '@/store/modules/rbac-user';
import { getMapIdFromAccessToken } from '@/utils/jwt';
const { t } = useI18n();
const rbacUserStore = useRbacUserStore();
defineOptions({
name: 'WarehouseAddress',
@ -130,6 +138,36 @@ const isEdit = ref(false);
const editingId = ref<string | number | null>(null);
const warehouseTypeOptions = ref<Array<{ value: string; label: string }>>([]);
const currentCustomerCode = ref('');
function appendCustomerCode(value?: string, codeSuffix = ''): string {
const base = value?.trim() || '';
const code = currentCustomerCode.value.trim();
if (!code) return base || '-';
const tail = `${code}${codeSuffix}`;
if (!base) return tail;
if (base.endsWith(tail)) return base;
return `${base} ${tail}`;
}
function displayRecipient(item: { recipient?: string }) {
return appendCustomerCode(item.recipient);
}
function displayShippingAddress(item: { shippingAddress?: string }) {
return appendCustomerCode(item.shippingAddress, '号');
}
async function loadCurrentCustomerCode() {
try {
const mapId = getMapIdFromAccessToken(rbacUserStore.accessToken);
const account = rbacUserStore.userInfo?.account?.trim() || '';
const data = await resolveCurrentCustomer({ mapId, account });
currentCustomerCode.value = String(data?.customerCode ?? '').trim();
} catch {
currentCustomerCode.value = '';
}
}
async function loadWarehouseTypeDict() {
try {
@ -220,9 +258,9 @@ function handleAdd() {
function handleCopy(item: any) {
const lines = [
`${t('system.warehouseAddress.fields.recipient')}: ${item.recipient || '-'}`,
`${t('system.warehouseAddress.fields.recipient')}: ${displayRecipient(item)}`,
`${t('system.warehouseAddress.fields.contactPhone')}: ${item.contactPhone || '-'}`,
`${t('system.warehouseAddress.fields.shippingAddress')}: ${item.shippingAddress || '-'}`,
`${t('system.warehouseAddress.fields.shippingAddress')}: ${displayShippingAddress(item)}`,
];
const text = lines.join('\n');
navigator.clipboard.writeText(text).then(
@ -278,6 +316,7 @@ function handleModalCancel() {
onMounted(() => {
loadWarehouseTypeDict();
loadList();
loadCurrentCustomerCode();
});
</script>
@ -327,34 +366,57 @@ onMounted(() => {
padding: 16px;
box-sizing: border-box;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
grid-template-columns: repeat(auto-fill, minmax(496px, 1fr));
gap: 24px;
align-items: start;
}
/* 固定高度:grid 子项默认 min-height:auto 会按内容撑开,必须 min-height:0 才能让 height 生效 */
@warehouse-card-height: 400px;
@warehouse-card-height: 267px;
.warehouse-card-shell {
min-width: 0;
/* 覆盖 grid item 默认 min-height:auto,否则内容多高卡片就多高,改数字看不出变化 */
min-height: 0;
height: @warehouse-card-height;
max-height: @warehouse-card-height;
overflow: hidden;
display: flex;
flex-direction: column;
box-sizing: border-box;
:deep(.arco-card) {
flex: 1;
min-height: 0;
height: 100%;
max-height: 100%;
display: flex;
flex-direction: column;
box-sizing: border-box;
border: 1px solid var(--color-border-2);
border-radius: 8px;
box-shadow: none;
transition: border-color 0.2s, box-shadow 0.2s;
}
:deep(.arco-card:hover) {
border-color: rgb(var(--primary-5));
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
:deep(.arco-card-header) {
height: auto;
min-height: 52px;
padding: 16px 20px;
border-bottom: 1px solid var(--color-border-1);
}
:deep(.arco-card-header-title) {
flex: 1;
min-width: 0;
}
:deep(.arco-card-header-extra) {
flex-shrink: 0;
margin-left: 12px;
}
:deep(.arco-card-body) {
@ -362,13 +424,13 @@ onMounted(() => {
display: flex;
flex-direction: column;
min-height: 0;
overflow: auto;
padding: 16px 20px 20px;
}
.warehouse-card-title {
display: flex;
align-items: center;
gap: 8px;
gap: 12px;
min-width: 0;
}
@ -377,18 +439,12 @@ onMounted(() => {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 6px;
width: 40px;
height: 40px;
border-radius: 8px;
background: var(--color-fill-2);
color: var(--app-primary-color, rgb(var(--arcoblue-6)));
font-size: 16px;
}
.warehouse-card-type-tag {
flex-shrink: 0;
border-radius: 4px;
font-weight: 500;
font-size: 20px;
}
.warehouse-card-title-text {
@ -397,16 +453,59 @@ onMounted(() => {
text-overflow: ellipsis;
white-space: nowrap;
font-size: 18px;
font-weight: 700;
font-weight: 600;
line-height: 1.35;
color: var(--color-text-1);
}
.card-extra {
display: flex;
align-items: center;
gap: 8px;
}
.warehouse-card-type-tag {
flex-shrink: 0;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border-radius: 4px;
font-size: 13px;
line-height: 22px;
padding: 0 10px;
}
.card-actions {
display: flex;
align-items: center;
gap: 2px;
flex-shrink: 0;
}
.action-icon-btn {
width: 32px;
height: 32px;
padding: 0;
font-size: 16px;
color: var(--color-text-3);
&:hover {
color: rgb(var(--primary-6));
background: var(--color-fill-2);
}
}
.action-icon-btn--danger:hover {
color: rgb(var(--danger-6));
background: rgb(var(--danger-1));
}
&--add {
:deep(.arco-card.add-card) {
cursor: pointer;
border: 1px dashed #d9d9d9;
background: #fafafa;
border: 1px dashed var(--color-border-3);
background: var(--color-fill-1);
}
:deep(.arco-card-header) {
@ -415,74 +514,78 @@ onMounted(() => {
:deep(.arco-card-body) {
padding: 0;
justify-content: center;
align-items: center;
}
.add-card-inner {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 0;
padding: 16px;
gap: 12px;
width: 100%;
height: 100%;
padding: 24px;
box-sizing: border-box;
color: #8c8c8c;
color: var(--color-text-3);
.add-icon {
font-size: 48px;
margin-bottom: 12px;
}
.add-text {
font-size: 14px;
}
}
:deep(.arco-card.add-card:hover) {
border-color: rgb(var(--primary-6));
background: rgb(var(--primary-1));
.add-card-inner {
color: rgb(var(--primary-6));
}
:deep(.arco-card.add-card:hover .add-card-inner) {
color: rgb(var(--primary-6));
}
}
}
.card-body {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
.card-body-scroll {
flex: 1;
min-height: 0;
overflow: auto;
}
.card-actions {
flex-shrink: 0;
display: flex;
justify-content: flex-end;
align-items: center;
padding-top: 10px;
margin-top: 4px;
border-top: 1px solid var(--color-border-2);
}
flex-direction: column;
gap: 10px;
.card-row {
display: flex;
margin-bottom: 12px;
font-size: 13px;
align-items: flex-start;
gap: 12px;
font-size: 14px;
line-height: 1.5;
min-height: 22px;
.label {
flex-shrink: 0;
width: 80px;
color: #8c8c8c;
width: 72px;
color: var(--color-text-3);
}
.value {
flex: 1;
min-width: 0;
color: var(--color-text-1);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&--address .value-address {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
white-space: normal;
word-break: break-all;
}
}

View File

@ -0,0 +1,316 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Modal } from '@arco-design/web-vue'
import HandsontablePro from '@/components/HandsontablePro/index.vue'
import PaginationPro from '@/components/PaginationPro/index.vue'
import ModalPro from '@/components/ModalPro/index.vue'
import useModal from '@/components/ModalPro/useModal'
import FormPro from '@/components/FormPro/index.vue'
import { useTableContainerHeight } from '@/composables/useTableContainerHeight'
import {
deleteWarehouseInbound,
getWarehouseInboundDetail,
getWarehouseInboundList,
getWarehouseInboundSummary,
saveWarehouseInbound,
} from '@/api/warehouse'
import { getWarehouseList } from '@/api/system/warehouse'
import { getWarehouseSkuList } from '@/api/warehouse'
import { $baseMessage } from '@/utils'
import { hasPermission } from '@/utils/rbac-permission'
defineOptions({ name: 'WarehouseInboundNotice' })
const { t } = useI18n()
const { tableContainerRef, tableHeight } = useTableContainerHeight()
const receiptStatus = ref<string>()
const summary = ref({ forecasted: 0, received: 0, completed: 0 })
const keyword = ref('')
const warehouseId = ref<number>()
const warehouseOptions = ref<Array<{ label: string; value: number }>>([])
const skuOptions = ref<Array<{ label: string; value: number; code: string }>>([])
const listLoading = ref(false)
const tableRows = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(30)
const totalCount = ref(0)
const statusTabs = [
{ value: undefined, labelKey: 'warehouse.inbound.status.all', countKey: null },
{ value: 'forecasted', labelKey: 'warehouse.inbound.status.forecasted', countKey: 'forecasted' },
{ value: 'completed', labelKey: 'warehouse.inbound.status.completed', countKey: 'completed' },
]
const detailVisible = ref(false)
const detailData = ref<any>(null)
const { visible: modalVisible, open: openModal, close: closeModal } = useModal()
const saving = ref(false)
const formModel = reactive({
id: 0,
warehouseId: undefined as number | undefined,
markReference: '',
inboundType: 'normal',
remark: '',
skuId: undefined as number | undefined,
plannedQty: 1,
markBoxNo: '',
})
const hotColumns = computed(() => [
{ key: 'noticeNo', label: t('warehouse.inbound.table.noticeNo'), width: 180 },
{ key: 'markReference', label: t('warehouse.inbound.table.markReference'), width: 120 },
{ key: 'receiptStatus', label: t('warehouse.inbound.table.receiptStatus'), width: 100 },
{ key: 'boxCount', label: t('warehouse.inbound.table.boxCount'), width: 80 },
{ key: 'plannedQty', label: t('warehouse.inbound.table.plannedQty'), width: 90 },
{ key: 'createTime', label: t('warehouse.inbound.table.createTime'), width: 170 },
])
async function loadWarehouses() {
const { items } = await getWarehouseList({ page: 1, pageSize: 200 }).catch(() => ({ items: [] }))
warehouseOptions.value = (items || []).map((w: any) => ({
label: w.warehouseName || `#${w.id}`,
value: Number(w.id),
}))
}
async function loadSkus() {
const { items } = await getWarehouseSkuList({ page: 1, pageSize: 500 }).catch(() => ({ items: [] }))
skuOptions.value = (items || []).map((s: any) => ({
label: `${s.skuCode} - ${s.skuName}`,
value: Number(s.id),
code: s.skuCode,
}))
}
async function loadSummary() {
try {
const data = await getWarehouseInboundSummary({ warehouseId: warehouseId.value })
summary.value = {
forecasted: data?.forecasted ?? data?.Forecasted ?? 0,
received: data?.received ?? data?.Received ?? 0,
completed: data?.completed ?? data?.Completed ?? 0,
}
} catch {
summary.value = { forecasted: 0, received: 0, completed: 0 }
}
}
async function loadList() {
listLoading.value = true
try {
const { items, total } = await getWarehouseInboundList({
page: currentPage.value,
pageSize: pageSize.value,
receiptStatus: receiptStatus.value,
keyword: keyword.value || undefined,
warehouseId: warehouseId.value,
})
tableRows.value = (items || []).map((r: any) => ({
...r,
receiptStatus: t(`warehouse.inbound.status.${r.receiptStatus}`, r.receiptStatus),
_raw: r,
}))
totalCount.value = Number(total || 0)
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.inbound.message.loadFailed'), 'error')
} finally {
listLoading.value = false
}
}
async function showDetail(row: any) {
try {
detailData.value = await getWarehouseInboundDetail(row._raw?.id || row.id)
detailVisible.value = true
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.inbound.message.detailFailed'), 'error')
}
}
function handleAdd() {
if (!hasPermission('Warehouse.InboundNotice.Save')) return
formModel.id = 0
formModel.warehouseId = warehouseId.value
formModel.markReference = ''
formModel.remark = ''
formModel.skuId = undefined
formModel.plannedQty = 1
formModel.markBoxNo = ''
openModal()
}
async function handleSave() {
if (!formModel.warehouseId || !formModel.skuId) {
$baseMessage(t('warehouse.inbound.message.required'), 'warning')
return
}
const sku = skuOptions.value.find((s) => s.value === formModel.skuId)
saving.value = true
try {
await saveWarehouseInbound({
id: formModel.id,
warehouseId: formModel.warehouseId,
markReference: formModel.markReference,
inboundType: formModel.inboundType,
remark: formModel.remark,
boxes: [
{
boxSeqNo: '1',
markBoxNo: formModel.markBoxNo || 'BOX-001',
lines: [{ skuId: formModel.skuId, skuCode: sku?.code || '', plannedQty: formModel.plannedQty }],
},
],
})
$baseMessage(t('warehouse.inbound.message.saveSuccess'), 'success')
closeModal()
await loadSummary()
await loadList()
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.inbound.message.saveFailed'), 'error')
} finally {
saving.value = false
}
}
function handleDelete(row: any) {
if (!hasPermission('Warehouse.InboundNotice.Delete')) return
Modal.confirm({
title: t('warehouse.inbound.actions.delete'),
content: row._raw?.noticeNo || row.noticeNo,
onOk: async () => {
await deleteWarehouseInbound(row._raw?.id || row.id)
$baseMessage(t('warehouse.inbound.message.deleteSuccess'), 'success')
await loadSummary()
await loadList()
},
})
}
function actionRenderer(row: any) {
const parts = [`<button type="button" class="hot-action-btn" data-action="detail">${t('warehouse.common.detail')}</button>`]
const rawStatus = row._raw?.receiptStatus
if (hasPermission('Warehouse.InboundNotice.Delete') && rawStatus === 'forecasted') {
parts.push(`<button type="button" class="hot-action-btn" data-action="delete">${t('warehouse.common.delete')}</button>`)
}
return parts.join('')
}
function handleActionClick(row: any, _i: number, action?: string) {
if (action === 'detail') showDetail(row)
if (action === 'delete') handleDelete(row)
}
onMounted(async () => {
await loadWarehouses()
await loadSkus()
await loadSummary()
await loadList()
})
</script>
<template>
<div class="warehouse-inbound-container">
<div class="page-card">
<a-tabs v-model:active-key="receiptStatus" @change="() => { currentPage = 1; loadList() }">
<a-tab-pane v-for="tab in statusTabs" :key="tab.value ?? 'all'">
<template #title>
{{ t(tab.labelKey) }}
<span v-if="tab.countKey" class="tab-count">({{ summary[tab.countKey as 'forecasted' | 'completed'] }})</span>
</template>
</a-tab-pane>
</a-tabs>
<div class="table-toolbar">
<div class="toolbar-left">
<a-space wrap :size="8">
<a-select v-model="warehouseId" allow-clear :placeholder="t('warehouse.common.warehouse')" :options="warehouseOptions" style="width: 200px" @change="() => { loadSummary(); currentPage = 1; loadList() }" />
<a-input v-model="keyword" allow-clear :placeholder="t('warehouse.inbound.search.keyword')" style="width: 200px" />
<a-button type="primary" @click="() => { currentPage = 1; loadList() }">{{ t('warehouse.common.search') }}</a-button>
<a-button v-if="hasPermission('Warehouse.InboundNotice.Save')" type="primary" @click="handleAdd">{{ t('warehouse.common.add') }}</a-button>
</a-space>
</div>
</div>
<div ref="tableContainerRef" class="list-wrap">
<HandsontablePro :columns="hotColumns" :data="tableRows" :height="tableHeight" :loading="listLoading" show-action-column :action-renderer="actionRenderer" @action-click="handleActionClick" />
</div>
<PaginationPro v-model:current="currentPage" v-model:page-size="pageSize" :total="totalCount" @change="loadList" @page-size-change="() => { currentPage = 1; loadList() }" />
</div>
<a-drawer v-model:visible="detailVisible" :title="t('warehouse.inbound.drawer.detail')" :width="640">
<template v-if="detailData">
<p>{{ t('warehouse.inbound.table.noticeNo') }}: {{ detailData.noticeNo }}</p>
<div v-for="box in detailData.boxes || []" :key="box.id" class="box-block">
<div class="box-title">{{ t('warehouse.inbound.box') }}: {{ box.markBoxNo || box.boxSeqNo }}</div>
<a-table :data="box.lines || []" :pagination="false" size="small">
<template #columns>
<a-table-column :title="t('warehouse.inbound.line.skuCode')" data-index="skuCode" />
<a-table-column :title="t('warehouse.inbound.line.plannedQty')" data-index="plannedQty" />
<a-table-column :title="t('warehouse.inbound.line.receivedQty')" data-index="receivedQty" />
</template>
</a-table>
</div>
</template>
</a-drawer>
<ModalPro v-model:visible="modalVisible" :title="t('warehouse.inbound.modal.add')" :width="640" @cancel="closeModal">
<FormPro :model="formModel" layout="horizontal" :row-gutter="20" :default-span="12">
<a-form-item :label="t('warehouse.common.warehouse')" required>
<a-select v-model="formModel.warehouseId" :options="warehouseOptions" />
</a-form-item>
<a-form-item :label="t('warehouse.inbound.form.markReference')">
<a-input v-model="formModel.markReference" />
</a-form-item>
<a-form-item :label="t('warehouse.inbound.form.markBoxNo')">
<a-input v-model="formModel.markBoxNo" />
</a-form-item>
<a-form-item :label="t('warehouse.inbound.form.sku')" required>
<a-select v-model="formModel.skuId" :options="skuOptions" allow-search />
</a-form-item>
<a-form-item :label="t('warehouse.inbound.form.plannedQty')" required>
<a-input-number v-model="formModel.plannedQty" :min="1" style="width: 100%" />
</a-form-item>
</FormPro>
<template #footer>
<a-button @click="closeModal">{{ t('warehouse.common.cancel') }}</a-button>
<a-button type="primary" :loading="saving" @click="handleSave">{{ t('warehouse.common.save') }}</a-button>
</template>
</ModalPro>
</div>
</template>
<style scoped lang="less">
.warehouse-inbound-container {
padding: 16px;
background: #f0f3f4;
min-height: 100%;
display: flex;
flex-direction: column;
}
.page-card {
background: #fff;
padding: 16px;
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
border-radius: 4px;
}
.list-wrap {
flex: 1;
min-height: 0;
margin-top: 12px;
}
.box-block {
margin-bottom: 16px;
}
.box-title {
font-weight: 500;
margin-bottom: 8px;
}
.tab-count {
margin-left: 4px;
color: var(--app-primary-color);
}
</style>

View File

@ -0,0 +1,233 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import HandsontablePro from '@/components/HandsontablePro/index.vue'
import PaginationPro from '@/components/PaginationPro/index.vue'
import ModalPro from '@/components/ModalPro/index.vue'
import useModal from '@/components/ModalPro/useModal'
import FormPro from '@/components/FormPro/index.vue'
import { useTableContainerHeight } from '@/composables/useTableContainerHeight'
import {
getWarehouseInventoryBinDetail,
getWarehouseInventoryList,
relocateWarehouseInventory,
} from '@/api/warehouse'
import { getWarehouseList } from '@/api/system/warehouse'
import { $baseMessage } from '@/utils'
import { hasPermission } from '@/utils/rbac-permission'
defineOptions({ name: 'WarehouseInventory' })
const { t } = useI18n()
const { tableContainerRef, tableHeight } = useTableContainerHeight()
const listLoading = ref(false)
const tableRows = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(30)
const totalCount = ref(0)
const keyword = ref('')
const warehouseId = ref<number>()
const warehouseOptions = ref<Array<{ label: string; value: number }>>([])
const binDetailVisible = ref(false)
const binDetailRows = ref<any[]>([])
const activeSku = ref<any>(null)
const { visible: relocateVisible, open: openRelocate, close: closeRelocate } = useModal()
const relocateSaving = ref(false)
const relocateForm = ref({
sourceBinLocationId: undefined as number | undefined,
targetBinLocationId: undefined as number | undefined,
qty: 1,
})
const hotColumns = computed(() => [
{ key: 'skuCode', label: t('warehouse.inventory.table.skuCode'), width: 140 },
{ key: 'skuName', label: t('warehouse.inventory.table.skuName'), width: 200 },
{ key: 'warehouseId', label: t('warehouse.inventory.table.warehouseId'), width: 100 },
{ key: 'totalQty', label: t('warehouse.inventory.table.totalQty'), width: 90 },
{ key: 'binCount', label: t('warehouse.inventory.table.binCount'), width: 90 },
])
async function loadWarehouses() {
try {
const { items } = await getWarehouseList({ page: 1, pageSize: 200 })
warehouseOptions.value = (items || []).map((w: any) => ({
label: w.warehouseName || w.WarehouseName || `#${w.id}`,
value: Number(w.id),
}))
} catch {
warehouseOptions.value = []
}
}
async function loadList() {
listLoading.value = true
try {
const { items, total } = await getWarehouseInventoryList({
page: currentPage.value,
pageSize: pageSize.value,
keyword: keyword.value || undefined,
warehouseId: warehouseId.value,
})
tableRows.value = items || []
totalCount.value = Number(total || 0)
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.inventory.message.loadFailed'), 'error')
tableRows.value = []
totalCount.value = 0
} finally {
listLoading.value = false
}
}
async function showBinDetail(row: any) {
activeSku.value = row
try {
const data = await getWarehouseInventoryBinDetail(row.skuId, row.warehouseId)
binDetailRows.value = data?.items ?? data?.Items ?? (Array.isArray(data) ? data : [])
binDetailVisible.value = true
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.inventory.message.binDetailFailed'), 'error')
}
}
function openRelocateModal(row: any) {
if (!hasPermission('Warehouse.Inventory.Relocate')) return
activeSku.value = row
relocateForm.value = { sourceBinLocationId: undefined, targetBinLocationId: undefined, qty: 1 }
openRelocate()
}
async function submitRelocate() {
const row = activeSku.value
const f = relocateForm.value
if (!row || !f.sourceBinLocationId || !f.targetBinLocationId || !f.qty) {
$baseMessage(t('warehouse.inventory.message.relocateRequired'), 'warning')
return
}
relocateSaving.value = true
try {
await relocateWarehouseInventory({
warehouseId: row.warehouseId,
skuId: row.skuId,
sourceBinLocationId: f.sourceBinLocationId,
targetBinLocationId: f.targetBinLocationId,
qty: f.qty,
})
$baseMessage(t('warehouse.inventory.message.relocateSuccess'), 'success')
closeRelocate()
await loadList()
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.inventory.message.relocateFailed'), 'error')
} finally {
relocateSaving.value = false
}
}
function actionRenderer() {
const parts: string[] = [
`<button type="button" class="hot-action-btn" data-action="detail">${t('warehouse.inventory.actions.binDetail')}</button>`,
]
if (hasPermission('Warehouse.Inventory.Relocate')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="relocate">${t('warehouse.inventory.actions.relocate')}</button>`)
}
return parts.join('')
}
function handleActionClick(row: any, _idx: number, action?: string) {
if (action === 'detail') showBinDetail(row)
if (action === 'relocate') openRelocateModal(row)
}
onMounted(async () => {
await loadWarehouses()
await loadList()
})
</script>
<template>
<div class="warehouse-inventory-container">
<div class="page-card">
<div class="table-toolbar">
<div class="toolbar-left">
<a-space wrap :size="8">
<a-select
v-model="warehouseId"
allow-clear
:placeholder="t('warehouse.common.warehouse')"
:options="warehouseOptions"
style="width: 200px"
/>
<a-input v-model="keyword" allow-clear :placeholder="t('warehouse.inventory.search.keyword')" style="width: 200px" />
<a-button type="primary" @click="() => { currentPage = 1; loadList() }">{{ t('warehouse.common.search') }}</a-button>
</a-space>
</div>
</div>
<div ref="tableContainerRef" class="list-wrap">
<HandsontablePro
:columns="hotColumns"
:data="tableRows"
:height="tableHeight"
:loading="listLoading"
show-action-column
:action-renderer="actionRenderer"
@action-click="handleActionClick"
/>
</div>
<PaginationPro v-model:current="currentPage" v-model:page-size="pageSize" :total="totalCount" @change="loadList" @page-size-change="() => { currentPage = 1; loadList() }" />
</div>
<a-drawer v-model:visible="binDetailVisible" :title="t('warehouse.inventory.drawer.binDetail')" :width="520">
<a-table :data="binDetailRows" :pagination="false" size="small">
<template #columns>
<a-table-column :title="t('warehouse.inventory.table.binCode')" data-index="binCode" />
<a-table-column :title="t('warehouse.inventory.table.qty')" data-index="qty" />
</template>
</a-table>
</a-drawer>
<ModalPro v-model:visible="relocateVisible" :title="t('warehouse.inventory.modal.relocate')" :width="520" @cancel="closeRelocate">
<FormPro :model="relocateForm" layout="horizontal" :row-gutter="20" :default-span="24">
<a-form-item :label="t('warehouse.inventory.form.sourceBin')" required>
<a-input-number v-model="relocateForm.sourceBinLocationId" :min="1" style="width: 100%" />
</a-form-item>
<a-form-item :label="t('warehouse.inventory.form.targetBin')" required>
<a-input-number v-model="relocateForm.targetBinLocationId" :min="1" style="width: 100%" />
</a-form-item>
<a-form-item :label="t('warehouse.inventory.form.qty')" required>
<a-input-number v-model="relocateForm.qty" :min="1" style="width: 100%" />
</a-form-item>
</FormPro>
<template #footer>
<a-button @click="closeRelocate">{{ t('warehouse.common.cancel') }}</a-button>
<a-button type="primary" :loading="relocateSaving" @click="submitRelocate">{{ t('warehouse.common.confirm') }}</a-button>
</template>
</ModalPro>
</div>
</template>
<style scoped lang="less">
.warehouse-inventory-container {
padding: 16px;
background: #f0f3f4;
min-height: 100%;
display: flex;
flex-direction: column;
}
.page-card {
background: #fff;
padding: 16px;
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
border-radius: 4px;
}
.list-wrap {
flex: 1;
min-height: 0;
margin-top: 12px;
}
</style>

View File

@ -0,0 +1,226 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Modal } from '@arco-design/web-vue'
import HandsontablePro from '@/components/HandsontablePro/index.vue'
import PaginationPro from '@/components/PaginationPro/index.vue'
import ModalPro from '@/components/ModalPro/index.vue'
import useModal from '@/components/ModalPro/useModal'
import FormPro from '@/components/FormPro/index.vue'
import { useTableContainerHeight } from '@/composables/useTableContainerHeight'
import { deleteWarehouseParcel, getWarehouseParcelList, saveWarehouseParcel } from '@/api/warehouse'
import { getWarehouseList } from '@/api/system/warehouse'
import { $baseMessage } from '@/utils'
import { hasPermission } from '@/utils/rbac-permission'
defineOptions({ name: 'WarehouseParcel' })
const { t } = useI18n()
const { tableContainerRef, tableHeight } = useTableContainerHeight()
const lifecycleStatus = ref<string>()
const keyword = ref('')
const warehouseId = ref<number>()
const warehouseOptions = ref<Array<{ label: string; value: number }>>([])
const listLoading = ref(false)
const tableRows = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(30)
const totalCount = ref(0)
const statusTabs = [
{ value: undefined, labelKey: 'warehouse.parcel.status.all' },
{ value: 'inTransit', labelKey: 'warehouse.parcel.status.inTransit' },
{ value: 'arrived', labelKey: 'warehouse.parcel.status.arrived' },
{ value: 'stored', labelKey: 'warehouse.parcel.status.stored' },
]
const { visible: modalVisible, open: openModal, close: closeModal } = useModal()
const saving = ref(false)
const formModel = reactive({
id: 0,
warehouseId: undefined as number | undefined,
trackingNo: '',
carrierName: '',
lifecycleStatus: 'inTransit',
remark: '',
items: [{ productName: '', quantity: 1 }],
})
const hotColumns = computed(() => [
{ key: 'trackingNo', label: t('warehouse.parcel.table.trackingNo'), width: 160 },
{ key: 'carrierName', label: t('warehouse.parcel.table.carrierName'), width: 120 },
{ key: 'lifecycleStatus', label: t('warehouse.parcel.table.lifecycleStatus'), width: 100 },
{ key: 'warehouseId', label: t('warehouse.parcel.table.warehouseId'), width: 90 },
{ key: 'remark', label: t('warehouse.parcel.table.remark'), width: 160 },
])
async function loadWarehouses() {
try {
const { items } = await getWarehouseList({ page: 1, pageSize: 200 })
warehouseOptions.value = (items || []).map((w: any) => ({
label: w.warehouseName || w.WarehouseName || `#${w.id}`,
value: Number(w.id),
}))
} catch {
warehouseOptions.value = []
}
}
async function loadList() {
listLoading.value = true
try {
const { items, total } = await getWarehouseParcelList({
page: currentPage.value,
pageSize: pageSize.value,
lifecycleStatus: lifecycleStatus.value,
keyword: keyword.value || undefined,
warehouseId: warehouseId.value,
})
tableRows.value = (items || []).map((r: any) => ({
...r,
lifecycleStatus: t(`warehouse.parcel.status.${r.lifecycleStatus}`, r.lifecycleStatus),
_raw: r,
}))
totalCount.value = Number(total || 0)
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.parcel.message.loadFailed'), 'error')
tableRows.value = []
totalCount.value = 0
} finally {
listLoading.value = false
}
}
function handleAdd() {
if (!hasPermission('Warehouse.Parcel.Save')) return
formModel.id = 0
formModel.warehouseId = warehouseId.value
formModel.trackingNo = ''
formModel.carrierName = ''
formModel.lifecycleStatus = 'inTransit'
formModel.remark = ''
formModel.items = [{ productName: '', quantity: 1 }]
openModal()
}
async function handleSave() {
if (!formModel.warehouseId || !formModel.trackingNo.trim()) {
$baseMessage(t('warehouse.parcel.message.required'), 'warning')
return
}
saving.value = true
try {
await saveWarehouseParcel({ ...formModel })
$baseMessage(t('warehouse.parcel.message.saveSuccess'), 'success')
closeModal()
await loadList()
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.parcel.message.saveFailed'), 'error')
} finally {
saving.value = false
}
}
function handleDelete(row: any) {
if (!hasPermission('Warehouse.Parcel.Delete')) return
Modal.confirm({
title: t('warehouse.parcel.actions.delete'),
content: row._raw?.trackingNo || row.trackingNo,
onOk: async () => {
await deleteWarehouseParcel(row._raw?.id || row.id)
$baseMessage(t('warehouse.parcel.message.deleteSuccess'), 'success')
await loadList()
},
})
}
function actionRenderer() {
const parts: string[] = []
if (hasPermission('Warehouse.Parcel.Delete')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="delete">${t('warehouse.common.delete')}</button>`)
}
return parts.join('')
}
function handleActionClick(row: any, _i: number, action?: string) {
if (action === 'delete') handleDelete(row)
}
onMounted(async () => {
await loadWarehouses()
await loadList()
})
</script>
<template>
<div class="warehouse-parcel-container">
<div class="page-card">
<a-tabs v-model:active-key="lifecycleStatus" @change="() => { currentPage = 1; loadList() }">
<a-tab-pane v-for="tab in statusTabs" :key="tab.value ?? 'all'" :title="t(tab.labelKey)" />
</a-tabs>
<div class="table-toolbar">
<div class="toolbar-left">
<a-space wrap :size="8">
<a-select v-model="warehouseId" allow-clear :placeholder="t('warehouse.common.warehouse')" :options="warehouseOptions" style="width: 200px" />
<a-input v-model="keyword" allow-clear :placeholder="t('warehouse.parcel.search.trackingNo')" style="width: 200px" />
<a-button type="primary" @click="() => { currentPage = 1; loadList() }">{{ t('warehouse.common.search') }}</a-button>
<a-button v-if="hasPermission('Warehouse.Parcel.Save')" type="primary" @click="handleAdd">{{ t('warehouse.common.add') }}</a-button>
</a-space>
</div>
</div>
<div ref="tableContainerRef" class="list-wrap">
<HandsontablePro :columns="hotColumns" :data="tableRows" :height="tableHeight" :loading="listLoading" show-action-column :action-renderer="actionRenderer" @action-click="handleActionClick" />
</div>
<PaginationPro v-model:current="currentPage" v-model:page-size="pageSize" :total="totalCount" @change="loadList" @page-size-change="() => { currentPage = 1; loadList() }" />
</div>
<ModalPro v-model:visible="modalVisible" :title="t('warehouse.parcel.modal.add')" :width="640" @cancel="closeModal">
<FormPro :model="formModel" layout="horizontal" :row-gutter="20" :default-span="12">
<a-form-item :label="t('warehouse.common.warehouse')" required>
<a-select v-model="formModel.warehouseId" :options="warehouseOptions" />
</a-form-item>
<a-form-item :label="t('warehouse.parcel.form.trackingNo')" required>
<a-input v-model="formModel.trackingNo" />
</a-form-item>
<a-form-item :label="t('warehouse.parcel.form.carrierName')">
<a-input v-model="formModel.carrierName" />
</a-form-item>
<a-form-item :label="t('warehouse.parcel.form.productName')">
<a-input v-model="formModel.items[0].productName" />
</a-form-item>
<a-form-item :label="t('warehouse.parcel.form.quantity')">
<a-input-number v-model="formModel.items[0].quantity" :min="1" style="width: 100%" />
</a-form-item>
</FormPro>
<template #footer>
<a-button @click="closeModal">{{ t('warehouse.common.cancel') }}</a-button>
<a-button type="primary" :loading="saving" @click="handleSave">{{ t('warehouse.common.save') }}</a-button>
</template>
</ModalPro>
</div>
</template>
<style scoped lang="less">
.warehouse-parcel-container {
padding: 16px;
background: #f0f3f4;
min-height: 100%;
display: flex;
flex-direction: column;
}
.page-card {
background: #fff;
padding: 16px;
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
border-radius: 4px;
}
.list-wrap {
flex: 1;
min-height: 0;
margin-top: 12px;
}
</style>

View File

@ -0,0 +1,255 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Modal } from '@arco-design/web-vue'
import HandsontablePro from '@/components/HandsontablePro/index.vue'
import PaginationPro from '@/components/PaginationPro/index.vue'
import ModalPro from '@/components/ModalPro/index.vue'
import useModal from '@/components/ModalPro/useModal'
import FormPro from '@/components/FormPro/index.vue'
import { useTableContainerHeight } from '@/composables/useTableContainerHeight'
import { deleteWarehouseSku, getWarehouseSkuList, saveWarehouseSku } from '@/api/warehouse'
import { $baseMessage } from '@/utils'
import { hasPermission } from '@/utils/rbac-permission'
defineOptions({ name: 'WarehouseSku' })
const { t } = useI18n()
const { tableContainerRef, tableHeight } = useTableContainerHeight()
const listLoading = ref(false)
const tableRows = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(30)
const totalCount = ref(0)
const keyword = ref('')
const { visible: modalVisible, open: openModal, close: closeModal } = useModal()
const saving = ref(false)
const formModel = reactive({
id: 0,
skuCode: '',
skuName: '',
skuImageUrl: '',
weightG: undefined as number | undefined,
lengthCm: undefined as number | undefined,
widthCm: undefined as number | undefined,
heightCm: undefined as number | undefined,
remark: '',
})
const hotColumns = computed(() => [
{ key: 'skuCode', label: t('warehouse.sku.table.skuCode'), width: 140 },
{ key: 'skuName', label: t('warehouse.sku.table.skuName'), width: 200 },
{ key: 'totalQty', label: t('warehouse.sku.table.totalQty'), width: 90 },
{ key: 'weightG', label: t('warehouse.sku.table.weightG'), width: 90 },
{ key: 'remark', label: t('warehouse.sku.table.remark'), width: 160 },
])
function resetForm() {
formModel.id = 0
formModel.skuCode = ''
formModel.skuName = ''
formModel.skuImageUrl = ''
formModel.weightG = undefined
formModel.lengthCm = undefined
formModel.widthCm = undefined
formModel.heightCm = undefined
formModel.remark = ''
}
async function loadList() {
listLoading.value = true
try {
const { items, total } = await getWarehouseSkuList({
page: currentPage.value,
pageSize: pageSize.value,
keyword: keyword.value || undefined,
})
tableRows.value = (items || []).map((r: any) => ({
id: r.id,
skuCode: r.skuCode,
skuName: r.skuName,
totalQty: r.totalQty ?? 0,
weightG: r.weightG ?? '-',
remark: r.remark ?? '',
_raw: r,
}))
totalCount.value = Number(total || 0)
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.sku.message.loadFailed'), 'error')
tableRows.value = []
totalCount.value = 0
} finally {
listLoading.value = false
}
}
function handleSearch() {
currentPage.value = 1
loadList()
}
function handleAdd() {
if (!hasPermission('Warehouse.Sku.Save')) return
resetForm()
openModal()
}
function handleEdit(row: any) {
if (!hasPermission('Warehouse.Sku.Save')) return
const raw = row._raw || row
formModel.id = raw.id
formModel.skuCode = raw.skuCode || ''
formModel.skuName = raw.skuName || ''
formModel.skuImageUrl = raw.skuImageUrl || ''
formModel.weightG = raw.weightG
formModel.lengthCm = raw.lengthCm
formModel.widthCm = raw.widthCm
formModel.heightCm = raw.heightCm
formModel.remark = raw.remark || ''
openModal()
}
async function handleSave() {
if (!formModel.skuCode.trim() || !formModel.skuName.trim()) {
$baseMessage(t('warehouse.sku.message.required'), 'warning')
return
}
saving.value = true
try {
await saveWarehouseSku({ ...formModel })
$baseMessage(t('warehouse.sku.message.saveSuccess'), 'success')
closeModal()
await loadList()
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.sku.message.saveFailed'), 'error')
} finally {
saving.value = false
}
}
function handleDelete(row: any) {
if (!hasPermission('Warehouse.Sku.Delete')) return
Modal.confirm({
title: t('warehouse.sku.actions.delete'),
content: t('warehouse.sku.message.deleteConfirm', { code: row.skuCode }),
onOk: async () => {
try {
await deleteWarehouseSku(row.id)
$baseMessage(t('warehouse.sku.message.deleteSuccess'), 'success')
await loadList()
} catch (e: any) {
$baseMessage(e?.message || t('warehouse.sku.message.deleteFailed'), 'error')
}
},
})
}
function actionRenderer(row: any) {
const parts: string[] = []
if (hasPermission('Warehouse.Sku.Save')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="edit">${t('warehouse.common.edit')}</button>`)
}
if (hasPermission('Warehouse.Sku.Delete')) {
parts.push(`<button type="button" class="hot-action-btn" data-action="delete">${t('warehouse.common.delete')}</button>`)
}
return parts.join('')
}
function handleActionClick(row: any, _idx: number, action?: string) {
if (action === 'edit') handleEdit(row)
if (action === 'delete') handleDelete(row)
}
onMounted(loadList)
</script>
<template>
<div class="warehouse-sku-container">
<div class="page-card">
<div class="table-toolbar">
<div class="toolbar-left">
<a-space wrap :size="8">
<a-input
v-model="keyword"
allow-clear
:placeholder="t('warehouse.sku.search.keyword')"
style="width: 220px"
@press-enter="handleSearch"
/>
<a-button type="primary" @click="handleSearch">{{ t('warehouse.common.search') }}</a-button>
<a-button v-if="hasPermission('Warehouse.Sku.Save')" type="primary" @click="handleAdd">
{{ t('warehouse.common.add') }}
</a-button>
</a-space>
</div>
</div>
<div ref="tableContainerRef" class="list-wrap">
<HandsontablePro
:columns="hotColumns"
:data="tableRows"
:height="tableHeight"
:loading="listLoading"
show-action-column
:action-renderer="actionRenderer"
@action-click="handleActionClick"
/>
</div>
<PaginationPro
v-model:current="currentPage"
v-model:page-size="pageSize"
:total="totalCount"
@change="loadList"
@page-size-change="() => { currentPage = 1; loadList() }"
/>
</div>
<ModalPro v-model:visible="modalVisible" :title="formModel.id ? t('warehouse.sku.modal.edit') : t('warehouse.sku.modal.add')" :width="720" @cancel="closeModal">
<FormPro :model="formModel" layout="horizontal" :row-gutter="20" :default-span="12">
<a-form-item :label="t('warehouse.sku.form.skuCode')" field="skuCode" required>
<a-input v-model="formModel.skuCode" />
</a-form-item>
<a-form-item :label="t('warehouse.sku.form.skuName')" field="skuName" required>
<a-input v-model="formModel.skuName" />
</a-form-item>
<a-form-item :label="t('warehouse.sku.form.weightG')" field="weightG">
<a-input-number v-model="formModel.weightG" :min="0" style="width: 100%" />
</a-form-item>
<a-form-item :label="t('warehouse.sku.form.remark')" field="remark">
<a-textarea v-model="formModel.remark" :auto-size="{ minRows: 2, maxRows: 4 }" />
</a-form-item>
</FormPro>
<template #footer>
<a-button @click="closeModal">{{ t('warehouse.common.cancel') }}</a-button>
<a-button type="primary" :loading="saving" @click="handleSave">{{ t('warehouse.common.save') }}</a-button>
</template>
</ModalPro>
</div>
</template>
<style scoped lang="less">
.warehouse-sku-container {
padding: 16px;
background: #f0f3f4;
min-height: 100%;
display: flex;
flex-direction: column;
}
.page-card {
background: #fff;
padding: 16px;
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
border-radius: 4px;
}
.list-wrap {
flex: 1;
min-height: 0;
margin-top: 12px;
}
</style>

View File

@ -0,0 +1,109 @@
{
"default_max_attempts": 500,
"stagnant_limit": 20,
"min_scroll_delta": 10,
"max_click_per_round": 3,
"stagnant_check_threshold": 2,
"large_scroll_trigger": 5,
"button_click_interval": 3,
"final_sprint_push_count": 15,
"human_delay": {
"min_ms": 300,
"max_ms": 700
},
"reaction_time": {
"min_ms": 300,
"max_ms": 800
},
"hover_time": {
"min_ms": 100,
"max_ms": 300
},
"read_time": {
"min_ms": 500,
"max_ms": 1200
},
"short_read": {
"min_ms": 600,
"max_ms": 1200
},
"scroll_wait": {
"min_ms": 100,
"max_ms": 200
},
"post_scroll": {
"min_ms": 300,
"max_ms": 500
},
"navigation_delay": {
"min_ms": 1000,
"max_ms": 2500
},
"scroll_slow": {
"interval_base_ms": 1200,
"interval_jitter_ms": 300,
"scroll_ratio": 0.5
},
"scroll_normal": {
"interval_base_ms": 600,
"interval_jitter_ms": 200,
"scroll_ratio": 0.7
},
"scroll_fast": {
"interval_base_ms": 300,
"interval_jitter_ms": 100,
"scroll_ratio": 0.9
},
"home_feed_collect_time": {
"min": 90,
"max": 240
},
"search_feed_collect_time": {
"min": 60,
"max": 180
},
"home_browse_plan": {
"stable_sec_lo": 2.0,
"stable_sec_hi": 3.0,
"scroll_lo": 8,
"scroll_hi": 15,
"click_lo": 1,
"click_hi": 3,
"sprint_sec_lo": 4.0,
"sprint_sec_hi": 6.0,
"parse_sec_lo": 1.5,
"parse_sec_hi": 2.5,
"detail_stay_sec_lo": 10.0,
"detail_stay_sec_hi": 20.0,
"detail_scroll_lo": 3,
"detail_scroll_hi": 6
},
"search_browse_plan": {
"stable_sec_lo": 2.0,
"stable_sec_hi": 3.0,
"scroll_lo": 8,
"scroll_hi": 15,
"click_lo": 1,
"click_hi": 3,
"sprint_sec_lo": 4.0,
"sprint_sec_hi": 6.0,
"parse_sec_lo": 1.5,
"parse_sec_hi": 2.5,
"detail_stay_sec_lo": 10.0,
"detail_stay_sec_hi": 20.0,
"detail_scroll_lo": 3,
"detail_scroll_hi": 6
},
"inaccessible_keywords": [
"当前笔记暂时无法浏览",
"该内容因违规已被删除",
"该笔记已被删除",
"内容不存在",
"笔记不存在",
"已失效",
"私密笔记",
"仅作者可见",
"因用户设置,你无法查看",
"因违规无法查看"
]
}