chore: 清理归档文件和文档模板

删除不再需要的归档文件和过时的文档模板,包括多个README、安全策略、前端集成蓝图等文件,同时移除了未使用的业务文档和项目结构文件。

优化项目结构,移除冗余文件,保持代码库整洁。主要删除archive/handover目录下的多个文件及doc目录下的部分文档模板。
This commit is contained in:
2026-03-18 01:21:15 +08:00
parent 56b8a2e2f8
commit 72cd7f6f45
147 changed files with 5982 additions and 16716 deletions

View File

@@ -10,29 +10,214 @@
### 1.1 命名规范
- **表前缀**: `cf_` (crawlful)
- **字段命名**: snake_case
- **金額字段**: `decimal(10,2)` 或更高精度。
- **金額字段**: `decimal(10,2)` 或更高精度。**禁止**使用 float/double。
- **物理单位**: 长度 (cm), 重量 (kg), 体积 (m³)。
### 1.2 核心表定义
### 1.2 数据库安全约束
- **⚠️ 严禁**: 代码中执行 `DROP`, `TRUNCATE` 等破坏性操作
- **幂等性**: 所有建表语句必须使用 `db.schema.hasTable` 前置校验
- **JSON 处理**: images/skus/attributes 入库前序列化,出库解析
- **唯一约束**: `cf_product` 表必须保证 (platform, productId) 唯一
#### 租户与用户
- `cf_tenant`: 租户 ID、名称、配额、状态。
- `cf_user`: 邮箱、密码哈希、角色 (ADMIN/MANAGER 等)、租户 ID。
### 1.3 核心表定义
#### 店铺与商品
- `cf_shop`: 租户 ID、平台 (AMAZON/TIKTOK 等)、授权 Token。
- `cf_product`: 租户 ID、源平台 ID、标题、描述、JSON 图片列表。
- `cf_product_sku`: SKU 编码、属性 JSON、成本价、零售价、重量/尺寸。
#### 1.3.1 租户与用户
#### 订单与库存
- `cf_inventory`: SKU ID、仓库 ID、总数量、可用/预留数量。
- `cf_order`: 平台订单号、总金额、货币、利润/利润率、状态。
- `cf_order_item`: 订单项、SKU ID、单价、数量。
**cf_tenant** (租户表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 租户ID |
| name | string | 租户名称 |
| quota | json | 配额配置 |
| status | string | 状态 |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
#### 供应链与财务
- `cf_supplier`: 供应商名称、联系方式、评分、状态。
- `cf_purchase_order`: 采购单号、供应商 ID、总金额、状态。
- `cf_finance_reconciliation`: 对账周期、总销售/利润、差异状态。
**cf_user** (用户表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 用户ID |
| email | string | 邮箱 |
| password_hash | string | 密码哈希 |
| role | enum | ADMIN/MANAGER/OPERATOR/FINANCE/SOURCING/LOGISTICS/ANALYST |
| tenant_id | string(FK) | 租户ID |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
#### 1.3.2 店铺与商品
**cf_shop** (店铺表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 店铺ID |
| tenant_id | string(FK) | 租户ID |
| platform | enum | AMAZON/EBAY/SHOPEE/TIKTOK/TEMU/1688 |
| platform_shop_id | string | 平台店铺ID |
| name | string | 店铺名称 |
| auth_token | encrypted | 授权Token(加密存储) |
| status | string | 状态 |
| **trace_id** | string | 链路追踪ID |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
**cf_product** (商品主表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 商品ID |
| tenant_id | string(FK) | 租户ID |
| shop_id | string(FK) | 店铺ID |
| platform | enum | 平台类型 |
| platform_product_id | string | 平台商品ID |
| title | string | 商品标题 |
| description | text | 商品描述 |
| images | json | 图片列表(JSON数组) |
| category | string | 类目 |
| status | string | 状态 |
| **trace_id** | string | 链路追踪ID |
| **business_type** | enum | TOC/TOB |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
| **唯一约束**: (platform, platform_product_id) |
**cf_product_sku** (SKU变体表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | SKU ID |
| tenant_id | string(FK) | 租户ID |
| shop_id | string(FK) | 店铺ID |
| product_id | string(FK) | 商品ID |
| sku_code | string | SKU编码 |
| attributes | json | 属性JSON(颜色/尺寸等) |
| cost_price | decimal(10,2) | 成本价 |
| retail_price | decimal(10,2) | 零售价 |
| weight_kg | decimal(8,3) | 重量(kg) |
| length_cm | decimal(8,2) | 长度(cm) |
| width_cm | decimal(8,2) | 宽度(cm) |
| height_cm | decimal(8,2) | 高度(cm) |
| **trace_id** | string | 链路追踪ID |
| **business_type** | enum | TOC/TOB |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
#### 1.3.3 订单与库存
**cf_inventory** (库存表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 库存ID |
| tenant_id | string(FK) | 租户ID |
| shop_id | string(FK) | 店铺ID |
| sku_id | string(FK) | SKU ID |
| warehouse_id | string | 仓库ID |
| total_qty | int | 总数量 |
| available_qty | int | 可用数量 |
| reserved_qty | int | 预留数量 |
| **trace_id** | string | 链路追踪ID |
| **business_type** | enum | TOC/TOB |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
**cf_consumer_orders** (C端订单表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 订单ID |
| tenant_id | string(FK) | 租户ID |
| shop_id | string(FK) | 店铺ID |
| platform | enum | 平台类型 |
| platform_order_id | string | 平台订单号 |
| total_amount | decimal(10,2) | 总金额 |
| currency | string | 币种 |
| profit | decimal(10,2) | 利润 |
| profit_margin | decimal(5,2) | 利润率(%) |
| status | string | 订单状态 |
| **trace_id** | string | 链路追踪ID |
| **task_id** | string | 任务ID |
| **business_type** | enum | TOC/TOB |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
**cf_order_item** (订单项表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 订单项ID |
| order_id | string(FK) | 订单ID |
| sku_id | string(FK) | SKU ID |
| unit_price | decimal(10,2) | 单价 |
| quantity | int | 数量 |
| created_at | datetime | 创建时间 |
#### 1.3.4 供应链与财务
**cf_supplier** (供应商表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 供应商ID |
| tenant_id | string(FK) | 租户ID |
| name | string | 供应商名称 |
| contact | json | 联系方式 |
| rating | decimal(3,2) | 评分 |
| status | string | 状态 |
| **trace_id** | string | 链路追踪ID |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
**cf_purchase_order** (采购订单表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 采购单号 |
| tenant_id | string(FK) | 租户ID |
| supplier_id | string(FK) | 供应商ID |
| total_amount | decimal(10,2) | 总金额 |
| status | string | 状态 |
| **trace_id** | string | 链路追踪ID |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
**cf_finance_reconciliation** (财务对账表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 对账ID |
| tenant_id | string(FK) | 租户ID |
| shop_id | string(FK) | 店铺ID |
| period | string | 对账周期 |
| total_sales | decimal(12,2) | 总销售额 |
| total_profit | decimal(12,2) | 总利润 |
| variance_status | string | 差异状态 |
| **trace_id** | string | 链路追踪ID |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |
#### 1.3.5 审计日志
**cf_audit_log** (审计日志表)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string(PK) | 日志ID |
| tenant_id | string | 租户ID |
| shop_id | string | 店铺ID |
| task_id | string | 任务ID |
| trace_id | string | 链路追踪ID |
| business_type | enum | TOC/TOB |
| action | string | 操作类型 |
| entity_type | string | 实体类型 |
| entity_id | string | 实体ID |
| old_values | json | 旧值 |
| new_values | json | 新值 |
| user_id | string | 操作用户ID |
| ip_address | string | IP地址 |
| created_at | datetime | 创建时间 |
### 1.4 五元组追踪字段说明
所有业务表必须包含以下追踪字段:
| 字段 | 类型 | 说明 | 必填 |
|------|------|------|------|
| tenant_id | string | 租户ID - 业务隔离 | ✅ |
| shop_id | string | 店铺ID - 平台/店铺隔离 | ✅ (店铺相关表) |
| task_id | string | 任务ID - 任务追踪 | ✅ (异步任务) |
| trace_id | string | 链路追踪ID - 全链路唯一 | ✅ |
| business_type | enum | TOC/TOB | ✅ |
---

View File

@@ -0,0 +1,403 @@
# Finance API Specification
> **定位**:财务管理 API 规范 - 包含财务结算、税务、汇率对冲、利润对账等接口。
> **更新日期**: 2026-03-18
> **版本**: v1.0
> **最高优先级参考**: [Business_ClosedLoops.md](../../00_Business/Business_ClosedLoops.md)
---
## 1. 接口概览
| 方法 | 路径 | 功能 | 权限 |
|------|------|------|------|
| POST | `/api/v1/finance/orders/:id/record` | 记录订单财务 | finance:create |
| POST | `/api/v1/finance/transactions` | 记录交易流水 | finance:create |
| GET | `/api/v1/finance/reconciliation` | 执行利润对账 | finance:reconcile |
| GET | `/api/v1/finance/bills/:orderId` | 账单回放 | finance:read |
| GET | `/api/v1/finance/stats` | 财务统计 | finance:read |
| POST | `/api/v1/finance/hedge` | 汇率对冲 | finance:hedge |
| GET | `/api/v1/finance/tax/:orderId` | 税务信息 | finance:read |
---
## 2. 接口详情
### 2.1 记录订单财务 [BIZ_FIN_01]
**请求**
```http
POST /api/v1/finance/orders/:id/record
```
**请求体**
```json
{
"platform": "AMAZON",
"productId": "product-uuid",
"sellingPrice": 59.99,
"purchasePrice": 25.00,
"countryCode": "US",
"logisticsCost": 8.00,
"adBudget": 5.00,
"status": "COMPLETED"
}
```
**业务逻辑**
1. 插入订单主表 (`cf_orders`)
2. 实时税务计提 (`BIZ_FIN_02`)
3. 汇率自动对冲 (`BIZ_FIN_03`)
**响应**
```json
{
"success": true,
"data": {
"orderId": "order-uuid",
"taxAccrued": 5.40,
"hedgeApplied": true
}
}
```
---
### 2.2 记录交易流水 [BIZ_FIN_04]
**请求**
```http
POST /api/v1/finance/transactions
```
**请求体**
```json
{
"amount": 59.99,
"currency": "USD",
"type": "ORDER_REVENUE",
"category": "SALES",
"orderId": "order-uuid",
"metadata": {
"platform": "AMAZON",
"productId": "product-uuid"
}
}
```
**交易类型**
| 类型 | 说明 |
|------|------|
| ORDER_REVENUE | 订单收入 |
| LOGISTICS_COST | 物流成本 |
| PLATFORM_FEE | 平台费用 |
| REFUND | 退款 |
| COMMISSION | 佣金 |
| INCOME | 其他收入 |
**响应**
```json
{
"success": true,
"data": {
"transactionId": 12345,
"recordedAt": "2026-03-18T10:00:00Z"
}
}
```
---
### 2.3 执行利润对账 [BIZ_FIN_06]
**请求**
```http
GET /api/v1/finance/reconciliation?shopId=shop-uuid
```
**查询参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| shopId | string | 是 | 店铺ID |
**业务逻辑**
1. 获取所有已完成且未对账的订单
2. 聚合各项成本(采购、物流、税务)
3. 计算净利润
4. 更新对账状态
**响应**
```json
{
"success": true,
"data": {
"totalReconciled": 50,
"details": [
{
"orderId": "order-1",
"sellingPrice": 59.99,
"purchaseCost": 25.00,
"logisticsCost": 8.00,
"taxAmount": 5.40,
"netProfit": 21.59,
"profitMargin": 36.0
}
]
}
}
```
---
### 2.4 账单回放
**请求**
```http
GET /api/v1/finance/bills/:orderId
```
**响应**
```json
{
"success": true,
"data": {
"orderId": "order-uuid",
"timeline": [
{
"event": "ORDER_CREATED",
"time": "2026-03-18T10:00:00Z",
"amount": 59.99,
"description": "订单创建"
},
{
"event": "PURCHASE_COMPLETED",
"time": "2026-03-18T11:00:00Z",
"amount": -25.00,
"description": "采购完成"
},
{
"event": "LOGISTICS_DEDUCTED",
"time": "2026-03-18T12:00:00Z",
"amount": -8.00,
"description": "物流扣款"
},
{
"event": "TAX_ACCRUED",
"time": "2026-03-18T12:00:00Z",
"amount": -5.40,
"description": "税务计提"
}
],
"finalProfit": 21.59,
"profitMargin": 36.0
}
}
```
---
### 2.5 财务统计
**请求**
```http
GET /api/v1/finance/stats?startDate=2026-03-01&endDate=2026-03-31
```
**查询参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| startDate | string | 否 | 开始日期 |
| endDate | string | 否 | 结束日期 |
| shopId | string | 否 | 店铺筛选 |
**响应**
```json
{
"success": true,
"data": {
"period": "2026-03-01 ~ 2026-03-31",
"totalRevenue": 59980.00,
"totalCost": 35988.00,
"totalProfit": 23992.00,
"averageMargin": 40.0,
"byType": {
"ORDER_REVENUE": 59980.00,
"LOGISTICS_COST": -8000.00,
"PLATFORM_FEE": -3998.00,
"TAX": -5400.00,
"PURCHASE": -25000.00
},
"byPlatform": {
"AMAZON": { "revenue": 29990.00, "profit": 11996.00 },
"SHOPIFY": { "revenue": 19993.00, "profit": 7997.00 },
"TIKTOK": { "revenue": 9997.00, "profit": 3999.00 }
}
}
}
```
---
### 2.6 汇率对冲 [BIZ_FIN_03]
**请求**
```http
POST /api/v1/finance/hedge
```
**请求体**
```json
{
"pair": "USD/CNY",
"amount": 59980.00,
"strategy": "AUTO"
}
```
**响应**
```json
{
"success": true,
"data": {
"hedgeId": "hedge-uuid",
"pair": "USD/CNY",
"amount": 59980.00,
"rate": 7.25,
"hedgedAmount": 434855.00,
"status": "EXECUTED"
}
}
```
---
### 2.7 税务信息 [BIZ_FIN_02]
**请求**
```http
GET /api/v1/finance/tax/:orderId
```
**响应**
```json
{
"success": true,
"data": {
"orderId": "order-uuid",
"countryCode": "US",
"baseAmount": 59.99,
"taxRate": 9.0,
"totalTax": 5.40,
"isIOSS": false,
"taxType": "STANDARD_VAT",
"status": "ACCRUED",
"accruedAt": "2026-03-18T10:00:00Z"
}
}
```
---
## 3. 数据模型
### 3.1 OrderRecord (订单财务记录)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string | 主键 |
| tenantId | string | 租户ID |
| shopId | string | 店铺ID |
| taskId | string | 任务ID |
| traceId | string | 追踪ID |
| platform | string | 平台 |
| productId | string | 商品ID |
| sellingPrice | number | 售价 |
| purchasePrice | number | 采购价 |
| countryCode | string | 国家代码 |
| logisticsCost | number | 物流成本 |
| adBudget | number | 广告预算 |
| status | string | 状态 |
| netProfit | number | 净利润 |
| reconciledAt | string | 对账时间 |
### 3.2 Transaction (交易流水)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | number | 自增ID |
| tenantId | string | 租户ID |
| orderId | string | 订单ID |
| amount | decimal(10,2) | 金额 |
| currency | string | 币种 |
| transactionType | string | 交易类型 |
| traceId | string | 追踪ID |
| metadata | object | 元数据 |
| createdAt | string | 创建时间 |
### 3.3 TaxAccrual (税务计提)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | number | 自增ID |
| orderId | string | 订单ID |
| tenantId | string | 租户ID |
| amount | decimal(10,2) | 税额 |
| currency | string | 币种 |
| taxType | string | 税务类型 |
| status | string | 状态 |
| traceId | string | 追踪ID |
| createdAt | string | 创建时间 |
| updatedAt | string | 更新时间 |
---
## 4. 利润计算公式
### 4.1 净利润
```
净利润 = 售价 - 采购成本 - 物流成本 - 税费 - 平台费用 - 广告费用
```
### 4.2 利润率
```
利润率 = (净利润 / 售价) × 100%
```
### 4.3 利润红线
| 模式 | 红线 | 处理 |
|------|------|------|
| B2B | < 15% | 禁止报价 |
| B2C | < 20% | 触发风控预警 |
---
## 5. 错误码
| 错误码 | 说明 | HTTP状态 |
|--------|------|----------|
| ORDER_NOT_FOUND | 订单不存在 | 404 |
| INSUFFICIENT_FUNDS | 资金不足 | 400 |
| INVALID_CURRENCY | 无效币种 | 400 |
| HEDGE_FAILED | 对冲失败 | 500 |
| RECONCILIATION_FAILED | 对账失败 | 500 |
| UNAUTHORIZED | 未授权 | 401 |
| FORBIDDEN | 无权限 | 403 |
---
## 6. 相关文档
- [Backend Design](../Backend_Design.md)
- [Product API](./Product_API.md)
- [Order API](./Order_API.md)
- [Business ClosedLoops](../../00_Business/Business_ClosedLoops.md) - 财务结算闭环
---
*本文档基于代码自动生成,最后更新: 2026-03-18*

View File

@@ -0,0 +1,521 @@
# Order API Specification
> **定位**:订单管理 API 规范 - 包含订单 CRUD、Webhook、批量操作、状态流转等接口。
> **更新日期**: 2026-03-18
> **版本**: v1.0
> **最高优先级参考**: [Business_ClosedLoops.md](../../00_Business/Business_ClosedLoops.md)
---
## 1. 接口概览
| 方法 | 路径 | 功能 | 权限 |
|------|------|------|------|
| POST | `/api/v1/orders/webhook/:platform` | 平台 Webhook 接收 | public |
| GET | `/api/v1/orders` | 获取订单列表 | order:read |
| GET | `/api/v1/orders/:id` | 获取订单详情 | order:read |
| POST | `/api/v1/orders` | 创建订单 | order:create |
| PUT | `/api/v1/orders/:id` | 更新订单 | order:update |
| DELETE | `/api/v1/orders/:id` | 删除订单 | order:delete |
| POST | `/api/v1/orders/sync` | 手动触发同步 | order:sync |
| GET | `/api/v1/orders/stats` | 订单统计 | order:read |
| PUT | `/api/v1/orders/batch` | 批量更新 | order:update |
| POST | `/api/v1/orders/:id/status` | 状态流转 | order:update |
| POST | `/api/v1/orders/batch/audit` | 批量审核 | order:audit |
---
## 2. 接口详情
### 2.1 平台 Webhook 接收 [BIZ_OPS_01]
**请求**
```http
POST /api/v1/orders/webhook/:platform
```
**路径参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| platform | string | 是 | 平台 (SHOPIFY, AMAZON, TIKTOK, ALIEXPRESS) |
**请求头**
```
X-Tenant-Id: {tenantId}
X-Shop-Id: {shopId}
```
**请求体 (Shopify 示例)**
```json
{
"id": "1234567890",
"name": "#1001",
"customer": {
"first_name": "John",
"last_name": "Doe",
"email": "john@example.com"
},
"line_items": [
{
"sku": "SKU001",
"title": "Product Name",
"price": "29.99",
"quantity": 2
}
],
"total_price": "59.98",
"currency": "USD",
"financial_status": "paid",
"fulfillment_status": null
}
```
**响应**
```json
{
"success": true,
"orderId": "internal-order-id"
}
```
**支持平台**
- Shopify
- Amazon
- TikTok Shop
- AliExpress
---
### 2.2 获取订单列表
**请求**
```http
GET /api/v1/orders?status=PAID&platform=AMAZON&page=1&pageSize=20
```
**查询参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| status | string | 否 | 状态筛选 |
| platform | string | 否 | 平台筛选 |
| startDate | string | 否 | 开始日期 (ISO 8601) |
| endDate | string | 否 | 结束日期 (ISO 8601) |
| page | number | 否 | 页码,默认 1 |
| pageSize | number | 否 | 每页数量,默认 20 |
**响应**
```json
{
"success": true,
"data": {
"items": [
{
"id": "order-uuid",
"platform": "AMAZON",
"platformOrderId": "123-4567890-1234567",
"customerName": "John Doe",
"customerEmail": "john@example.com",
"status": "PAID",
"paymentStatus": "COMPLETED",
"fulfillmentStatus": "PENDING",
"totalAmount": 59.98,
"currency": "USD",
"items": [
{
"skuId": "SKU001",
"title": "Product Name",
"price": 29.99,
"quantity": 2
}
],
"createdAt": "2026-03-18T10:00:00Z"
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 100
}
}
}
```
---
### 2.3 获取订单详情
**请求**
```http
GET /api/v1/orders/:id
```
**响应**
```json
{
"success": true,
"data": {
"id": "order-uuid",
"platform": "AMAZON",
"platformOrderId": "123-4567890-1234567",
"tenantId": "tenant-uuid",
"shopId": "shop-uuid",
"customerName": "John Doe",
"customerEmail": "john@example.com",
"shippingAddress": {
"name": "John Doe",
"address1": "123 Main St",
"city": "New York",
"province": "NY",
"country": "US",
"zip": "10001"
},
"items": [
{
"skuId": "SKU001",
"title": "Product Name",
"price": 29.99,
"quantity": 2,
"costPrice": 15.00
}
],
"totalAmount": 59.98,
"currency": "USD",
"status": "PAID",
"paymentStatus": "COMPLETED",
"fulfillmentStatus": "PENDING",
"profit": 29.98,
"profitMargin": 50.0,
"traceId": "trace-uuid",
"createdAt": "2026-03-18T10:00:00Z",
"updatedAt": "2026-03-18T10:00:00Z"
}
}
```
---
### 2.4 创建订单
**请求**
```http
POST /api/v1/orders
```
**请求体**
```json
{
"platform": "MANUAL",
"customerName": "John Doe",
"customerEmail": "john@example.com",
"shippingAddress": {
"name": "John Doe",
"address1": "123 Main St",
"city": "New York",
"province": "NY",
"country": "US",
"zip": "10001"
},
"items": [
{
"skuId": "SKU001",
"title": "Product Name",
"price": 29.99,
"quantity": 2
}
],
"totalAmount": 59.98,
"currency": "USD"
}
```
**响应**
```json
{
"success": true,
"orderId": "order-uuid"
}
```
---
### 2.5 更新订单
**请求**
```http
PUT /api/v1/orders/:id
```
**请求体**
```json
{
"status": "SHIPPED",
"fulfillmentStatus": "SHIPPED",
"trackingNumber": "1Z999AA1234567890"
}
```
**响应**
```json
{
"success": true,
"message": "Order updated successfully"
}
```
---
### 2.6 删除订单
**请求**
```http
DELETE /api/v1/orders/:id
```
**响应**
```json
{
"success": true,
"message": "Order deleted successfully"
}
```
---
### 2.7 手动触发同步
**请求**
```http
POST /api/v1/orders/sync
```
**请求体**
```json
{
"platform": "AMAZON",
"shopId": "shop-uuid"
}
```
**响应**
```json
{
"success": true,
"message": "Manual sync triggered for AMAZON"
}
```
---
### 2.8 订单统计
**请求**
```http
GET /api/v1/orders/stats
```
**响应**
```json
{
"success": true,
"data": {
"totalOrders": 1000,
"totalRevenue": 59980.00,
"totalProfit": 29990.00,
"averageOrderValue": 59.98,
"byStatus": {
"PAID": 500,
"SHIPPED": 300,
"DELIVERED": 200
},
"byPlatform": {
"AMAZON": 400,
"SHOPIFY": 300,
"TIKTOK": 300
}
}
}
```
---
### 2.9 批量更新
**请求**
```http
PUT /api/v1/orders/batch
```
**请求体**
```json
{
"orderIds": ["order-1", "order-2", "order-3"],
"updates": {
"status": "SHIPPED",
"fulfillmentStatus": "SHIPPED"
}
}
```
**响应**
```json
{
"success": true,
"data": {
"updated": 3,
"failed": 0
}
}
```
---
### 2.10 状态流转
**请求**
```http
POST /api/v1/orders/:id/status
```
**请求体**
```json
{
"status": "SHIPPED",
"reason": "Order shipped via UPS"
}
```
**状态机**
```
PULLED → PENDING_REVIEW → CONFIRMED → ALLOCATED → READY_TO_SHIP → SHIPPED → DELIVERED → CLOSED
```
**响应**
```json
{
"success": true,
"message": "Order status updated to SHIPPED"
}
```
---
### 2.11 批量审核
**请求**
```http
POST /api/v1/orders/batch/audit
```
**请求体**
```json
{
"orderIds": ["order-1", "order-2", "order-3"]
}
```
**响应**
```json
{
"success": true,
"data": {
"approved": 3,
"rejected": 0
}
}
```
---
## 3. 数据模型
### 3.1 Order (订单)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | string | 主键 (UUID) |
| tenantId | string | 租户ID |
| shopId | string | 店铺ID |
| platform | string | 平台 |
| platformOrderId | string | 平台订单ID |
| customerName | string | 客户姓名 |
| customerEmail | string | 客户邮箱 |
| shippingAddress | object | 配送地址 |
| items | OrderItem[] | 订单项 |
| totalAmount | decimal(10,2) | 订单金额 |
| currency | string | 币种 |
| status | string | 订单状态 |
| paymentStatus | string | 支付状态 |
| fulfillmentStatus | string | 履约状态 |
| profit | number | 利润 |
| profitMargin | number | 利润率 |
| traceId | string | 追踪ID |
| createdAt | string | 创建时间 |
| updatedAt | string | 更新时间 |
### 3.2 OrderItem (订单项)
| 字段 | 类型 | 说明 |
|------|------|------|
| skuId | string | SKU ID |
| title | string | 商品标题 |
| price | number | 单价 |
| quantity | number | 数量 |
| costPrice | number | 成本价 |
### 3.3 状态枚举
```typescript
enum OrderStatus {
PULLED = 'PULLED', // 已拉取
PENDING_REVIEW = 'PENDING_REVIEW', // 待审核
CONFIRMED = 'CONFIRMED', // 已确认
ALLOCATED = 'ALLOCATED', // 已分配
READY_TO_SHIP = 'READY_TO_SHIP', // 待发货
SHIPPED = 'SHIPPED', // 已发货
DELIVERED = 'DELIVERED', // 已送达
CLOSED = 'CLOSED' // 已关闭
}
enum PaymentStatus {
PENDING = 'PENDING',
COMPLETED = 'COMPLETED',
FAILED = 'FAILED',
REFUNDED = 'REFUNDED'
}
enum FulfillmentStatus {
PENDING = 'PENDING',
PROCESSING = 'PROCESSING',
SHIPPED = 'SHIPPED',
DELIVERED = 'DELIVERED'
}
```
---
## 4. 错误码
| 错误码 | 说明 | HTTP状态 |
|--------|------|----------|
| ORDER_NOT_FOUND | 订单不存在 | 404 |
| INVALID_STATUS_TRANSITION | 非法状态流转 | 400 |
| PLATFORM_NOT_SUPPORTED | 不支持的平台 | 400 |
| UNAUTHORIZED | 未授权 | 401 |
| FORBIDDEN | 无权限 | 403 |
| VALIDATION_ERROR | 参数校验失败 | 400 |
| INTERNAL_ERROR | 内部错误 | 500 |
---
## 5. 相关文档
- [Backend Design](../Backend_Design.md)
- [Product API](./Product_API.md)
- [Finance API](./Finance_API.md)
- [Business ClosedLoops](../../00_Business/Business_ClosedLoops.md) - 订单履约闭环
---
*本文档基于代码自动生成,最后更新: 2026-03-18*

View File

@@ -0,0 +1,399 @@
# Product API Specification
> **定位**:商品管理 API 规范 - 包含商品 CRUD、采集、定价、审核等接口。
> **更新日期**: 2026-03-18
> **版本**: v1.0
---
## 1. 接口概览
| 方法 | 路径 | 功能 | 权限 |
|------|------|------|------|
| GET | `/api/v1/products` | 获取商品列表 | product:read |
| GET | `/api/v1/products/:id` | 获取商品详情 | product:read |
| POST | `/api/v1/products` | 创建商品 | product:create |
| PUT | `/api/v1/products/:id` | 更新商品 | product:update |
| DELETE | `/api/v1/products/:id` | 删除商品 | product:delete |
| POST | `/api/v1/products/:id/approve` | 审核商品 | product:review |
| POST | `/api/v1/products/collect` | 采集商品 | product:create |
| POST | `/api/v1/products/:id/pricing` | 动态调价 | product:update |
| POST | `/api/v1/products/autonomous-listing` | 自治上架 | product:create |
---
## 2. 接口详情
### 2.1 获取商品列表
**请求**
```http
GET /api/v1/products?platform=AMAZON&status=ACTIVE&page=1&limit=20
```
**请求头**
```
Authorization: Bearer {token}
X-Tenant-Id: {tenantId}
X-Trace-Id: {traceId}
```
**查询参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| platform | string | 否 | 平台筛选 (AMAZON, EBAY, SHOPIFY, etc.) |
| status | string | 否 | 状态筛选 (DRAFTED, PENDING_REVIEW, APPROVED, etc.) |
| page | number | 否 | 页码,默认 1 |
| limit | number | 否 | 每页数量,默认 20 |
**响应**
```json
{
"success": true,
"data": {
"items": [
{
"id": 1,
"title": "Product Name",
"platform": "AMAZON",
"platformProductId": "B08N5WRWNW",
"status": "APPROVED",
"sellingPrice": 29.99,
"purchasePrice": 15.00,
"stock": 100,
"createdAt": "2026-03-18T10:00:00Z",
"updatedAt": "2026-03-18T10:00:00Z"
}
],
"pagination": {
"page": 1,
"limit": 20,
"total": 100,
"totalPages": 5
}
}
}
```
---
### 2.2 获取商品详情
**请求**
```http
GET /api/v1/products/:id
```
**响应**
```json
{
"success": true,
"data": {
"id": 1,
"title": "Product Name",
"description": "Product description...",
"platform": "AMAZON",
"platformProductId": "B08N5WRWNW",
"status": "APPROVED",
"sellingPrice": 29.99,
"purchasePrice": 15.00,
"currency": "USD",
"stock": 100,
"images": ["url1", "url2"],
"attributes": {
"color": "black",
"size": "M"
},
"profitMargin": 45.5,
"roi": 99.9,
"createdAt": "2026-03-18T10:00:00Z",
"updatedAt": "2026-03-18T10:00:00Z"
}
}
```
---
### 2.3 创建商品
**请求**
```http
POST /api/v1/products
```
**请求体**
```json
{
"title": "Product Name",
"description": "Product description",
"platform": "AMAZON",
"platformProductId": "B08N5WRWNW",
"sellingPrice": 29.99,
"purchasePrice": 15.00,
"currency": "USD",
"stock": 100,
"images": ["url1", "url2"],
"attributes": {
"color": "black",
"size": "M"
},
"category": "Electronics",
"tags": ["new", "hot"]
}
```
**响应**
```json
{
"success": true,
"data": {
"id": 1,
"message": "Product created successfully"
}
}
```
---
### 2.4 更新商品
**请求**
```http
PUT /api/v1/products/:id
```
**请求体**
```json
{
"title": "Updated Product Name",
"sellingPrice": 34.99,
"stock": 150,
"status": "PENDING_REVIEW"
}
```
**状态机校验**
- 商品状态流转必须符合预定义状态机
- 非法状态流转返回 400 错误
**响应**
```json
{
"success": true,
"data": {
"id": 1,
"title": "Updated Product Name",
"status": "PENDING_REVIEW",
"updatedAt": "2026-03-18T11:00:00Z"
}
}
```
---
### 2.5 删除商品
**请求**
```http
DELETE /api/v1/products/:id
```
**响应**
```json
{
"success": true,
"message": "Product deleted successfully"
}
```
---
### 2.6 审核商品 [UX_REVIEW_01]
**请求**
```http
POST /api/v1/products/:id/approve
```
**请求体**
```json
{
"decision": "APPROVE",
"reason": "符合上架标准"
}
```
**参数说明**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| decision | string | 是 | APPROVE 或 REJECT |
| reason | string | 否 | 审核意见 |
**响应**
```json
{
"success": true,
"message": "Product approved successfully"
}
```
---
### 2.7 采集商品 [CORE_WORK_01]
**请求**
```http
POST /api/v1/products/collect
```
**请求体**
```json
{
"url": "https://www.1688.com/product/123456.html",
"sandbox": false
}
```
**参数说明**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| url | string | 是 | 商品链接 |
| sandbox | boolean | 否 | 是否使用沙箱模式 |
**响应**
```json
{
"success": true,
"data": {
"jobId": "job-uuid",
"status": "PENDING",
"message": "Crawl job submitted successfully"
}
}
```
---
### 2.8 动态调价 [BIZ_MKT_30]
**请求**
```http
POST /api/v1/products/:id/pricing
```
**响应**
```json
{
"success": true,
"data": {
"productId": 1,
"oldPrice": 29.99,
"newPrice": 32.99,
"reason": "Competitor price increased",
"profitMargin": 48.5,
"updatedAt": "2026-03-18T12:00:00Z"
}
}
```
---
### 2.9 自治上架 [CORE_AUTO_01]
**请求**
```http
POST /api/v1/products/autonomous-listing
```
**请求体**
```json
{
"url": "https://www.1688.com/product/123456.html",
"targetPlatforms": ["AMAZON", "EBAY"]
}
```
**响应**
```json
{
"success": true,
"data": {
"instanceId": "pipeline-uuid",
"status": "RUNNING",
"steps": [
{ "id": "crawl", "status": "PENDING" },
{ "id": "optimize", "status": "PENDING" },
{ "id": "publish", "status": "PENDING" }
]
}
}
```
---
## 3. 数据模型
### 3.1 Product (商品)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | number | 主键 |
| tenantId | string | 租户ID |
| title | string | 商品标题 |
| description | string | 商品描述 |
| platform | string | 平台 (AMAZON, EBAY, etc.) |
| platformProductId | string | 平台商品ID |
| status | string | 状态 |
| sellingPrice | number | 售价 |
| purchasePrice | number | 采购价 |
| currency | string | 币种 |
| stock | number | 库存 |
| images | string[] | 图片URL列表 |
| attributes | object | 属性 |
| category | string | 类目 |
| tags | string[] | 标签 |
| profitMargin | number | 利润率 |
| roi | number | ROI |
| createdAt | string | 创建时间 |
| updatedAt | string | 更新时间 |
### 3.2 状态枚举
```typescript
enum ProductStatus {
DRAFTED = 'DRAFTED', // 草稿
PENDING_REVIEW = 'PENDING_REVIEW', // 待审核
APPROVED = 'APPROVED', // 已通过
REJECTED = 'REJECTED', // 已拒绝
LISTED = 'LISTED', // 已上架
DELISTED = 'DELISTED' // 已下架
}
```
---
## 4. 错误码
| 错误码 | 说明 | HTTP状态 |
|--------|------|----------|
| PRODUCT_NOT_FOUND | 商品不存在 | 404 |
| INVALID_STATUS_TRANSITION | 非法状态流转 | 400 |
| UNAUTHORIZED | 未授权 | 401 |
| FORBIDDEN | 无权限 | 403 |
| VALIDATION_ERROR | 参数校验失败 | 400 |
| INTERNAL_ERROR | 内部错误 | 500 |
---
## 5. 相关服务
- [Backend Design](../Backend_Design.md)
- [Order API](./Order_API.md)
- [Finance API](./Finance_API.md)
---
*本文档基于代码自动生成,最后更新: 2026-03-18*

View File

@@ -0,0 +1,349 @@
# Backend Design (Crawlful Hub)
> **定位**Crawlful Hub 后端架构设计文档 - 包含技术栈、目录结构、核心服务及依赖规则。
> **更新日期**: 2026-03-18
---
## 1. 技术栈 (Tech Stack)
| 层级 | 技术 | 版本 | 用途 |
|------|------|------|------|
| **Runtime** | Node.js | 20+ | 运行时环境 |
| **Language** | TypeScript | 5.x | 开发语言 (strict: true) |
| **Framework** | Express.js | 4.x | Web 框架 |
| **Database** | MySQL | 8.0 | 主数据库 (cf_ 前缀) |
| **ORM** | Knex.js | 3.x | SQL 构建器 |
| **Cache** | Redis | 6.0 | 缓存 & 队列 |
| **Queue** | BullMQ | 5.x | 异步任务队列 |
| **Testing** | Jest | 29.x | 单元测试 |
---
## 2. 目录结构 (Directory Structure)
```
server/src/
├─ api/ # API 层
│ ├─ controllers/ # 控制器 (HTTP 请求处理)
│ │ ├─ ProductController.ts
│ │ ├─ OrderController.ts
│ │ ├─ AuthController.ts
│ │ └─ ...
│ ├─ middlewares/ # 中间件
│ │ ├─ auth.middleware.ts
│ │ ├─ tenant.middleware.ts
│ │ └─ trace.middleware.ts
│ └─ routes/ # 路由定义
│ ├─ product.routes.ts
│ ├─ order.routes.ts
│ └─ ...
├─ services/ # 服务层 (业务逻辑)
│ ├─ ProductService.ts # 商品服务
│ ├─ OrderService.ts # 订单服务
│ ├─ FinanceService.ts # 财务服务
│ ├─ InventoryService.ts # 库存服务
│ ├─ AuthService.ts # 认证服务
│ └─ ... (200+ 服务类)
├─ domains/ # 领域层 (按业务域组织)
│ ├─ Trade/ # 交易域
│ │ ├─ ConsumerOrderService.ts
│ │ ├─ TradeService.ts
│ │ └─ ...
│ ├─ Analytics/ # 分析域
│ │ ├─ ReportService.ts
│ │ ├─ AnalyticsService.ts
│ │ └─ ...
│ └─ Tenant/ # 租户域
│ ├─ TenantService.ts
│ └─ ...
├─ models/ # 数据模型
│ ├─ Product.ts
│ ├─ User.ts
│ ├─ Order.ts
│ └─ ...
├─ core/ # 核心基础设施
│ ├─ ai/ # AI 引擎
│ │ └─ FingerprintEngine.ts
│ ├─ pipeline/ # 流水线引擎
│ │ ├─ PipelineEngine.ts
│ │ └─ PipelineTypes.ts
│ ├─ telemetry/ # 遥测服务
│ │ ├─ GlobalTracingService.ts
│ │ ├─ PredictiveHealthService.ts
│ │ └─ ...
│ └─ workers/ # Worker 管理
│ └─ WorkerHub.ts
├─ workers/ # 任务 Worker
│ ├─ PlatformSyncWorker.ts # 平台API数据同步有API平台
│ └─ WorkerHub.ts
├─ shared/ # 共享资源
│ ├─ types/ # 类型定义
│ │ ├─ contracts/
│ │ └─ ...
│ └─ contracts/ # 接口契约
│ └─ business-contracts.ts
├─ utils/ # 工具函数
│ ├─ logger.ts
│ ├─ RedisService.ts
│ └─ SignatureUtils.ts
├─ config/ # 配置文件
│ └─ database.ts
└─ plugins/ # 插件
└─ RedisQuota.plugin.ts
```
---
## 3. 分层架构 (Layered Architecture)
### 3.1 依赖规则
```
API (Controllers)
↓ (调用)
Services (业务逻辑)
↓ (调用)
Domains (领域服务)
↓ (调用)
Models / Repository (数据访问)
```
### 3.2 允许的依赖
| 从 | 到 | 说明 |
|----|----|----|
| `api/controllers` | `services` | Controller 调用 Service |
| `services` | `domains` | Service 调用 Domain |
| `services` | `models` | Service 直接操作 Model |
| `domains` | `services` | Domain 可调用 Service |
| `domains` | `models` | Domain 直接操作 Model |
| `core` | `services` | 核心可调用 Service |
| `workers` | `services` | Worker 调用 Service |
### 3.3 禁止的依赖
| 从 | 到 | 原因 |
|----|----|----|
| `api/controllers` | `models` | 禁止跨层访问 |
| `models` | `services` | 下层不能依赖上层 |
| `services` | `api` | 业务层不应感知 HTTP |
---
## 4. 核心服务清单 (Core Services)
### 4.1 商品管理 (PIM)
| 服务 | 文件 | 功能 |
|------|------|------|
| ProductService | `services/ProductService.ts` | 商品 CRUD |
| PlatformApiService | `services/PlatformApiService.ts` | 平台API对接有API平台 |
| DynamicPricingService | `services/DynamicPricingService.ts` | 动态定价 |
| ArbitrageService | `services/ArbitrageService.ts` | 套利分析 |
| VisualSourcingService | `services/VisualSourcingService.ts` | 视觉寻源 |
### 4.2 订单管理 (OMS)
| 服务 | 文件 | 功能 |
|------|------|------|
| OrderService | `services/OrderService.ts` | 订单管理 |
| ConsumerOrderService | `domains/Trade/ConsumerOrderService.ts` | TOC 订单流 |
| PaymentService | `services/PaymentService.ts` | 支付处理 |
| AuditService | `services/AuditService.ts` | 审计日志 |
### 4.3 财务管理 (FIN)
| 服务 | 文件 | 功能 |
|------|------|------|
| FinanceService | `services/FinanceService.ts` | 财务结算 |
| TaxService | `services/TaxService.ts` | 税务计算 |
| FXHedgingService | `services/FXHedgingService.ts` | 汇率对冲 |
| MultiCurrencyFinanceService | `services/MultiCurrencyFinanceService.ts` | 多币种财务 |
### 4.4 库存管理 (WMS)
| 服务 | 文件 | 功能 |
|------|------|------|
| InventoryService | `services/InventoryService.ts` | 库存管理 |
| InventoryForecastService | `services/InventoryForecastService.ts` | 库存预测 |
| WarehouseService | `services/WarehouseService.ts` | 仓库管理 |
| InventoryAgingService | `services/InventoryAgingService.ts` | 库存老化分析 |
### 4.5 营销广告 (MKT)
| 服务 | 文件 | 功能 |
|------|------|------|
| MarketingService | `services/MarketingService.ts` | 营销管理 |
| AdAutoService | `services/AdAutoService.ts` | 广告自动化 |
| CompetitorService | `services/CompetitorService.ts` | 竞品监控 |
| PlatformFeeWatcher | `services/PlatformFeeWatcher.ts` | 平台费用监控 |
### 4.6 AI 服务
| 服务 | 文件 | 功能 |
|------|------|------|
| AIService | `services/AIService.ts` | AI 核心服务 |
| AgentSwarmService | `services/AgentSwarmService.ts` | 多 AI 协作 |
| AdviceService | `domains/Strategy/AdviceService.ts` | 策略建议 |
### 4.7 供应链 (SCM)
| 服务 | 文件 | 功能 |
|------|------|------|
| SupplyChainService | `services/SupplyChainService.ts` | 供应链管理 |
| SupplierService | `services/SupplierService.ts` | 供应商管理 |
| LogisticsIntelligenceService | `services/LogisticsIntelligenceService.ts` | 物流智能 |
---
## 5. 基础设施 (Infrastructure)
### 5.1 数据库 (MySQL)
- **表前缀**: `cf_` (如 `cf_product`, `cf_order`)
- **ORM**: Knex.js
- **连接池**: 默认配置
- **迁移**: 代码中自动建表 (`db.schema.hasTable` 前置校验)
### 5.2 缓存 (Redis)
- **用途**: 缓存、会话、速率限制
- **端口**: 6379
- **服务类**: `RedisService.ts`
### 5.3 队列 (BullMQ)
- **用途**: 异步任务处理
- **Worker**: `PlatformSyncWorker.ts` (有API平台同步), `WorkerHub.ts`
- **并发限制**: ≤ 10
### 5.4 资源限制
- **内存**: Node.js 进程限制 `--max-old-space-size=4096` (4GB)
- **图片处理**: Sharp 必须开启 `sequentialRead`
- **API 速率**: 基于 Redis 的速率限制
### 5.4 遥测 (Telemetry)
- **全局追踪**: `GlobalTracingService`
- **健康预测**: `PredictiveHealthService`
- **网络拓扑**: `NetworkTopologyService`
---
## 6. 安全与权限
### 6.1 认证 (Auth)
- **服务**: `AuthService.ts`
- **方式**: JWT + OAuth2 + MFA
- **中间件**: `auth.middleware.ts`
### 6.2 权限 (RBAC)
- **角色**: ADMIN, MANAGER, OPERATOR, FINANCE, SOURCING, LOGISTICS, ANALYST
- **中间件**: `authorize(permission)`
- **数据隔离**:
- `tenantId`: 租户隔离
- `parentId`: 层级过滤(非 ADMIN 用户必须)
- **⚠️ 禁止**: Controller 中硬编码 `role === 'ADMIN'`
### 6.3 审计 (Audit)
- **服务**: `AuditService.ts`
- **五元组**: `tenantId/shopId/taskId/traceId/businessType`
- **日志**: 所有操作记录到 `cf_audit_logs`
---
## 7. 开发规范
### 7.1 命名规范
- **服务类**: `XxxService` 后缀。**禁止**使用 `Manager`/`Helper` 等后缀
- **控制器**: `XxxController` 后缀
- **模型**: 大驼峰,单数形式
- **文件**: 大驼峰 (PascalCase)
### 7.2 注释规范
```typescript
/**
* [TASK_ID] 服务名称
* @description 功能描述
* @version 1.0
*/
export class XxxService { ... }
```
### 7.3 错误处理
- 使用 try-catch 包裹异步操作
- 返回标准错误格式: `{ success: false, error: string }`
- 记录错误日志
---
## 8. 测试
### 8.1 测试结构
```
services/__tests__/
├─ EventBusService.test.ts
├─ PaymentService.test.ts
├─ OrderService.test.ts
└─ ...
```
### 8.2 测试命令
```bash
npm test # 运行所有测试
npm test -- --watch # 监听模式
```
---
## 9. 部署
### 9.1 环境变量
```env
DATABASE_URL=mysql://user:pass@host:3306/db
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-secret
PORT=3000
```
### 9.2 启动命令
```bash
npm run dev # 开发模式
npm run build # 构建
npm start # 生产模式
```
---
## 10. 相关文档
- [API 规范](./API_Specs/)
- [数据库设计](./Database/)
- [系统架构](../01_Architecture/System_Architecture.md)
- [业务蓝图](../00_Business/Business_Blueprint.md)
---
*本文档基于代码自动生成,最后更新: 2026-03-18*