# 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*
