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

# Bulk Delete by Filters

> Delete all purchases matching filter criteria using an optimistic concurrency guard

# Bulk Delete by Filters

Delete all purchases that match the given filter criteria. Uses the same filter parameters as the list endpoint, plus a `filter_hash` for optimistic concurrency — ensuring you delete exactly what the user saw.

## How filter\_hash works

1. Call the [list endpoint](/api-reference/purchases/list) with your filters — the response includes a `filter_hash`
2. Pass that `filter_hash` in the body of this request along with the same filters
3. If the filters changed between the two calls, the server returns `409 Conflict`

This prevents accidental mass deletions when filters have been modified.

## Request

### Headers

<ParamField header="x-api-key" type="string" required>
  Your API key for authentication

  **Example:** `sk_live_1234567890abcdef`
</ParamField>

<ParamField header="x-organization-id" type="string" required>
  Your organization UUID

  **Example:** `a8315ef3-dd50-43f8-b7ce-d839e68d51fa`
</ParamField>

### Query Parameters

At least one filter parameter is required. Supports all the same filters as the [list endpoint](/api-reference/purchases/list):

<ParamField query="purchase_date_from" type="string">
  Filter purchases on or after this date (`YYYY-MM-DD`)
</ParamField>

<ParamField query="purchase_date_to" type="string">
  Filter purchases on or before this date (`YYYY-MM-DD`)
</ParamField>

<ParamField query="search" type="string">
  Search by description or supplier name
</ParamField>

<ParamField query="status[]" type="string[]">
  Filter by status. Values: `active`, `error`, `in_progress`, `in_review`, `inactive`, `pending`
</ParamField>

<ParamField query="purchase_type[]" type="string[]">
  Filter by calculation methodology. Values: `spend_based`, `supplier_specific`
</ParamField>

<ParamField query="expense_type[]" type="string[]">
  Filter by expense classification. Values: `capex`, `opex`
</ParamField>

<ParamField query="file_id[]" type="string[]">
  Filter by file UUID
</ParamField>

<ParamField query="supplier_id[]" type="string[]">
  Filter by supplier UUID
</ParamField>

<ParamField query="unit_id[]" type="string[]">
  Filter by currency unit UUID
</ParamField>

<ParamField query="created_at_from" type="string">
  Filter records created on or after this date
</ParamField>

<ParamField query="created_at_to" type="string">
  Filter records created on or before this date
</ParamField>

<ParamField query="co2e_status" type="string">
  Filter by CO2e calculation status
</ParamField>

### Body Parameters

<ParamField body="filter_hash" type="string" required>
  Hash from the list endpoint response. Must match the current filter set.
</ParamField>

## Response

<ResponseField name="deleted" type="string[]">
  UUIDs of successfully deleted purchases
</ResponseField>

<ResponseField name="failed" type="object[]">
  Failed deletions with reason
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  # Step 1: Get filter_hash from list
  RESPONSE=$(curl -s "https://api.dcycle.io/v1/purchases?expense_type[]=opex&purchase_date_to=2024-12-31" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}")

  FILTER_HASH=$(echo $RESPONSE | jq -r '.filter_hash')

  # Step 2: Bulk delete with the same filters
  curl -X POST "https://api.dcycle.io/v1/purchases/bulk-delete-by-filters?expense_type[]=opex&purchase_date_to=2024-12-31" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "Content-Type: application/json" \
    -d "{\"filter_hash\": \"${FILTER_HASH}\"}"
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests
  import os

  headers = {
      "x-api-key": os.getenv("DCYCLE_API_KEY"),
      "x-organization-id": os.getenv("DCYCLE_ORG_ID"),
  }

  filters = {"expense_type[]": "opex", "purchase_date_to": "2024-12-31"}

  # Step 1: Get filter_hash from list
  list_resp = requests.get(
      "https://api.dcycle.io/v1/purchases",
      headers=headers,
      params=filters,
  )
  filter_hash = list_resp.json()["filter_hash"]

  # Step 2: Bulk delete with the same filters
  delete_resp = requests.post(
      "https://api.dcycle.io/v1/purchases/bulk-delete-by-filters",
      headers={**headers, "Content-Type": "application/json"},
      params=filters,
      json={"filter_hash": filter_hash},
  )

  result = delete_resp.json()
  print(f"Deleted: {len(result['deleted'])} | Failed: {len(result['failed'])}")
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const axios = require('axios');

  const headers = {
    'x-api-key': process.env.DCYCLE_API_KEY,
    'x-organization-id': process.env.DCYCLE_ORG_ID,
  };

  const filters = { 'expense_type[]': 'opex', purchase_date_to: '2024-12-31' };

  // Step 1: Get filter_hash from list
  const listResp = await axios.get('https://api.dcycle.io/v1/purchases', {
    headers, params: filters,
  });
  const filterHash = listResp.data.filter_hash;

  // Step 2: Bulk delete with the same filters
  const deleteResp = await axios.post(
    'https://api.dcycle.io/v1/purchases/bulk-delete-by-filters',
    { filter_hash: filterHash },
    { headers: { ...headers, 'Content-Type': 'application/json' }, params: filters },
  );

  console.log(`Deleted: ${deleteResp.data.deleted.length}`);
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "deleted": [
    "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "b2c3d4e5-f6a7-8901-bcde-f12345678901"
  ],
  "failed": []
}
```

## Common Errors

### 401 Unauthorized

**Cause:** Missing or invalid API key

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"detail": "Invalid API key for organization", "code": "INVALID_API_KEY"}
```

### 403 Forbidden

**Cause:** The authenticated user is not a member of the organization

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"detail": "Logged User is not Member of Organization", "code": "LOGGED_USER_NOT_MEMBER"}
```

### 409 Conflict

**Cause:** The `filter_hash` doesn't match the current filters — they changed since the list was loaded

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Filter hash mismatch. The filters have changed since the list was loaded. Please refresh and try again."
}
```

### 422 Unprocessable Entity

**Cause:** No filter parameters provided (at least one is required to prevent accidental mass deletion)

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "At least one filter parameter is required for bulk delete by filters."
}
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Bulk Delete" icon="trash" href="/api-reference/purchases/bulk-delete">
    Delete specific purchases by ID
  </Card>

  <Card title="List Purchases" icon="list" href="/api-reference/purchases/list">
    Browse purchases and get filter\_hash
  </Card>
</CardGroup>
