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

# Working with Business Areas

> Learn how to retrieve and use business areas to organize your master data operations

This guide explains how to work with business areas in Pretectum using the API. You will learn how to retrieve the business areas your application has access to and use them effectively in your data operations.

## Overview

Business areas are the top-level organizational units in Pretectum that categorize your master data. They provide a logical structure for organizing different types of data within your organization:

* **Customer**: Customer records, contacts, and related data
* **Product**: Product catalog, inventory, and specifications
* **Supplier**: Vendor and supplier information
* **Employee**: Human resources and personnel data

Each business area contains schemas (data structures) and datasets (collections of records) that further organize your data.

## Why Business Areas Matter

Understanding your business areas is essential for:

1. **Scoped Searches**: Filter search results to specific data categories
2. **Access Control**: Different applications may have access to different business areas
3. **Data Organization**: Understand the structure of your master data
4. **Performance**: Searching within a specific business area is faster than searching across all data

## Before You Begin

To use the Business Areas API, you need:

<Steps>
  <Step title="Create an API Key">
    In the Pretectum app, go to **Configuration → API Keys** and create a key. It is shown once, at
    creation, so copy it then. See [API Keys](/api-reference/authentication/api-keys).
  </Step>

  <Step title="Verify Permissions">
    Ensure your application client has been granted access to the business areas permission.
  </Step>
</Steps>

## Retrieving Business Areas

Use the List Business Areas endpoint to get all business areas your application can access.

### Basic Request

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.pretectum.io/v1/my/businessareas" \
    -H "Authorization: pre_your_api_key" \
    -H "Accept: application/json"
  ```

  ```javascript JavaScript theme={null}
  async function getBusinessAreas(apiKey) {
    const response = await fetch('https://api.pretectum.io/v1/my/businessareas', {
      headers: {
        'Authorization': apiKey,
        'Accept': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch business areas: ${response.statusText}`);
    }

    return response.json();
  }

  // Usage
  const apiKey = 'pre_your_api_key';
  const businessAreas = await getBusinessAreas(apiKey);
  console.log('Available business areas:', businessAreas);
  ```

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

  def get_business_areas(api_key):
      response = requests.get(
          'https://api.pretectum.io/v1/my/businessareas',
          headers={
              'Authorization': api_key,
              'Accept': 'application/json'
          }
      )
      response.raise_for_status()
      return response.json()

  # Usage
  api_key = 'pre_your_api_key'
  business_areas = get_business_areas(api_key)
  print('Available business areas:', business_areas)
  ```
</CodeGroup>

### Understanding the Response

The API returns an array of business area objects:

```json theme={null}
[
  {
    "businessAreaId": "20240115103000123a1b2c3d4e5f6789012345678901234",
    "name": "Customer",
    "description": "Customer master data including individuals and businesses",
    "active": true,
    "createdBy": "admin",
    "updatedBy": "admin",
    "createdDate": "2024-01-15T10:30:00Z",
    "updatedDate": "2024-06-01T14:22:00Z",
    "version": 3
  },
  {
    "businessAreaId": "20240115103500456b2c3d4e5f67890123456789012345",
    "name": "Product",
    "description": "Product catalog and inventory master data",
    "active": true,
    "createdBy": "admin",
    "updatedBy": "product_manager",
    "createdDate": "2024-01-15T10:35:00Z",
    "updatedDate": "2024-08-15T09:45:00Z",
    "version": 5
  }
]
```

| Field | Description |
| - | - |
| `businessAreaId` | Unique identifier for the business area |
| `name` | Display name used for filtering in search operations |
| `description` | Explanation of the business area's purpose |
| `active` | Whether the business area is currently active |
| `createdBy` | User who created the business area |
| `updatedBy` | User who last modified the business area |
| `createdDate` | When the business area was created |
| `updatedDate` | When the business area was last modified |
| `version` | Version number for tracking changes |

## Using Business Areas for Search

Once you have the list of business areas, use the `name` field to filter your data object searches.

### Searching Within a Business Area

<CodeGroup>
  ```bash cURL theme={null}
  # Get business areas
  curl -X GET "https://api.pretectum.io/v1/my/businessareas" \
    -H "Authorization: pre_your_api_key"

  # Search within the "Customer" business area
  curl -X GET "https://api.pretectum.io/v1/dataobjects/search?query=John&businessArea=Customer" \
    -H "Authorization: pre_your_api_key"
  ```

  ```javascript JavaScript theme={null}
  async function searchInBusinessArea(apiKey, query, businessAreaName) {
    const params = new URLSearchParams({
      query: query,
      businessArea: businessAreaName
    });

    const response = await fetch(
      `https://api.pretectum.io/v1/dataobjects/search?${params}`,
      {
        headers: { 'Authorization': apiKey }
      }
    );

    return response.json();
  }

  // Search for "John" in the Customer business area
  const results = await searchInBusinessArea(apiKey, 'John', 'Customer');
  console.log(`Found ${results.total} customers matching "John"`);
  ```

  ```python Python theme={null}
  def search_in_business_area(api_key, query, business_area_name):
      response = requests.get(
          'https://api.pretectum.io/v1/dataobjects/search',
          params={
              'query': query,
              'businessArea': business_area_name
          },
          headers={'Authorization': api_key}
      )
      response.raise_for_status()
      return response.json()

  # Search for "John" in the Customer business area
  results = search_in_business_area(api_key, 'John', 'Customer')
  print(f"Found {results['total']} customers matching 'John'")
  ```
</CodeGroup>

## Complete Client Implementation

Here is a complete implementation that handles authentication, business area retrieval, and searching:

<CodeGroup>
  ```javascript JavaScript theme={null}
  const API_BASE = 'https://api.pretectum.io';

  class PretectumClient {
    constructor(apiKey) {
      this.apiKey = apiKey;
      this.businessAreas = null;
    }

    async getBusinessAreas(forceRefresh = false) {
      if (this.businessAreas && !forceRefresh) {
        return this.businessAreas;
      }

      const response = await fetch(`${API_BASE}/v1/my/businessareas`, {
        headers: {
          'Authorization': this.apiKey,
          'Accept': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch business areas: ${response.statusText}`);
      }

      this.businessAreas = await response.json();
      return this.businessAreas;
    }

    async getActiveBusinessAreas() {
      const areas = await this.getBusinessAreas();
      return areas.filter(area => area.active);
    }

    async getBusinessAreaNames() {
      const areas = await this.getActiveBusinessAreas();
      return areas.map(area => area.name);
    }

    async hasAccessTo(businessAreaName) {
      const areas = await this.getBusinessAreas();
      return areas.some(
        area => area.name === businessAreaName && area.active
      );
    }

    async search(query, options = {}) {
      // Validate business area if provided
      if (options.businessArea) {
        const hasAccess = await this.hasAccessTo(options.businessArea);
        if (!hasAccess) {
          throw new Error(`No access to business area: ${options.businessArea}`);
        }
      }

      const params = new URLSearchParams({ query, ...options });
      const response = await fetch(
        `${API_BASE}/dataobjects/search?${params}`,
        {
          headers: { 'Authorization': this.apiKey }
        }
      );

      if (!response.ok) {
        throw new Error(`Search failed: ${response.statusText}`);
      }

      return response.json();
    }

    async searchAllBusinessAreas(query, options = {}) {
      const areas = await this.getActiveBusinessAreas();
      const results = {};

      for (const area of areas) {
        const searchResults = await this.search(query, {
          ...options,
          businessArea: area.name
        });
        results[area.name] = searchResults;
      }

      return results;
    }
  }

  // Usage
  const client = new PretectumClient(process.env.PRETECTUM_API_KEY);

  // Get available business areas
  const businessAreas = await client.getBusinessAreas();
  console.log('Available business areas:');
  businessAreas.forEach(area => {
    console.log(`  - ${area.name}: ${area.description}`);
  });

  // Get just the names for a dropdown
  const areaNames = await client.getBusinessAreaNames();
  console.log('Business area names:', areaNames);

  // Search within a specific business area
  const results = await client.search('John', { businessArea: 'Customer' });
  console.log(`Found ${results.total} customers`);

  // Search across all business areas
  const allResults = await client.searchAllBusinessAreas('Smith');
  for (const [areaName, data] of Object.entries(allResults)) {
    console.log(`${areaName}: ${data.total} results`);
  }
  ```

  ```python Python theme={null}
  import os
  import requests
  from typing import Optional, Dict, List, Any

  class PretectumClient:
      API_BASE = 'https://api.pretectum.io'

      def __init__(self, api_key: str):
          self.api_key = api_key
          self._business_areas: Optional[List[Dict]] = None

      def get_business_areas(self, force_refresh: bool = False) -> List[Dict]:
          if self._business_areas and not force_refresh:
              return self._business_areas

          response = requests.get(
              f'{self.API_BASE}/v1/my/businessareas',
              headers={
                  'Authorization': self.api_key,
                  'Accept': 'application/json'
              }
          )
          response.raise_for_status()

          self._business_areas = response.json()
          return self._business_areas

      def get_active_business_areas(self) -> List[Dict]:
          areas = self.get_business_areas()
          return [area for area in areas if area.get('active', False)]

      def get_business_area_names(self) -> List[str]:
          areas = self.get_active_business_areas()
          return [area['name'] for area in areas]

      def has_access_to(self, business_area_name: str) -> bool:
          areas = self.get_business_areas()
          return any(
              area['name'] == business_area_name and area.get('active', False)
              for area in areas
          )

      def search(self, query: str, **options) -> Dict[str, Any]:
          # Validate business area if provided
          if 'businessArea' in options:
              if not self.has_access_to(options['businessArea']):
                  raise ValueError(f"No access to business area: {options['businessArea']}")

          params = {'query': query, **options}
          response = requests.get(
              f'{self.API_BASE}/dataobjects/search',
              params=params,
              headers={'Authorization': self.api_key}
          )
          response.raise_for_status()

          return response.json()

      def search_all_business_areas(self, query: str, **options) -> Dict[str, Dict]:
          areas = self.get_active_business_areas()
          results = {}

          for area in areas:
              search_results = self.search(query, businessArea=area['name'], **options)
              results[area['name']] = search_results

          return results


  # Usage
  client = PretectumClient(os.environ['PRETECTUM_API_KEY'])

  # Get available business areas
  business_areas = client.get_business_areas()
  print('Available business areas:')
  for area in business_areas:
      print(f"  - {area['name']}: {area['description']}")

  # Get just the names for a dropdown
  area_names = client.get_business_area_names()
  print('Business area names:', area_names)

  # Search within a specific business area
  results = client.search('John', businessArea='Customer')
  print(f"Found {results['total']} customers")

  # Search across all business areas
  all_results = client.search_all_business_areas('Smith')
  for area_name, data in all_results.items():
      print(f"{area_name}: {data['total']} results")
  ```
</CodeGroup>

## Building a Business Area Selector

Create a user interface component that lets users select a business area for filtering:

<CodeGroup>
  ```javascript JavaScript (React Example) theme={null}
  import { useState, useEffect } from 'react';

  function BusinessAreaSelector({ client, onSelect }) {
    const [businessAreas, setBusinessAreas] = useState([]);
    const [selected, setSelected] = useState('all');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
      async function loadBusinessAreas() {
        try {
          const areas = await client.getActiveBusinessAreas();
          setBusinessAreas(areas);
        } catch (error) {
          console.error('Failed to load business areas:', error);
        } finally {
          setLoading(false);
        }
      }
      loadBusinessAreas();
    }, [client]);

    const handleChange = (event) => {
      const value = event.target.value;
      setSelected(value);
      onSelect(value === 'all' ? null : value);
    };

    if (loading) return <span>Loading...</span>;

    return (
      <select value={selected} onChange={handleChange}>
        <option value="all">All Business Areas</option>
        {businessAreas.map(area => (
          <option key={area.businessAreaId} value={area.name}>
            {area.name}
          </option>
        ))}
      </select>
    );
  }
  ```

  ```python Python (Flask Example) theme={null}
  import os

  from flask import Flask, render_template, jsonify

  app = Flask(__name__)
  client = PretectumClient(os.environ['PRETECTUM_API_KEY'])

  @app.route('/api/business-areas')
  def get_business_areas():
      """API endpoint to get business areas for frontend dropdown."""
      try:
          areas = client.get_active_business_areas()
          return jsonify([
              {
                  'id': area['businessAreaId'],
                  'name': area['name'],
                  'description': area['description']
              }
              for area in areas
          ])
      except Exception as e:
          return jsonify({'error': str(e)}), 500

  @app.route('/api/search')
  def search():
      """Search endpoint that accepts business area filter."""
      from flask import request

      query = request.args.get('query', '')
      business_area = request.args.get('businessArea')

      try:
          options = {}
          if business_area and business_area != 'all':
              options['businessArea'] = business_area

          results = client.search(query, **options)
          return jsonify(results)
      except Exception as e:
          return jsonify({'error': str(e)}), 500
  ```
</CodeGroup>

## Error Handling

Handle common errors when working with business areas:

<CodeGroup>
  ```javascript JavaScript theme={null}
  async function safeGetBusinessAreas(client) {
    try {
      return await client.getBusinessAreas();
    } catch (error) {
      if (error.message.includes('401')) {
        // Token expired, re-authenticate and retry
        await client.authenticate();
        return await client.getBusinessAreas();
      }
      if (error.message.includes('403')) {
        console.error('No permission to access business areas');
        return [];
      }
      throw error;
    }
  }
  ```

  ```python Python theme={null}
  def safe_get_business_areas(client):
      try:
          return client.get_business_areas()
      except requests.exceptions.HTTPError as e:
          if e.response.status_code == 401:
              # Token expired, re-authenticate and retry
              client.authenticate()
              return client.get_business_areas()
          elif e.response.status_code == 403:
              print('No permission to access business areas')
              return []
          raise
  ```
</CodeGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Cache Business Areas">
    Business areas change infrequently. Cache the response locally and refresh periodically rather than fetching on every request:

    ```javascript theme={null}
    // Refresh every 5 minutes
    const CACHE_TTL = 5 * 60 * 1000;
    let cachedAt = 0;

    async function getCachedBusinessAreas() {
      if (Date.now() - cachedAt > CACHE_TTL) {
        await client.getBusinessAreas(true);
        cachedAt = Date.now();
      }
      return client.businessAreas;
    }
    ```
  </Accordion>

  <Accordion title="Filter by Active Status">
    Only show active business areas in user-facing interfaces:

    ```python theme={null}
    active_areas = [
        area for area in business_areas
        if area.get('active', False)
    ]
    ```
  </Accordion>

  <Accordion title="Validate Before Search">
    Validate that the user has access to a business area before attempting to search:

    ```javascript theme={null}
    if (businessArea && !await client.hasAccessTo(businessArea)) {
      throw new Error('Access denied to this business area');
    }
    ```
  </Accordion>

  <Accordion title="Use Names, Not IDs">
    When filtering searches, use the `name` field, not the `businessAreaId`:

    ```bash theme={null}
    # Correct - use name
    ?businessArea=Customer

    # Incorrect - don't use ID
    ?businessArea=20240115103000123a1b2c3d4e5f6789012345678901234
    ```
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="code" href="/api-reference/business-areas/list">
    View the complete Business Areas API reference
  </Card>

  <Card title="Search Data Objects" icon="magnifying-glass" href="/guides/dataobjects/search">
    Learn how to search within business areas
  </Card>

  <Card title="Authentication" icon="key" href="/api-reference/authentication/api-keys">
    Create and manage the keys that authenticate your calls
  </Card>

  <Card title="Search API Reference" icon="book" href="/api-reference/dataobjects/search">
    Complete search API documentation
  </Card>
</CardGroup>
