Skip to main content
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:
1

Get API Credentials

Obtain your client_id and client_secret from your Pretectum tenant administrator.
2

Obtain Access Token

Exchange your credentials for an access token using the authentication endpoint.
3

Verify Permissions

Ensure your application client has been granted access to the business areas permission.

Retrieving Business Areas

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

Basic Request

curl -X GET "https://api.pretectum.io/v1/my/businessareas" \
  -H "Authorization: your_access_token" \
  -H "Accept: application/json"

Understanding the Response

The API returns an array of business area objects:
[
  {
    "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
  }
]
FieldDescription
businessAreaIdUnique identifier for the business area
nameDisplay name used for filtering in search operations
descriptionExplanation of the business area’s purpose
activeWhether the business area is currently active
createdByUser who created the business area
updatedByUser who last modified the business area
createdDateWhen the business area was created
updatedDateWhen the business area was last modified
versionVersion number for tracking changes
Once you have the list of business areas, use the name field to filter your data object searches.

Searching Within a Business Area

# Get business areas
curl -X GET "https://api.pretectum.io/v1/my/businessareas" \
  -H "Authorization: your_access_token"

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

Complete Client Implementation

Here is a complete implementation that handles authentication, business area retrieval, and searching:
const API_BASE = 'https://api.pretectum.io';

class PretectumClient {
  constructor(clientId, clientSecret) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.accessToken = null;
    this.tokenExpiry = null;
    this.businessAreas = null;
  }

  async authenticate() {
    const response = await fetch(`${API_BASE}/oauth2/token`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        client_id: this.clientId,
        client_secret: this.clientSecret
      })
    });

    if (!response.ok) {
      throw new Error('Authentication failed');
    }

    const data = await response.json();
    this.accessToken = data.access_token;
    this.tokenExpiry = Date.now() + (data.expires_in * 1000);
  }

  async ensureAuthenticated() {
    if (!this.accessToken || Date.now() >= this.tokenExpiry) {
      await this.authenticate();
    }
  }

  async getBusinessAreas(forceRefresh = false) {
    await this.ensureAuthenticated();

    if (this.businessAreas && !forceRefresh) {
      return this.businessAreas;
    }

    const response = await fetch(`${API_BASE}/v1/my/businessareas`, {
      headers: {
        'Authorization': this.accessToken,
        '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 = {}) {
    await this.ensureAuthenticated();

    // 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.accessToken }
      }
    );

    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('your_client_id', 'your_secret');

// 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`);
}

Building a Business Area Selector

Create a user interface component that lets users select a business area for filtering:
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>
  );
}

Error Handling

Handle common errors when working with business areas:
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;
  }
}

Best Practices

Business areas change infrequently. Cache the response locally and refresh periodically rather than fetching on every request:
// 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;
}
Only show active business areas in user-facing interfaces:
active_areas = [
    area for area in business_areas
    if area.get('active', False)
]
When filtering searches, use the name field, not the businessAreaId:
# Correct - use name
?businessArea=Customer

# Incorrect - don't use ID
?businessArea=20240115103000123a1b2c3d4e5f6789012345678901234

Next Steps