# Marketplace Settlement Ledger Normalizer (`mehdi_badawi/settlement-ledger-normalizer`) Actor

Convert marketplace settlement CSV, TSV, or JSON exports into exact, currency-separated ledger rows with source provenance. Missing amounts stay unresolved instead of being guessed.

- **URL**: https://apify.com/mehdi\_badawi/settlement-ledger-normalizer.md
- **Developed by:** [Mehdi Badawi](https://apify.com/mehdi_badawi) (community)
- **Categories:** E-commerce, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 reconciled ledger rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Marketplace Settlement Ledger Normalizer

Convert settlement CSV, TSV, or JSON exports into exact, currency-separated
ledger rows with source provenance. Missing amounts stay unresolved instead of
being guessed or forced into a balance.

### Start in 30 seconds

1. Select **Try for free** and run the packaged demonstration fixture.
2. Paste or upload an authorized settlement export.
3. Export normalized ledger rows and review the reconciliation summary.

**Price:** $0.001 per reconciled row, plus a $0.00005 start event. Unresolved
rows, failed runs, and the demo fixture are free.

The Actor does not connect to marketplaces or banks, and its output is not
accounting, tax, or compliance approval.

### Overview & Background (W2-18)

Marketplace settlement reports present major hurdles for self-bookkeeping sellers and ecommerce bookkeepers:

- Complex withholding and release mechanics (e.g., Amazon DD+7 reserve policies).
- Unexplained fee and debit line items (e.g. Amazon seller forum reports of unexpected "OTHER" charges).
- Opaque fee breakdowns spanning FBA fulfillment, weight handling, storage, advertising, refund commissions, and marketplace facilitator tax withholdings.
- Format breaks and silent omissions in spreadsheets leading to balance mismatches.

This Actor accepts uploaded settlement files and deterministically produces an itemized normalized ledger, verifies stated deposit totals against item sums, and explicitly buckets unresolved items without guessing or forcing matches.

### Core Guarantees

1. **Stateless Processing**: Operates entirely in-memory with file-in and ledger-out semantics. No credentials, tokens, external databases, or third-party connections required.
2. **Exact Decimal Representation**: Money is represented strictly with exact integer minor units (BigInt cents) and decimal-safe strings. Zero IEEE-754 floating-point rounding errors.
3. **Zero Silent Drops, Zero Forced Matches**: Every row in the input file is either matched to standard ledger categories or explicitly quarantined into a labeled unresolved bucket (e.g. `unresolved_unexplained_charge`, `unresolved_unknown_type`, `unresolved_missing_reference`).
4. **Complete Source Provenance**: Every generated ledger line retains the 1-based source file row number, original transaction identifier, raw input record, and matching rule identifier.
5. **Reconciliation Balancing**: Stated deposit totals (from settlement file headers or user declaration) are compared against the exact sum of line items. If a discrepancy exists, an explicit balancing gap line is emitted under `unresolved_reconciliation_gap` rather than silently ignored or force-allocated.

### Supported Formats & Categories

#### Input Formats

- **Delimited Text (TSV / CSV)**: Generic multi-column settlement records. Quoted or multiline CSV must be qualified before use.
- **JSON Array**: Array of settlement record objects.

#### Standard Normalized Categories

- `revenue`: Product principal sales, shipping revenue, gift wrap revenue.
- `fee`: Referral commission, FBA per-unit fulfillment, weight handling, monthly subscriptions, storage, return postage, removal order disposal, PPC advertising.
- `refund`: Return principal refunds, referral fee rebates, refund administration fees, restocking fee credits.
- `tax`: Sales tax collected, marketplace facilitator tax withheld at source.
- `promotion`: Merchant promotion discounts, shipping concessions.
- `reserve`: Reserve withholdings (e.g. DD+7 policy hold) and prior reserve releases.
- `adjustment`: Warehouse lost/damaged inventory reimbursements, customer concessions, foreign exchange adjustments, liquidation proceeds.
- `transfer`: Net disbursement bank transfer lines.
- `unresolved`: Explicit buckets for items requiring bookkeeper review.

#### Explicit Unresolved Buckets

- `unresolved_unexplained_charge`: Labeled "Other" or "OTHER" without item details.
- `unresolved_unknown_type`: Unrecognized transaction type strings.
- `unresolved_missing_reference`: Fee or adjustment missing mandatory order or adjustment reference.
- `unresolved_malformed_amount`: Non-numeric or invalid amount strings.
- `memo_non_financial`: Informational zero-value lines.
- `unresolved_reconciliation_gap`: Balancing gap when stated deposit differs from line sums.

### Outputs

- **Default Dataset**: One item per normalized ledger line.
- **Key-Value Store (`OUTPUT`)**: Run envelope with stated deposit, calculated total, exact delta, category totals, unresolved bucket breakdown, and audit counts.
- **Key-Value Store (`LEDGER`)**: Exportable JSON snapshot of the complete ledger.

### Local Development & Testing

Run all unit and integration tests using Node's built-in test runner (no external test dependencies):

```bash
npm test
```

Execute a local run with the built-in 35-row representative settlement fixture without network or Apify credentials:

```bash
npm start
```

### Non-Goals & Boundaries

- No external API integrations, banking connections, or credential storage.
- No legal, tax, or professional accounting advice or compliance certification.
- No fuzzy or forced matching on ambiguous money amounts.

Financial rows and raw source records can be sensitive. Minimize uploads,
never place customer exports in public samples, and delete datasets and stores
under the customer's retention policy. Mixed currencies remain separate and a
missing stated deposit remains unverified. Support owner: Mehdi Badawi through
the Apify Store support channel, with an initial-response target of two business
days.

# Actor input Schema

## `fileContent` (type: `string`):

Raw string content of the settlement file (TSV, CSV, or JSON). When omitted, the Actor loads the representative built-in fixture specified by fixtureName.

## `format` (type: `string`):

Settlement file format. 'auto' detects from header lines and delimiter.

## `fixtureName` (type: `string`):

Representative deterministic fixture loaded when fileContent is empty or null.

## `declaredDepositTotal` (type: `string`):

Optional stated net deposit amount from bank statement or payout advice (e.g. '1091.10'). When omitted, the Actor uses the total-amount stated in the settlement header if present.

## `declaredCurrency` (type: `string`):

Three-letter ISO currency code (e.g. 'USD', 'EUR', 'GBP').

## `settlementId` (type: `string`):

Optional settlement identifier to override or supplement the report metadata.

## `options` (type: `object`):

Optional processing flags.

## Actor input object example

```json
{
  "format": "auto",
  "fixtureName": "settlement-amazon-35-rows",
  "declaredCurrency": "USD"
}
```

# Actor output Schema

## `ledgerRows` (type: `string`):

One dataset item per normalized ledger line: provenance (source line number, raw record), exact decimal money, classification category/subcategory, and reconciliation state.

## `runOutput` (type: `string`):

The settlement-level reconciliation envelope: runStatus, stated vs calculated deposit totals, exact delta, category totals, unresolved bucket breakdown, and audit counts.

## `fullLedger` (type: `string`):

Exportable snapshot of the full normalized ledger array and metadata.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("mehdi_badawi/settlement-ledger-normalizer").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("mehdi_badawi/settlement-ledger-normalizer").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call mehdi_badawi/settlement-ledger-normalizer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,mehdi_badawi/settlement-ledger-normalizer"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Amu5SfyNGKzdvaEFv/builds/qXQpc865gEUN4zeFM/openapi.json
