# Generic Settlements

## About Generic Settlements

A Generic Settlement is a data structure used to clear financial transactions between financially relevant parties.
It's a flexible, extensible structure for representing settlement data in a standardized format that can be process directly,
eliminating the need for custom integration modules.
The settlement also documents the resulting General Ledger entries.  

Settlements are processed atomically — they either succeed completely or fail entirely, ensuring data integrity.
The Clearing system supports several settlement variants, but each requires custom mapping logic to transform
external data into clearing-compatible structures. The mapping logic needs to be configured by Entur before the
settlements is submitted.

This document focuses on submitting Generic Settlements as supported by the Clearing API.

:::note
Settlement clearing is a complex topic requiring solid understanding of accounting principles, VAT regulations,
business requirements, and configuration of the Clearing system.
 
This guide enables developers to submit Generic Settlements but does not cover the full scope of settlement
clearing. Developers must collaborate closely with the Chart of Accounts administrator to ensure proper
modelling of the data to be cleared.
:::


## Settlement Structure

A Settlement can model any type of financial transaction data, not limited to fare product sales. Relevant use cases 
include:

* Cash Deposit transactions
* Settlement corrections
* Payment provider reconciliation
* Third-party marketplace transactions
* Revenue sharing agreements
* Sales commission calculations

The structure is designed to support wide number of clearing mechanisms, with extensibility for future requirements.

The following diagram illustrates the hierarchical structure of a Settlement:

```mermaid
graph TD
A[Settlement<br/>Point Of Sale: POS:OsloS<br/>Settlement Number: 3<br/>Distribution Channel Id: DCI:App]
A --> B1[Transaction<br/>type: SALES]
A --> B2[Transaction<br/>type: PAYMENT]
A --> B3[Transaction<br/>type: ...]
B1 --> C1[Annex<br/>...]
B1 --> C2[Annex<br/>ID: SalesPackage:123<br/>attributes:<br/>keyB=valueB<br/>context: keyF=valueF]
C2 --> D1[Parameter<br/>ID: Discount:Child<br/>attributes:<br/>keyC=valueC]
C2 --> C3[Annex<br/>ID: Product:345<br/>attributes:<br/>keyD=valueD<br/>context: keyG=valueG]
C2 --> D2[Annex<br/>ID: Product:456<br/>attributes:<br/>keyE=valueE]
C2 --> D3[Annex<br/>...]
C3 --> D4[Annex<br/>...]
B2 --> C4[Annex<br/>...]


classDef settlStyle fill:#e1f5ff,stroke:#333,stroke-width:2px, color:#000
classDef transStyle fill:#ffffff,stroke:#333,stroke-width:2px, color:#000
classDef annexStyle fill:#fff2cc,stroke:#333,stroke-width:2px, color:#000
classDef paramStyle fill:#d9ead3,stroke:#333,stroke-width:2px, color:#000


class A settlStyle
class B1,B2,B3 transStyle
class C1,C2,C3,C4,D2,D3,D4 annexStyle
class D1 paramStyle

```

### Structure Overview

Settlements consist of hierarchical elements — Transactions, Annexes, and Parameters — each with unique identifiers and 
attributes that provide additional context for clearing and reporting.

The "Generic" designation reflects the structure's ability to model any type of settlement data, not just fare products. 
This flexibility enables the Clearing system to process diverse financial scenarios through a standardized format.

```mermaid
classDiagram
    direction TB
    class PersistedSettlement {
        String posRef
        String distributionChannelRef
        String settlementNumber
        LocalDate settlementDate
        String correctionFor
        String eksterntOppgjNr
        Map context
    }

    class PersistedTransaction {
        +String transactionType
        +String JSON
    }

    class ParsedAnnex {
        Boolean ?cancel
        BigDecimal priceContribution
        BigDecimal ?foreignAmount
        String ?guid
        String annexRef
        Map ?attributes
        String ?description
        Map ?context
        BigDecimal ?price
    }

    PersistedSettlement "1" --* "0..1" PersistedTransaction : persisted transactions
    PersistedTransaction "1" --* "1..n" ParsedAnnex : parsed annexes
    ParsedAnnex "1" --* "0..n" ParsedAnnex : parameters
    ParsedAnnex "1" --* "0..n" ParsedAnnex : subannexes (recursive)

    class PersistedSettlement:::transStyle
    class PersistedTransaction:::persistedStyle
    class ParsedAnnex:::annexStyle
```

### Persistent Storage and Transaction Boundaries
  
`PersistedSettlement` and `PersistedTransaction` represent settlements and transactions as stored in the Clearing system. These 
define the atomic units of work for settlement processing and establish important operational boundaries for API integration.

Transaction content is stored as JSON, enabling the flexible structure that makes Generic Settlements possible. The 
key distinction between persistent and parsed structures lies in their identity management:

**Settlement processing guarantees:**

- Settlements are processed atomically — they either succeed completely or fail entirely (COMMIT or ROLLBACK semantics)
- Individual `PersistedTransaction` entries can be replaced through correction settlements to resolve processing failures
- Corrections cannot target individual annexes or parameters within the JSON structure, only complete transactions 
can be replaced
- Annexes may include custom GUIDs in the incoming settlement for external tracking purposes
- The Clearing system assigns transient GUIDs to all annexes without client provided GUID, useful for aggregation and reporting

**Key point:** Settlement and transaction identities are persistent and stable across systems (GUI, API, logs). 
Annex identities within the JSON structure are transient unless explicitly provided as GUIDs by the client.

### Structure Inheritance

The Generic Settlement structure uses inheritance to propagate attributes and context values through the hierarchy. 
The following overview is essential to understand the importance of constructing settlements correctly.

**Inheritance rules:**

- **Annex identity inheritance:** All annex IDs are inherited from parent annexes and automatically added to child annex attributes
- **Parameter propagation:** Parameters add their ID, attributes, and context values to their associated annex
- **Recursive attribute inheritance:** All annex attributes and context values cascade recursively from parent to child annexes

**Benefits:**

This inheritance model enables concise settlement representation by sharing common data across hierarchies, reducing 
redundancy and simplifying structure while maintaining full context at every level.

From the example above, the effective attributes and context for annex `Product:345` are:
- **Attributes:**
  - ids:
    - POS:OsloS
    - DCI:App
    - id=Product:345
    - id=SalesPackage:123
    - id=Discount:Child
  - keyB=valueB
  - keyC=valueC
  - keyD=valueD
- **Context:**
  - keyF=valueF
  - keyG=valueG

Note that keyE=valueE is not included, as it belongs to sibling annex `Product:456` and does not propagate to 
`Product:345`.

The inheritance of attributes in particular enables clearing rules to target specific combinations of annexes and 
parameters, such as applying custom logic when `Product:345` appears under discount `Discount:Child` within the 
context of `SalesPackage:123`.

:::note
The entire settlement is during the normalization phase of the clearing process modelled as a single hierarchical 
tree structure. The settlement itself appears to the clearing engine as the root of a single annex.

This inheritance model is the core mechanism that enables the Clearing system to flatten hierarchical tree structures into tabular 
rows for clearing and reporting, where each row contains the complete inherited context from its ancestor chain.
Each possible path from the root annex to a leaf annex represents a potential row in the flattened dataset.
:::

## Example: Birthday Package Settlement

The following example demonstrates a Generic Settlement for a complex multi-party transaction; a birthday package 
sale at ACME Cafe. This example deliberately uses a non-transport scenario to illustrate the structure's flexibility 
beyond fare products.

**Business scenario:**

ACME Cafe sells a birthday package combining products from partners Baker Hansen (BKH) and The Coffee Experts (CFE) 
with entertainment services provided by external clown providers. The sale includes:

- A seasonal Christmas campaign discount on all packages
- Senior citizen rebates
- Room rental fees for hosting the party
- A composite product sourced partly from external partners (BKH and CFE)


```mermaid
graph TD
    S["Settlement<br/>posRef: ACM:Pos:1<br/>settlementNumber: 31<br/>settlementDate: 2025-08-02"]
    
    T1["Transaction<br/>ACMSALESPACKAGE<br/>(sumTotal: 600.00)"]
    T2["Transaction<br/>ACMPAY<br/>(sumTotal: 600.00)"]
    
    A1["Annex<br/>ACM:SalesPackage:Birthday<br/>priceContrib: -0.01"]
    A2["Annex<br/>ACM:Payment:Payment<br/>priceContrib: 600.00<br/>paymentType: CASH"]
    
    P1["Parameter<br/>ACM:Campaign:Christmas2025<br/>priceContrib: -100.00"]
    P2["Parameter<br/>ACM:Fee:RoomRental<br/>priceContrib: 200.00"]
    
    SA1["Sub-Annex<br/>ACM:Product:CoffeeAndCake<br/>priceContrib: 0.00"]
    SA2["Sub-Annex<br/>ACM:Service:Clown<br/>priceContrib: 500.01<br/>clownProvider: ACM:HireService:ClownServicesLtd"]
    
    P3["Parameter<br/>ACM:Discount:Senior<br/>priceContrib: -10.00"]
    
    SSA1["Sub-Annex<br/>CFE:Product:Coffee<br/>priceContrib: 20.00"]
    SSA2["Sub-Annex<br/>BKH:Product:Cake<br/>priceContrib: 65.00"]
    SSA3["Sub-Annex<br/>ACM:Product:Milk<br/>priceContrib: 5.00"]
    SSA4["Sub-Annex<br/>BKH:Takeaway:Goodiebag<br/>priceContrib: 10.00"]
    
    S --> T1
    S --> T2
    
    T1 --> A1
    T2 --> A2
    
    A1 --> P1
    A1 --> P2
    A1 --> SA1
    A1 --> SA2
    
    SA1 --> P3
    SA1 --> SSA1
    SA1 --> SSA2
    SA1 --> SSA3
    T1 --> SSA4
    
    classDef settlStyle fill:#e1f5ff,stroke:#333,stroke-width:2px, color:#000
    classDef transStyle fill:#ffffff,stroke:#333,stroke-width:2px, color:#000
    classDef annexStyle fill:#fff2cc,stroke:#333,stroke-width:2px, color:#000
    classDef paramStyle fill:#d9ead3,stroke:#333,stroke-width:2px, color:#000
    
    class S settlStyle
    class T1,T2 transStyle
    class A1,A2,SA1,SA2,SSA1,SSA2,SSA3,SSA4 annexStyle
    class P1,P2,P3 paramStyle
```

The example above can be cleared by submitting the following JSON representation.

```json
{
  "posRef": "ACM:Pos:1",
  "distributionChannelRef": "ACM:DistributionChannel:Cafe",
  "settlementNo": 36,
  "settlementDate": "2025-08-02",
  "comments": [{"comment":"One of the 100-bills looks a bit off."}],
  "context": {
    "externalBatchId": "12345"
  },
  "genericTransactions": [
    {
      "transactionType": "ACMSALESPACKAGE",
      "genericAnnexes": [
        {
          "annexRef": "ACM:SalesPackage:Birthday",
          "description": "Birthday package",
          "priceContribution": {
            "amount": "-0.01"
          },
          "parameters": [
            {
              "annexRef": "ACM:Campaign:Christmas2025",
              "priceContribution": {
                "amount": "-100.00",
                "taxRate": "25.00",
                "taxCode": "25"
              }
            },
            {
              "annexRef": "ACM:Fee:RoomRental",
              "priceContribution": {
                "amount": "200.00",
                "taxRate": "12.00",
                "taxCode": "12"
              },
              "context": {
                "roomNumber": "42",
                "numberOfHours": 4
              }
            }
          ],
          "subAnnexes": [
            {
              "annexRef": "ACM:Product:CoffeeAndCake",
              "priceContribution": {
                "amount": "0.00",
                "taxRate": "15.00",
                "taxCode": "15",
                "currency": "NOK"
              },
              "parameters": [
                {
                  "annexRef": "ACM:Discount:Senior",
                  "priceContribution": {
                    "amount": "-10.00",
                    "taxRate": "25.00",
                    "taxCode": "25",
                    "currency": "NOK"
                  },
                  "context": {
                  }
                }
              ],
              "subAnnexes": [
                {
                  "annexRef": "CFE:Product:Coffee",
                  "priceContribution": {
                    "amount": "20.00",
                    "taxRate": "25.00",
                    "taxCode": "25",
                    "currency": "NOK"
                  }
                },
                {
                  "annexRef": "BKH:Product:Cake",
                  "priceContribution": {
                    "amount": "65.00",
                    "taxRate": "25.00",
                    "taxCode": "25",
                    "currency": "NOK"
                  }
                },
                {
                  "annexRef": "ACM:Product:Milk",
                  "priceContribution": {
                    "amount": "5.00",
                    "taxRate": "25.00",
                    "taxCode": "25",
                    "currency": "NOK"
                  }
                }
              ]
            },
            {
              "annexRef": "ACM:Service:Clown",
              "attributes": {
                "clownProvider": "ACM:HireService:ClownServicesLtd"
              },
              "priceContribution": {
                "amount": "500.01",
                "taxRate": "12.00",
                "taxCode": "12",
                "currency": "NOK"
              },
              "context": {
                "clownName": "Bubbles"
              }

            }
          ]
        },
        {
          "annexRef": "BKH:Takeaway:Goodiebag",
          "priceContribution": {
            "amount": "10.00",
            "taxRate": "15.00",
            "taxCode": "15",
            "currency": "NOK"
          }
        }
      ]
    },
    {
      "transactionType": "ACMPAY",
      "genericAnnexes": [
        {
          "annexRef": "ACM:Payment:Payment",
          "priceContribution": {
            "amount": "600.00",
            "taxRate": "0.00",
            "taxCode": "00",
            "currency": "NOK"
          },
          "attributes": {
            "paymentType": "CASH"
          }
        }
      ]
    }
  ]
}
```

### Understanding the Settlement Structure
  
  **Transaction composition:**
  - Settlements contain one or more transaction types, each representing a distinct business operation
  - This example includes `ACMSALESPACKAGE` (representing the sale) and `ACMPAY` (representing payment collection)
  - Each transaction type may have specific clearing and reporting requirements
  
  **Hierarchical relationships:**
  - Parameters apply to their parent annex and cascade to all nested sub-annexes
  - This hierarchical structure enables proportional distribution of adjustments (discounts, fees) across multiple components
  - Annexes can be nested to model complex product structures
  
  **Identifiers and price contributions:**
  - Each annex and parameter requires a unique `annexRef` identifier following the namespace format (`NAMESPACE:TYPE:IDENTIFIER`)
  - Price contributions can be positive (revenue, fees) or negative (discounts, refunds)
  - Transaction totals equal the sum of all annex and parameter price contributions
  
  **Tax handling:**
  - Different annexes may have distinct tax rates and codes based on product/service classification
  - Tax information (`taxRate`, `taxCode`) is specified per price contribution
  - In this example, tax rates range from 0% (not applicable for payments) to 25% (standard VAT)
  - Discounts and fees may span multiple tax rates, making the clearing more complex
  
  **Price adjustments:**
  - The top-level annex includes a `-0.01` price contribution to round the total to a whole number
  - This adjustment technique ensures customer-facing prices match business requirements
  
  **Extensibility:**
  - Use `attributes` to provide data that influences clearing logic (e.g., `paymentType`, `clownProvider`)
  - Use `context` to include supplementary reporting data (e.g., `roomNumber`, `clownName`)
  - Context values must be explicitly referenced in reporting templates to appear in reports

### Clearing Flexibility and Business Logic
  
  The settlement structure provides _information_ for clearing but does not dictate clearing behavior. Actual clearing 
  logic is determined by Clearing Mappings configured in the Clearing system. This is done by Entur.
  
  **Example clearing scenarios:**
  
  - **Context-driven reporting:** The room rental fee parameter includes `roomNumber` and `numberOfHours` context values 
    that enable detailed facility utilization reports
  - **Provider-specific routing:** The clown service annex uses the `clownProvider` attribute to support separate 
    clearing agreements with different service providers
  - **Partner revenue sharing:** External partner products (BKH, CFE) are modeled as sub-annexes, enabling accurate 
    revenue distribution and inter-company accounting between ACME Cafe and its suppliers
  - **Commission extraction:** Clearing rules can calculate and allocate commissions on partner product sales, 
    ensuring ACME receives their contractual revenue share
  - **Proportional adjustments:** The senior discount parameter applies to the `CoffeeAndCake` annex and cascades to 
    all sub-annexes, automatically distributing the discount across multiple partners and tax codes weighted by their 
    respective `priceContribution` values

## Settlement Corrections

Any modification to previously submitted transactions requires a correction settlement. Due to the batched 
processing architecture, settlements may have already been cleared and reported before corrections are identified, 
making direct modification of previously submitted settlements impossible.

**Correction mechanism:**

Corrections use a two-step approach within a single settlement:

1. **Reversal:** A complete reversal of the original transaction (DEBIT and CREDIT switched), negating the original entry in the General Ledger
2. **Replacement:** A new transaction containing the corrected data, effectively superseding the original

**Refunds as corrections:**

Refunds follow the same pattern but serve a different business purpose:

1. **Reversal:** A complete reversal of the original sales transaction (DEBIT and CREDIT switched), negating the original entry
2. **Credit:** A new credit transaction that returns funds to the customer

**Implementation:**

- Set the `cancel` field to `true` on the root annex in the reversal transaction
- Include both the cancellation and replacement transactions in the same settlement submission
- Optionally reference the original settlement using the `correctionFor` field at the settlement level

**Key point:** Corrections must include both the reversal and optional replacement within a single settlement to 
maintain proper accounting and audit trails.

## Client Responsibilities

Clients submitting settlements act as **Settlement Agents** in Entur clearing terminology. A Settlement Agent is the 
authenticated organization responsible for submitting settlements on behalf of one or more clearing partners.

**Settlement Agent scope:**

Typically, a Settlement Agent represents only itself. However, in marketplace or platform scenarios, a single 
Settlement Agent may represent multiple partners. For example, Entur acts as the Settlement Agent for all partner 
products sold through its platform.

**Delegated responsibilities:**

The Settlement Agent is a trusted role with delegated responsibility for ensuring settlement accuracy and completeness. 
This includes:

- **Structural correctness:** Verify that settlements are properly formatted and balanced
- **Authorization:** Ensure proper authentication and authorization for all submitted data
- **Data scope:** Include only information relevant to the Agent and its partners
- **Validation:** Confirm that point of sale references, distribution channels, VAT codes, and tax rates are correct
- **Legal compliance:** Recognize that submitted settlements constitute legal vouchers for accounting purposes

**Validation and correction:**

Depending on incoming data quality, Settlement Agents may need to implement local staging areas for validation and 
correction before submission to the Clearing system.

:::info
The Clearing system performs validation during settlement processing, but the failed settlement lists is not currently 
self-serviced. Any settlement failing clearing requires manual analysis and correction by the Chart of Accounts 
Administrator in cooperation with the Settlement Agent.
:::

:::warning
Under Norwegian accounting regulations, submitted settlements are considered vouchers for accounting data. 
The Settlement Agent assumes full responsibility for data accuracy, completeness, and compliance with accounting and 
VAT reporting requirements.
:::

## Best Practices

Multiple approaches exist for modeling settlements. Consider these best practices when creating Generic Settlements:

### Settlements Must Be Balanced

A settlement must ultimately balance (SUM DEBIT = SUM CREDIT). For example, the Payment transaction must accompany the 
Sales Package transaction within the same settlement. The specific balancing mechanism depends on your business 
scenario, the clearing configuration and accounting rules configured.

**Key point:** Submitting separate settlements for each transaction type will likely fail, as each settlement must be 
balanced independently.

### Transaction Types Should Represent Logical Units of Work

Transaction types define logical units of work with shared context. For example, a sales package transaction 
(`ACMSALESPACKAGE`) and its associated payment transaction (`ACMPAY`) are separate transaction types with distinct 
clearing and reporting requirements. 
Each transaction type typically has several associated reporting templates showing columns relevant to that 
transaction's context.

:::info
New transaction types must be registered by the Clearing administrator and assigned to all relevant Charts of Accounts 
before they can be submitted in settlements.
:::

**Key point:** New transaction types require careful analysis and registration before use.

### Hierarchical vs. Flat Annex Structures

Each price contribution can be represented as a separate annex directly under the transaction. However, this flat 
structure eliminates the ability to leverage annex relationships when defining clearing rules.

For example, clearing rules can target specific parent-child annex combinations, such as applying custom accounting 
logic when `ACM:HireService:ClownServicesLtd` appears under `ACM:Campaign:Christmas2025`.

The hierarchical structure also enables proportional distribution of rebates and discounts across multiple annexes 
based on their relative price contributions.

**Key point:** Design the annex structure to match your clearing logic requirements. Use hierarchical nesting when 
clearing rules need to consider annex relationships.

### Deep Annex Structures vs. Multiple Transactions

In our example, the takeaway goodie bag (`BKH:Takeaway:Goodiebag`) is modeled as a separate annex under the birthday 
sales package transaction (`ACM:SalesPackage:Birthday`). However, this structure may be problematic if the cafe needs 
to refund the goodie bag independently of the rest of the birthday package.

**Key point:** Split annexes into separate transactions when they require independent correction or refund capabilities.

### Annex vs Parameter
Parameters are functionally similar to simply adding a parent annex with equivalent values, but parameters 
exhibit distinct inheritance behavior:

**Bidirectional inheritance:**
- The parameter inherits attributes and context from its associated annex (child-like behavior)
- The associated annex inherits values from the parameter (parent-like behavior)

**Clearing perspective:**
- Parameters can be cleared as child annexes of their associated annex
- Associated annexes can simultaneously be cleared as child annexes of their parameters

This bidirectional relationship creates a unique inheritance pattern. While the recursive structure technically 
allows parameters to have sub-annexes, this practice should be avoided.

**Key point:** Use parameters as modifiers (such as discounts, fees, or adjustments) applied to robust  
annex structures rather than creating structural variations for each modification. This enables clearer semantics and
better reuse of existing clearing logic.

### Attributes vs. Context

Use **attributes** for data that drives clearing logic, such as payment types or service provider identifiers. 
Use **context** for supplementary information needed for reporting or analysis that doesn't affect clearing rules.

**Important considerations about the Clearing system:**

- It's _not_ a general-purpose data store. Include only essential reporting data in context: external references 
  or critical metadata, not large data payloads.
- It may produce datasets containing the context values, but context _not relevant for clearing_ should be joined 
  with these datasets locally using external references from the datasets, not embedded directly in the settlement.
- Context values are not automatically included in reports. Each context key must be explicitly referenced in a 
  reporting template column.
- Several context keys are already standardized and must be used as specified to ensure compatibility with existing 
  reports. Consult the support team for details on standardized context keys.

**Key point:** Use attributes for clearing logic and context for reporting. Collaborate with the Chart of 
Accounts administrator when designing context for new transaction types to maintain compatibility with existing 
reporting templates.

### Generic Settlements and High Transaction Volumes

The Clearing system can process large volumes of transactions efficiently. However, the Generic Settlement API is optimized for 
moderate-sized settlements rather than bulk processing.

Submitting settlements containing thousands of transactions and multi-megabyte JSON payloads introduces reliability and 
performance risks. Instead, distribute high-volume transaction data across multiple smaller settlements submitted at 
regular intervals.

For scenarios requiring continuous high-volume processing, a streaming-based integration module may be more appropriate.
This capability will be developed based on identified use cases.

**Key point:** Split high-volume transaction data into multiple smaller settlements.

### Resubmitting Settlements

The Clearing system supports settlement resubmission using the same `posRef` and `settlementNumber` combination. If a settlement with 
matching identifiers has already been successfully received, the resubmission will be rejected to prevent duplicate 
processing.

**Client responsibilities:**
- Generate sequential settlement numbers for each settlement submission
- Implement retry logic to resubmit failed settlements (within reasonable limits)

Note that the duplicate detection mechanism is limited to settlements submitted within the last 7 days, it is
only intended to handle transient submission failures. Older duplicates will be detected and failed during clearing.

**Key point:** Settlement identifiers (`posRef` + `settlementNumber`) must be unique and sequential. Resubmit failed 
settlements using the same identifiers; do not create new settlement numbers for retry attempts.

### Identifier Requirements and Namespacing

The Clearing system is designed to process settlements from partners who may not use the broader Entur platform. This
necessitates a highly flexible approach to identifier management.

**Namespaced References ("refs"):**

All identifier fields suffixed with `Ref` (such as `posRef`, `distributionChannelRef`, `annexRef`, etc.) must be 
globally unique. This is achieved by enforcing a namespaced format: `NAMESPACE:TYPE:IDENTIFIER`. For example: 
`ACM:SalesPackage:Birthday`. Each namespace must be registered with Entur prior to use.

:::info
The Clearing system maintains an internal mapping of refs to human-readable names, so descriptive labels are not required
in the settlement payload.
:::

**Attribute Identifiers:**

Identifiers used within the `attributes` map (e.g., `paymentType`, `clownProvider`) are not required to be globally 
unique or follow a specific format. These are key-value pairs that may be referenced in clearing logic. Keys and values 
should be concise, meaningful strings without special characters. The value may also be a namespaced ref.

**Context Identifiers:**

Identifiers within the `context` map (e.g., `externalBatchId`, `roomNumber`) are also not required to be globally unique 
or follow a specific format. These values typically provide supplementary metadata for reporting or audit purposes.

:::warning
When attribute or context values represent entities shared across partners (such as `clownProvider` in revenue-sharing 
scenarios), naming conventions must be coordinated to ensure consistent interpretation in clearing logic.
:::

**Summary:**  
- All refs must be globally unique and namespaced.
- Attribute and context identifiers are flexible but should remain meaningful and consistent.
- Any ref can be assigned a display name for use in the GUI and reports.

### Validation and Schema Flexibility

The Generic Settlement structure provides flexibility but does not accept arbitrary data structures. While basic 
structural validation occurs during submission, most validation is deferred to the asynchronous clearing process.

The Clearing system performs comprehensive consistency checks during clearing ("mottakskontroll"). Any validation
failures cause the entire settlement to be rejected, requiring manual intervention.

**Validation considerations:**

- Schema validation is intentionally minimal. The effective "schema" is defined implicitly by clearing mappings and 
  reporting templates configured in the Clearing system.
- As common patterns emerge, the system may introduce stricter validation for specific context values to ensure consistent 
  reporting, especially for transaction types shared across multiple Charts of Accounts.
- Any changes to validation that is not compatible with existing settlements will be carefully analysed and 
  communicated in advance.
- Incorrect structures may pass initial validation but fail during clearing or produce invalid reports.

**Key point:** Thoroughly validate settlement structures before submitting large volumes. Test with small batches first 
to avoid creating backlogs of failed settlements that require manual correction by the Chart of Accounts administrator.

**Key point:** Settlements may be unbalanced or structurally incorrect for any number of reasons (client bugs, 
delays, infrastructure issues etc). The Client must implement local validation and correction facilities before 
submission.
