
# 取引 API

取引とは、[セールスパイプライン](../deals/sales-pipeline.md)ボード上の1つの販売機会を指します。これには、タイトル、金額、現在のステージ、およびオプションとして関連付けられた連絡先や担当チームメンバーが含まれます。このガイドでは、APIを介した取引の読み取りと管理について説明します。

- **ベースURL** — `https://api.youraiconnector.com/v1`
- **認証** — APIキー（[認証](authentication.md)を参照）
- **エラーとページネーション** — [エラーとページネーション](errors-and-pagination.md)を参照

以下のすべての例では、cURLでの `?apiKey=` クエリ形式と、JavaScriptおよびPythonでの `X-API-Key` ヘッダーを示しています。どちらの方法もすべてのエンドポイントで使用可能です。

---

## 取引オブジェクト

```json
{
  "id": "deal_abc123",
  "title": "Annual plan – Jane's Clinic",
  "description": "Asked for pricing on the annual plan.",
  "company": "Jane's Clinic",
  "notes": "Prefers a call after 5pm.",
  "stage": "stage-2",
  "pipeline_id": "default",
  "value": 4800,
  "probability": 60,
  "priority": "high",
  "status": "open",
  "source": "whatsapp",
  "position": 0,
  "contact_id": "ctc_9f8e7d",
  "assigned_to": "usr_4a2b",
  "tags": ["clinic"],
  "close_date": "2026-10-01T00:00:00.000Z",
  "created_at": "2026-09-05T09:12:00.000Z",
  "updated_at": "2026-09-05T09:40:00.000Z",
  "stage_entered_at": "2026-09-05T09:40:00.000Z"
}
```

`stage` はパイプラインステージのIDです。`GET /pipelines` で読み取ることができます（以下の [パイプライン](#pipelines) を参照）。ステージIDはすべてのパイプラインを通じて一意であるため、`pipeline_id` はステージから派生しており、読み取り専用です。`default` はメインパイプラインであり、ステージが存在しなくなると `null` になります。タイムスタンプは ISO 8601 形式です。

取引には、上記に表示されているフィールドのみが保存されます。取引を作成または更新する際、それ以外のフィールドが含まれていると、そのフィールド名を指定した `400` が返され、送信したデータが警告なしに失われることはありません。追加のデータは、リンクされた連絡先のカスタムフィールドに保存してください。

---

## 取引の一覧取得

`GET /deals` — アカウント上の取引を新しい順に返します。

**クエリパラメータ**（すべて任意）: `stage`（ステージID）、`pipeline_id`（そのパイプライン上の案件のみ）、`contact_id`、`limit`（デフォルト50、最大200）、`cursor`（前のページの `next_cursor` から）。

**cURL**

```bash
curl "https://api.youraiconnector.com/v1/deals?apiKey=YOUR_API_KEY&stage=stage-2&limit=50"
```

**JavaScript**

```javascript
const res = await fetch("https://api.youraiconnector.com/v1/deals?stage=stage-2&limit=50", {
  headers: { "X-API-Key": "YOUR_API_KEY" },
});
const { deals, next_cursor } = await res.json();
```

**Python**

```python
res = requests.get(
    "https://api.youraiconnector.com/v1/deals",
    headers={"X-API-Key": "YOUR_API_KEY"},
    params={"stage": "stage-2", "limit": 50},
)
deals = res.json()["deals"]
```

**レスポンス** (`200`)

```json
{ "success": true, "deals": [{ "id": "deal_abc123", "title": "Annual plan – Jane's Clinic", "...": "..." }], "next_cursor": null }
```

---

## 取引を取得する

`GET /deals/{dealId}`

```bash
curl "https://api.youraiconnector.com/v1/deals/deal_abc123?apiKey=YOUR_API_KEY"
```

**レスポンス** (`200`)

```json
{ "success": true, "deal": { "id": "deal_abc123", "title": "Annual plan – Jane's Clinic", "...": "..." } }
```

存在しない取引、または別のアカウントに属する取引を指定した場合、`404` が返されます。

---

## 取引を作成する

`POST /deals` — `title` と `stage` は必須です。`stage` には、パイプラインのステージIDのいずれかを指定する必要があります。

```bash
curl -X POST "https://api.youraiconnector.com/v1/deals?apiKey=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "title": "Annual plan – Jane'"'"'s Clinic", "stage": "stage-1", "value": 4800, "contact_id": "ctc_9f8e7d" }'
```

**レスポンス** (`201`)

```json
{ "success": true, "deal_id": "deal_abc123" }
```

---

## 取引を更新する

`PUT /deals/{dealId}` — 変更したいフィールドのみを送信します（`title`、`description`、`notes`、`value`、`stage`、`status`、`priority`、`contact_id`、…）。`value` は数値である必要があります。

```bash
curl -X PUT "https://api.youraiconnector.com/v1/deals/deal_abc123?apiKey=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "value": 5200, "priority": "high" }'
```

**レスポンス** (`200`): `{ "success": true, "deal_id": "deal_abc123" }`

---

## 取引を別のステージに移動する

`POST /deals/{dealId}/move` — 本文 `{ "new_stage_id": "stage-3", "new_position": 0 }`。位置 `0` はカードを列の最上部に配置します。

```bash
curl -X POST "https://api.youraiconnector.com/v1/deals/deal_abc123/move?apiKey=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "new_stage_id": "stage-3", "new_position": 0 }'
```

**レスポンス** (`200`): `{ "success": true, "deal_id": "deal_abc123", "stage": "stage-3", "position": 0 }`

---

## 取引を削除する

`DELETE /deals/{dealId}` — 取引を削除します。**この操作は元に戻せません。**

```bash
curl -X DELETE "https://api.youraiconnector.com/v1/deals/deal_abc123?apiKey=YOUR_API_KEY"
```

**レスポンス** (`200`): `{ "success": true }`

---

## パイプライン

すべてのアカウントにはメインパイプライン（`id: "default"`）があります。最大9つまで追加でき、それぞれに独自のステージを持たせることができます。ステージIDとトリガータグはアカウント内のすべてのパイプラインを通じて一意である必要があり、各パイプラインで1つのステージを `won` として、もう1つを `lost` 結果としてマークできます。

### パイプラインの一覧表示

`GET /pipelines` — すべてのパイプライン（メインが最初）、各ステージは位置順に並べ替えられます。

```bash
curl "https://api.youraiconnector.com/v1/pipelines?apiKey=YOUR_API_KEY"
```

**レスポンス** (`200`):

```json
{
  "success": true,
  "data": {
    "pipelines": [
      {
        "id": "default",
        "name": "Sales",
        "position": 0,
        "is_default": true,
        "settings": { "sync_stage_tags": false },
        "stages": [
          { "id": "stage-1", "name": "New lead", "color": "#3B82F6", "position": 0, "trigger_tag": null },
          { "id": "won", "name": "Won", "color": "#10B981", "position": 1, "outcome": "won" }
        ]
      }
    ]
  }
}
```

### パイプラインの作成

`POST /pipelines` — ボディ `{ "id"?, "name", "stages"?, "settings"? }`。`id` を省略すると自動生成されます。各ステージは「ステージ」ダイアログと同じフィールドを取ります：`id`、`name`、`color`、`position`、任意で `trigger_tag`（タグパス、`users/{uid}/tags/{tagId}`）、`default_value`、`auto_move_after_days` + `auto_move_to_stage`（同じパイプラインのステージ）、および `outcome`（`"won"` または `"lost"`）。

```bash
curl -X POST "https://api.youraiconnector.com/v1/pipelines?apiKey=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "reviews",
    "name": "Review requests",
    "stages": [
      { "id": "rv_asked", "name": "Asked", "color": "#3B82F6", "position": 0 },
      { "id": "rv_done", "name": "Review posted", "color": "#10B981", "position": 1, "outcome": "won" }
    ]
  }'
```

**レスポンス** (`201`): `{ "success": true, "data": { "pipeline": { ... } } }`。他のパイプラインですでに使用されているステージIDまたはトリガータグは、そのパイプラインを指定する `400` となります。すでに存在するIDは `409` となります。

### パイプラインの更新

`PUT /pipelines/{pipelineId}` — ボディ `{ "name"?, "stages"?, "settings"? }`。`stages` は「ステージ」ダイアログと同様にリスト全体を置き換えます。メインパイプラインには `default` を使用してください。パイプラインID自体は変更できません。

### パイプラインの削除

`DELETE /pipelines/{pipelineId}` — 追加のパイプラインを削除します（メインパイプラインは削除できません）。ステージ内に案件が残っている場合、呼び出しは `deal_count` を伴う `409` を返します。`?delete_deals=true` を追加すると、パイプラインと一緒にそれらの案件も削除されます。**この操作は元に戻せません。**

**レスポンス** (`204`)。

---

## 次のステップ

- [セールスパイプライン](../deals/sales-pipeline.md) — ステージ、ステージタグ、複数のパイプライン、ボードの仕組みについて。
- [タスク API](tasks.md) — タスクは `deal_id` を使用して取引にリンクできます。
- [自動化](../automations/automations.md) — **取引を検索**および**取引を検索**ステップは、ワークフロー内で同じデータを読み取ります。
