> ## Documentation Index
> Fetch the complete documentation index at: https://developers.zangsho.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 資料匯入

> 使用批次 API 匯入歷史客戶、訂單、訂閱資料到帳獸

## 概覽

如果你已經有現有的業務資料，帳獸提供批次匯入 API 讓你快速將歷史資料匯入系統。本指南將帶你完成完整的匯入流程。

## 匯入順序

由於資料之間有關聯性，建議按照以下順序匯入：

<Steps>
  <Step title="匯入客戶">
    客戶是基礎資料，訂單和訂閱都需要關聯到客戶。
  </Step>

  <Step title="匯入訂單">
    訂單需要 `customer_id`，所以必須先有客戶資料。
  </Step>

  <Step title="匯入訂閱">
    訂閱需要 `customer_id`，且每位客戶只能有一個訂閱。
  </Step>

  <Step title="匯入訂閱事件">
    訂閱事件需要 `customer_email`，記錄升降級歷史。
  </Step>
</Steps>

## 批次匯入客戶

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.zangsho.com/v1/customers/batch \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "on_conflict": "skip",
      "customers": [
        {
          "email": "wang.xiaoming@example.com",
          "name": "王小明",
          "phone": "0912345678"
        },
        {
          "email": "chen.meili@example.com",
          "name": "陳美麗",
          "phone": "0923456789",
          "metadata": {"source": "website"}
        }
      ]
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.zangsho.com/v1/customers/batch', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_TOKEN',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      on_conflict: 'skip',
      customers: [
        { email: 'wang.xiaoming@example.com', name: '王小明', phone: '0912345678' },
        { email: 'chen.meili@example.com', name: '陳美麗', phone: '0923456789' }
      ]
    })
  });
  ```

  ```php PHP (Laravel) theme={null}
  $response = Http::withToken('YOUR_API_TOKEN')
      ->post('https://api.zangsho.com/v1/customers/batch', [
          'on_conflict' => 'skip',
          'customers' => [
              ['email' => 'wang.xiaoming@example.com', 'name' => '王小明', 'phone' => '0912345678'],
              ['email' => 'chen.meili@example.com', 'name' => '陳美麗', 'phone' => '0923456789'],
          ],
      ]);
  ```
</CodeGroup>

## 衝突處理策略

當匯入的資料與現有資料衝突時（例如 `email` 已存在），你可以透過 `on_conflict` 參數來控制處理方式：

| 策略       | 說明                  |
| -------- | ------------------- |
| `skip`   | 跳過衝突的資料，保留現有資料（預設值） |
| `update` | 用匯入的資料更新現有資料        |

<Tip>
  如果你是第一次匯入歷史資料，建議使用 `skip` 策略。如果需要更新已存在的資料，再切換為 `update`。
</Tip>

## 批次匯入訂單

```bash theme={null}
curl -X POST https://api.zangsho.com/v1/orders/batch \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "on_conflict": "skip",
    "orders": [
      {
        "order_no": "ORD-2025-001",
        "customer_email": "wang.xiaoming@example.com",
        "customer_name": "王小明",
        "amount": "1990.00",
        "currency": "TWD",
        "status": "paid",
        "payment_method": "credit_card",
        "billing_cycle": "monthly",
        "paid_at": "2025-12-01T08:00:00Z"
      },
      {
        "order_no": "ORD-2025-002",
        "customer_email": "chen.meili@example.com",
        "customer_name": "陳美麗",
        "amount": "5990.00",
        "currency": "TWD",
        "status": "paid",
        "payment_method": "credit_card",
        "billing_cycle": "yearly",
        "paid_at": "2025-12-15T10:00:00Z"
      }
    ]
  }'
```

## 回應格式

批次匯入的回應包含每筆資料的處理結果：

```json theme={null}
{
  "data": {
    "total": 10,
    "created": 8,
    "updated": 0,
    "skipped": 1,
    "failed": 1,
    "results": {
      "created": [
        {"index": 0, "id": 101, "identifier": "wang.xiaoming@example.com"},
        {"index": 1, "id": 102, "identifier": "chen.meili@example.com"}
      ],
      "skipped": [
        {"index": 5, "reason": "duplicate_email", "identifier": "existing@example.com"}
      ],
      "failed": [
        {"index": 9, "reason": "validation_error", "message": "email 欄位為必填", "identifier": null}
      ]
    }
  }
}
```

| 欄位        | 說明                       |
| --------- | ------------------------ |
| `total`   | 提交的總筆數                   |
| `created` | 成功新建的筆數                  |
| `updated` | 成功更新的筆數（使用 `update` 策略時） |
| `skipped` | 被跳過的筆數（衝突且使用 `skip` 策略）  |
| `failed`  | 驗證失敗的筆數                  |

## 限制

<Warning>
  * 每次批次匯入最多 **100 筆**資料
  * 批次匯入**不會觸發 Webhook**（僅記錄 Activity Log）
  * 如果需要觸發 Webhook 通知，請使用單筆建立 API
</Warning>

## 常見錯誤排除

<AccordionGroup>
  <Accordion title="422 Validation Error - email 欄位為必填">
    確認每筆客戶資料都包含 `email` 欄位。`email` 是客戶的必填欄位。
  </Accordion>

  <Accordion title="422 Validation Error - order_no 已存在">
    使用 `on_conflict: update` 策略，或確認該訂單編號尚未匯入。
  </Accordion>

  <Accordion title="422 Validation Error - customer_id 不存在">
    確認已先匯入客戶資料，並使用正確的客戶 ID。匯入順序很重要：客戶 → 訂單。
  </Accordion>

  <Accordion title="匯入成功但數量不符">
    檢查回應中的 `skipped` 和 `failed` 陣列，了解哪些資料被跳過或失敗，以及具體原因。
  </Accordion>
</AccordionGroup>

## 匯入範例：完整流程

以下是匯入一整套歷史資料的完整流程範例：

```javascript Node.js theme={null}
// 1. 匯入客戶
const customerResult = await fetch('https://api.zangsho.com/v1/customers/batch', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    on_conflict: 'skip',
    customers: customers // 你的客戶陣列
  })
});
console.log('客戶匯入結果:', await customerResult.json());

// 2. 匯入訂單
const orderResult = await fetch('https://api.zangsho.com/v1/orders/batch', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    on_conflict: 'skip',
    orders: orders // 你的訂單陣列
  })
});
console.log('訂單匯入結果:', await orderResult.json());

// 3. 匯入訂閱（選填，SaaS 模式適用）
const subscriptionResult = await fetch('https://api.zangsho.com/v1/subscriptions/batch', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    on_conflict: 'skip',
    subscriptions: subscriptions
  })
});
console.log('訂閱匯入結果:', await subscriptionResult.json());
```

<Tip>
  如果資料量超過 100 筆，你需要將資料分批處理。建議每批 100 筆，批次之間間隔 1 秒，避免觸發頻率限制。
</Tip>

## 下一步

<CardGroup cols={2}>
  <Card title="API 文件" icon="book" href="/api-reference/introduction">
    查看完整的批次匯入 API 端點文件。
  </Card>

  <Card title="Webhook 設定" icon="webhook" href="/guides/webhooks">
    設定 Webhook 接收即時訂單通知。
  </Card>
</CardGroup>
