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

# Generate Transaction Statement

> Generate a downloadable transaction statement in CSV or PDF format

## Overview

Generates a downloadable transaction statement containing detailed transaction history. Supports both CSV and PDF formats, with optional date range filtering. Perfect for accounting, tax preparation, expense tracking, and financial record-keeping.

<Info>
  **Format Selection**

  Specify the desired format using the `Accept` header:

  * `text/csv` for CSV format
  * `application/pdf` for PDF format
</Info>

## Authentication

This endpoint requires authentication via Bearer token:

```bash theme={null}
Authorization: Bearer YOUR_ACCESS_TOKEN
```

## Request

### Headers

<ParamField header="x-client-key" type="string" required>
  Your public API client key
</ParamField>

<ParamField header="x-us-env" type="boolean" default={false}>
  Set to `true` to route requests to the US backend environment
</ParamField>

<ParamField header="Authorization" type="string" required>
  Bearer token for authentication
</ParamField>

<ParamField header="Accept" type="string" required>
  Desired response format

  **Accepted Values:**

  * `text/csv` - CSV format (comma-separated values)
  * `application/pdf` - PDF format (printable document)

  **Default:** Returns CSV if not specified
</ParamField>

### Query Parameters

<ParamField query="dateFrom" type="string">
  Start date for filtering transactions in ISO 8601 format (`YYYY-MM-DD`)

  **Required:** Only if `dateTo` is provided

  **Example:** `2024-10-24`

  **Note:** If not provided, returns complete transaction history
</ParamField>

<ParamField query="dateTo" type="string">
  End date for filtering transactions in ISO 8601 format (`YYYY-MM-DD`)

  **Required:** Only if `dateFrom` is provided

  **Example:** `2024-10-25`

  **Note:** Both `dateFrom` and `dateTo` must be provided together
</ParamField>

### Request Examples

<CodeGroup>
  ```bash CSV - All Transactions theme={null}
  curl -X GET "https://dev.api.baanx.com/v1/card/transactions/statement" \
    -H "x-client-key: YOUR_CLIENT_KEY" \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
    -H "Accept: text/csv" \
    --output transactions.csv
  ```

  ```bash PDF - Date Range theme={null}
  curl -X GET "https://dev.api.baanx.com/v1/card/transactions/statement?dateFrom=2024-10-01&dateTo=2024-10-31" \
    -H "x-client-key: YOUR_CLIENT_KEY" \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
    -H "Accept: application/pdf" \
    --output statement.pdf
  ```

  ```javascript JavaScript - CSV theme={null}
  const response = await fetch(
    'https://dev.api.baanx.com/v1/card/transactions/statement?dateFrom=2024-10-01&dateTo=2024-10-31',
    {
      headers: {
        'x-client-key': 'YOUR_CLIENT_KEY',
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        'Accept': 'text/csv'
      }
    }
  );

  const csvData = await response.text();

  const blob = new Blob([csvData], { type: 'text/csv' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'transactions.csv';
  a.click();
  ```

  ```javascript JavaScript - PDF theme={null}
  const response = await fetch(
    'https://dev.api.baanx.com/v1/card/transactions/statement?dateFrom=2024-10-01&dateTo=2024-10-31',
    {
      headers: {
        'x-client-key': 'YOUR_CLIENT_KEY',
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        'Accept': 'application/pdf'
      }
    }
  );

  const pdfBlob = await response.blob();

  const url = window.URL.createObjectURL(pdfBlob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'statement.pdf';
  a.click();
  ```

  ```python Python - CSV theme={null}
  import requests
  from datetime import date, timedelta

  url = "https://dev.api.baanx.com/v1/card/transactions/statement"
  headers = {
      "x-client-key": "YOUR_CLIENT_KEY",
      "Authorization": "Bearer YOUR_ACCESS_TOKEN",
      "Accept": "text/csv"
  }

  today = date.today()
  first_of_month = date(today.year, today.month, 1)

  params = {
      "dateFrom": first_of_month.isoformat(),
      "dateTo": today.isoformat()
  }

  response = requests.get(url, headers=headers, params=params)

  with open("transactions.csv", "wb") as f:
      f.write(response.content)

  print("CSV statement saved to transactions.csv")
  ```

  ```python Python - PDF theme={null}
  import requests

  url = "https://dev.api.baanx.com/v1/card/transactions/statement"
  headers = {
      "x-client-key": "YOUR_CLIENT_KEY",
      "Authorization": "Bearer YOUR_ACCESS_TOKEN",
      "Accept": "application/pdf"
  }

  params = {
      "dateFrom": "2024-10-01",
      "dateTo": "2024-10-31"
  }

  response = requests.get(url, headers=headers, params=params)

  with open("statement.pdf", "wb") as f:
      f.write(response.content)

  print("PDF statement saved to statement.pdf")
  ```

  ```typescript TypeScript theme={null}
  interface StatementOptions {
    dateFrom?: string;
    dateTo?: string;
    format: 'csv' | 'pdf';
  }

  const downloadStatement = async (options: StatementOptions) => {
    const params = new URLSearchParams();
    if (options.dateFrom) params.append('dateFrom', options.dateFrom);
    if (options.dateTo) params.append('dateTo', options.dateTo);

    const response = await fetch(
      `https://dev.api.baanx.com/v1/card/transactions/statement?${params}`,
      {
        headers: {
          'x-client-key': 'YOUR_CLIENT_KEY',
          'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
          'Accept': options.format === 'csv' ? 'text/csv' : 'application/pdf'
        }
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `statement-${Date.now()}.${options.format}`;
    a.click();
    window.URL.revokeObjectURL(url);
  };
  ```
</CodeGroup>

## Response

### CSV Format

Returns a CSV file with the following columns:

<ResponseField name="Timestamp" type="string">
  Transaction date and time in ISO 8601 format
</ResponseField>

<ResponseField name="Merchant" type="string">
  Merchant name and location
</ResponseField>

<ResponseField name="Merchant Type" type="string">
  Type of merchant or transaction context
</ResponseField>

<ResponseField name="Transaction Currency" type="string">
  Currency code for the card transaction
</ResponseField>

<ResponseField name="Transaction currency amount" type="string">
  Amount in the card's currency
</ResponseField>

<ResponseField name="Card currency" type="string">
  Card's base currency code
</ResponseField>

<ResponseField name="Card currency amount" type="string">
  Amount charged to the card
</ResponseField>

<ResponseField name="Funding Tokens" type="string">
  Cryptocurrencies/tokens used for funding
</ResponseField>

<ResponseField name="Funding Addresses" type="string">
  Wallet addresses used for funding
</ResponseField>

<ResponseExample>
  ```csv CSV Example theme={null}
  Timestamp,Merchant,Merchant Type,Transaction Currency,Transaction currency amount,Card currency,Card currency amount,Funding Tokens,Funding Addresses
  2024-10-14T10:44:36.276Z,WWW.ALIEXPRESS.COM LONDON,OutOfWalletOnline,USD,0.85,EUR,0.79,USDC,0x3a11...3424
  2024-10-13T15:22:10.123Z,STARBUCKS NEW YORK,InStore,USD,5.50,EUR,5.12,USDC,0x3a11...3424
  2024-10-12T09:15:44.567Z,AMAZON.COM,OutOfWalletOnline,USD,29.99,EUR,27.89,USDC USDT,0x3a11...3424 0x7b22...8912
  ```
</ResponseExample>

### PDF Format

Returns a formatted PDF document containing:

* **Header**: Account holder name, card details (last 4 digits)
* **Date Range**: Statement period
* **Transaction Table**: Detailed transaction list with columns similar to CSV
* **Summary Section**: Total spent, number of transactions, date range
* **Footer**: Page numbers, generation date

<ResponseExample>
  ```text PDF Example Structure theme={null}
  ┌─────────────────────────────────────────────────┐
  │  CARD TRANSACTION STATEMENT                      │
  │  Card: •••• 1234                                 │
  │  Period: October 1, 2024 - October 31, 2024    │
  └─────────────────────────────────────────────────┘

  Date          Merchant            Amount   Currency
  ─────────────────────────────────────────────────
  Oct 14, 2024  AliExpress          $0.85    USD
  Oct 13, 2024  Starbucks           $5.50    USD
  Oct 12, 2024  Amazon              $29.99   USD

  ─────────────────────────────────────────────────
  Total Transactions: 3
  Total Amount: $36.34 USD

  Generated: November 1, 2024
  Page 1 of 1
  ```
</ResponseExample>

## Error Responses

<ResponseExample>
  ```json 401 - Unauthorized theme={null}
  {
    "message": "Not authenticated"
  }
  ```

  ```json 403 - Forbidden theme={null}
  {
    "message": "Not authorized"
  }
  ```

  ```json 498 - Invalid Client Key theme={null}
  {
    "message": "Invalid client key"
  }
  ```

  ```json 499 - Missing Client Key theme={null}
  {
    "message": "Missing client key"
  }
  ```

  ```json 500 - Internal Server Error theme={null}
  {
    "message": "Internal server error"
  }
  ```
</ResponseExample>

## Use Cases

<CardGroup cols={2}>
  <Card title="Monthly Reports" icon="calendar-days">
    Generate monthly statements for accounting and bookkeeping
  </Card>

  <Card title="Tax Preparation" icon="file-invoice-dollar">
    Download annual transaction history for tax filing
  </Card>

  <Card title="Expense Tracking" icon="chart-line">
    Export data to spreadsheet software for analysis
  </Card>

  <Card title="Audit Trail" icon="clipboard-check">
    Maintain transaction records for compliance and auditing
  </Card>
</CardGroup>

## Common Integration Patterns

### Monthly Statement Download

```typescript theme={null}
async function downloadMonthlyStatement(year: number, month: number) {
  const dateFrom = new Date(year, month - 1, 1).toISOString().split('T')[0];
  const lastDay = new Date(year, month, 0).getDate();
  const dateTo = new Date(year, month - 1, lastDay).toISOString().split('T')[0];

  await downloadStatement({
    dateFrom,
    dateTo,
    format: 'pdf'
  });
}
```

### Annual Tax Report

```typescript theme={null}
async function generateAnnualTaxReport(year: number) {
  const dateFrom = `${year}-01-01`;
  const dateTo = `${year}-12-31`;

  await downloadStatement({
    dateFrom,
    dateTo,
    format: 'csv'
  });
}
```

### Custom Date Range Selector

```typescript theme={null}
function StatementDownloader() {
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [format, setFormat] = useState<'csv' | 'pdf'>('csv');
  const [loading, setLoading] = useState(false);

  const handleDownload = async () => {
    if (!dateFrom || !dateTo) {
      alert('Please select both start and end dates');
      return;
    }

    setLoading(true);
    try {
      await downloadStatement({ dateFrom, dateTo, format });
    } catch (error) {
      console.error('Failed to download statement:', error);
      alert('Failed to download statement. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h2>Download Transaction Statement</h2>

      <label>
        From:
        <input
          type="date"
          value={dateFrom}
          onChange={(e) => setDateFrom(e.target.value)}
        />
      </label>

      <label>
        To:
        <input
          type="date"
          value={dateTo}
          onChange={(e) => setDateTo(e.target.value)}
        />
      </label>

      <label>
        Format:
        <select value={format} onChange={(e) => setFormat(e.target.value as 'csv' | 'pdf')}>
          <option value="csv">CSV</option>
          <option value="pdf">PDF</option>
        </select>
      </label>

      <button onClick={handleDownload} disabled={loading}>
        {loading ? 'Downloading...' : 'Download Statement'}
      </button>
    </div>
  );
}
```

### Automated Monthly Reports

```typescript theme={null}
async function scheduleMonthlyReports() {
  const today = new Date();
  const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
  const lastDayOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);

  const dateFrom = lastMonth.toISOString().split('T')[0];
  const dateTo = lastDayOfLastMonth.toISOString().split('T')[0];

  try {
    await downloadStatement({
      dateFrom,
      dateTo,
      format: 'pdf'
    });

    console.log('Monthly report generated successfully');
  } catch (error) {
    console.error('Failed to generate monthly report:', error);
  }
}
```

## CSV Processing

Example of parsing CSV data in JavaScript:

```typescript theme={null}
async function parseCSVStatement(dateFrom: string, dateTo: string) {
  const response = await fetch(
    `https://dev.api.baanx.com/v1/card/transactions/statement?dateFrom=${dateFrom}&dateTo=${dateTo}`,
    {
      headers: {
        'x-client-key': 'YOUR_CLIENT_KEY',
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        'Accept': 'text/csv'
      }
    }
  );

  const csvText = await response.text();
  const lines = csvText.split('\n');
  const headers = lines[0].split(',');

  const transactions = lines.slice(1).map(line => {
    const values = line.split(',');
    const transaction: any = {};

    headers.forEach((header, index) => {
      transaction[header.trim()] = values[index]?.trim();
    });

    return transaction;
  });

  return transactions;
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="File Naming">
    Use descriptive filenames with date ranges:

    ```typescript theme={null}
    const filename = `statement-${dateFrom}-to-${dateTo}.${format}`;
    ```

    **Examples:**

    * `statement-2024-10-01-to-2024-10-31.pdf`
    * `transactions-2024-annual.csv`
  </Accordion>

  <Accordion title="Large Date Ranges">
    For very large date ranges (e.g., multiple years), consider splitting into smaller chunks:

    ```typescript theme={null}
    async function downloadAnnualStatementsByMonth(year: number) {
      for (let month = 1; month <= 12; month++) {
        const dateFrom = new Date(year, month - 1, 1).toISOString().split('T')[0];
        const dateTo = new Date(year, month, 0).toISOString().split('T')[0];

        await downloadStatement({
          dateFrom,
          dateTo,
          format: 'pdf'
        });

        await delay(1000);
      }
    }
    ```
  </Accordion>

  <Accordion title="Error Handling">
    Always handle download errors gracefully:

    ```typescript theme={null}
    try {
      await downloadStatement(options);
      showSuccess('Statement downloaded successfully');
    } catch (error) {
      if (error.response?.status === 401) {
        showError('Session expired. Please log in again.');
      } else if (error.response?.status === 404) {
        showError('No transactions found for this period.');
      } else {
        showError('Download failed. Please try again.');
      }
    }
    ```
  </Accordion>

  <Accordion title="User Feedback">
    Provide clear feedback during download:

    ```typescript theme={null}
    const [downloading, setDownloading] = useState(false);

    const handleDownload = async () => {
      setDownloading(true);
      try {
        await downloadStatement(options);
        toast.success('Statement downloaded');
      } catch (error) {
        toast.error('Download failed');
      } finally {
        setDownloading(false);
      }
    };
    ```
  </Accordion>
</AccordionGroup>

## Edge Cases

<Warning>
  **Date Range Validation**

  If only one of `dateFrom` or `dateTo` is provided, both parameters will be ignored and the complete transaction history will be returned.
</Warning>

<Note>
  **Empty Results**

  If no transactions exist for the specified date range, you'll receive an empty CSV (headers only) or a PDF with "No transactions found" message.
</Note>

<Info>
  **Content-Type Header**

  The response `Content-Type` header will match your `Accept` header:

  * `text/csv` for CSV downloads
  * `application/pdf` for PDF downloads
</Info>

## Related Endpoints

* `GET /v1/card/transactions` - Retrieve transaction history as JSON with advanced filtering
* `GET /v1/card/status` - Get card information before generating statement
