# Invoice & Expense CSV Reconciler (`makentest/invoice-expense-csv-reconciler`) Actor

Reconcile invoices, payments, bank transactions, and expenses automatically. Detect duplicates, partial payments, unmatched records, and discrepancies using deterministic matching rules. Export detailed reconciliation reports and exceptions for human review in CSV, JSON, or Excel formats.

- **URL**: https://apify.com/makentest/invoice-expense-csv-reconciler.md
- **Developed by:** [Harsh Garg](https://apify.com/makentest) (community)
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1,500.00 / 1,000 completed reconciliation jobs

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

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

## Invoice & Expense CSV Reconciler

Reconcile invoice exports against bank, payment and expense exports (CSV, XLSX, JSON, Apify datasets). The Actor finds matches, partial payments, grouped settlements, duplicates, discrepancies and unmatched records, explains every decision, and routes anything ambiguous to a **human review queue**.

- Deterministic: identical files and settings give identical business results. No AI/LLM, no probabilistic scoring, no web scraping, no external calls other than the file URL you supply.
- Auditable: every allocation records the rule, evidence, amount/date differences, original and normalized references, and source file + row.
- Safe by design: nothing is paid, sent or written to an accounting system. Money is handled with exact decimal arithmetic.

> **Disclaimer.** This Actor is a reconciliation aid, not certified accounting or audit advice. Automatic matches and aging figures must be reviewed by a qualified person. The review sheet is a proposed reconciliation decision record, **not an authorization to move money**.

***

### 1. Who it is for

Bookkeepers and accounting professionals, SMBs and AP/AR teams, freelance accountants and virtual assistants, and automation agencies (n8n / Make / Zapier / Google Sheets) who import CSV or Excel exports from banks and accounting software.

Typical workflow: upload invoice + bank exports → map columns → set tolerances → **dry-run preview** → run → download reports → work through `review_sheet.csv` → re-import it on the next run.

### 2. Supported inputs

| Source mode (per file) | Input fields (prefix = `invoices`, `transactions`, `expenses`, `fx`, `review`) |
|---|---|
| Upload / public HTTPS URL | `<prefix>FileUrl` (the Apify form's upload gives a URL) |
| Pasted CSV text (max 1 MB) | `<prefix>Text` |
| Existing Apify dataset | `<prefix>DatasetId` (flat records; keys become columns) |
| Apify key-value store record | `<prefix>StoreId` + `<prefix>StoreKey` (CSV, XLSX or a JSON array of flat objects) |

Formats: **CSV** (UTF-8, UTF-8 BOM, UTF-16, Windows-1252, Latin-1; `,` `;` tab `|` delimiters), **XLSX** (cached values only; formulas, macros and external links are never executed), **JSON** records. **Not supported:** XLS, XLSM, PDF invoices, OCR, accounting-system APIs. Exactly one source mode may be set per file.

Remote URLs: HTTPS only; loopback/private/link-local/reserved/cloud-metadata addresses are rejected; DNS answers and every redirect hop are re-validated; the connection is pinned to the validated IP; timeouts, a redirect limit and a size limit apply; content type and file signature are checked; no credentials are ever forwarded. A URL that needs authentication (for example a *private* key-value-store file link) cannot be fetched this way - use the dataset or key-value-store inputs instead.

### 3. Input at a glance

**Prefilled example and automated tests.** The input form is prefilled with a small sample and `dryRun: true`, so a default Console click or an Apify automated test run is a free preview. Untick *Dry run* (or send `dryRun: false` through the API) for a real, billed job; the API default is `false`.

`.actor/input_schema.json` has five sections: **A** input files, **B** column mapping, **C** matching configuration, **D** output configuration, **E** execution and billing. Minimal API input:

```json
{
  "invoicesText": "Invoice ID,Customer,Invoice Date,Due Date,Amount,Currency,Reference\nINV-1001,Acme Ltd,2026-01-05,2026-02-04,1200.00,USD,PO-77\n",
  "transactionsText": "Date,Description,Amount,Reference,Transaction ID,Currency,Payee\n2026-01-20,Payment PO 77,1200.00,po77,T-001,USD,ACME LIMITED\n",
  "asOfDate": "2026-03-01"
}
```

#### Column mapping

Unmapped fields are auto-detected from common header names (deterministic; **ambiguous detection is an error, never a guess**). Explicit mapping always wins:

```json
{
  "invoiceMapping":     {"invoiceId": "Doc No", "party": "Customer", "invoiceDate": "Issued", "dueDate": "Due", "amount": "Total", "currency": "Ccy", "reference": "PO", "tax": "VAT"},
  "transactionMapping": {"transactionId": "Bank Ref", "date": "Booking date", "amount": "Amount", "reference": "Reference", "memo": "Narrative", "counterparty": "Payee"},
  "expenseMapping":     {"expenseId": "Receipt", "date": "Date", "vendor": "Merchant", "amount": "Amount", "category": "Category"},
  "fxMapping":          {"baseCurrency": "Base", "quoteCurrency": "Quote", "rate": "Rate", "rateDate": "Date", "convention": "Convention"}
}
```

Payment direction is **never assumed from the sign**. Choose `transactionAmountMode`: `SIGNED` (with `incomingSign` POSITIVE/NEGATIVE), `POSITIVE_WITH_TYPE` (a type column plus `creditTypeValues` / `debitTypeValues`), or `DEBIT_CREDIT_COLUMNS`. `invoiceKind` (`RECEIVABLE` = money-in settles invoices, `PAYABLE` = money-out) decides the expected direction; expenses always expect money-out. `bankPreset` offers three generic, editable layouts - **starting points, not bank-specific guarantees**.

Dates and amounts: ambiguous values (for example `03/04/2026`, or `1,234`) are rejected until you set `dateFormat` (DMY/MDY) or `decimalSeparator`.

### 4. Matching hierarchy

Rules run in this priority order. Candidate pairs are computed for **all** records first and resolved per connected component, so row order and chunk size cannot change a decision (tested).

| # | Rule id | Evidence |
|---|---|---|
| 1 | `EXACT_REFERENCE` | invoice reference == payment reference (trimmed, case-insensitive) or == reference extracted from the memo by your regex |
| 2 | `NORMALIZED_REFERENCE` | equal after normalization (case, punctuation, configurable prefixes like `INV`, leading zeros, accents) |
| 3 | `EXACT_ID_AMOUNT` | invoice identifier == payment reference |
| 4 | `VENDOR_AMOUNT_DATE` | normalized party names equal + compatible amount + payment date in the window (invoice date - tolerance … due date + tolerance) |
| 5 | `GROUPED_SETTLEMENT` | one payment settles several invoices of one party (opt-in, bounded search) |
| 6 | `AMOUNT_DATE_FALLBACK` | amount + date only (opt-in, weakest) |
| - | `MANUAL_REVIEW` | everything unresolved, conflicting, incomplete or ambiguous |

Reference rules (1-3) need a compatible direction; a reference hit in the *opposite* direction becomes a `DIRECTION_MISMATCH` exception (possible refund) and is not allocated. No probability or confidence number is produced - only the rule, the evidence list (`reference`, `id`, `vendor`, `amount`, `date`) and the reasons. `minEvidence` (default 2) is the number of independent evidence items required for an automatic match.

**Conflicts.** If several invoices compete for a payment or several payments compete for an invoice, the whole conflict goes to review with every candidate preserved. `ambiguityPolicy = BEST_EVIDENCE_IF_UNIQUE` accepts only *mutual, strictly-best* candidates (smallest amount difference, then date difference); ties are always reviewed. The first CSV row never wins by position.

**Partial payments.** Several payments against one invoice are tracked (allocated / remaining / settled status). If the sum exceeds the balance beyond tolerance, nothing is allocated and an `OVERPAYMENT` exception is raised. A single payment above the balance is likewise **never auto-allocated** (reviewing it later allocates the invoice balance and leaves the remainder unallocated and visible).

**Grouped settlement.** Depth-first search over invoices of the *same normalized party* within the payment window, limited by `maxInvoicesPerCombination` (≤ 6), `maxCandidatesPerRecord` and `maxCombinationNodes`. Multiple equally plausible combinations, a competing payment, or an exhausted search budget produce an exception - never a silent choice. No invoice is marked settled until the whole allocation is valid.

**Reference extraction regex.** `referenceRegex` is validated structurally (no nested repetition, no alternation inside repetition, no back-references or look-around, repeat counts ≤ 100, pattern ≤ 200 chars, at most one capture group) and applied to at most the first 500 characters of the memo. Example: `INV[- ]?\d{3,6}`. The original memo is always preserved.

### 5. Tolerances, adjustments and FX

- Tolerances are separate and typed: `roundingTolerance` (default 0.01), `amountTolerance`, `bankFeeTolerance`, `processorFeeTolerance` (shortfalls only), `taxTolerance` (needs a tax amount on the invoice). Fee tolerances never forgive overpayments.
- An accepted difference is recorded as an **adjustment** (`ROUNDING`, `TOLERANCE`, `BANK_FEE`, `PROCESSOR_FEE`, `BANK_AND_PROCESSOR_FEE`, `TAX_DIFFERENCE`) in `allocations.csv` and `discrepancies.csv`. Source amounts are never altered: `allocated = converted payment + adjustment`.
- **FX**: only your table (`fxText` / file / dataset / store): base, quote, rate, rate date, optional convention (`QUOTE_PER_BASE` default, `BASE_PER_QUOTE`). Rates must be positive and finite; duplicates per pair+date are rejected. `fxRateMode` selects the transaction-date rate, invoice-date rate, or latest rate; `fxDateWindowDays` allows the closest *earlier* rate within N days. A missing rate is never substituted: the case becomes a `MISSING_FX_RATE` exception. The payment is converted into the invoice's currency; the allocation shows the rate and rounding difference. No rates are fetched from the internet. Totals are reported per currency without implicit conversion.

### 6. Example

`examples/invoices.csv`, `examples/bank.csv`, `examples/sample_input.json` (run date set to 2026-03-01 for the aging):

**Before:** 6 invoices, 5 bank transactions, nothing reconciled.

**After** (real output of this Actor):

| Invoice | Payment | Rule | Allocated | Note |
|---|---|---|---|---|
| INV-1001 | T-001 | `NORMALIZED_REFERENCE` | 1200.00 | `po77` ≙ `PO-77` |
| INV-1002 | T-002 | `VENDOR_AMOUNT_DATE` | 450.50 | no reference; party + amount + date |
| INV-1003 | T-003 | `NORMALIZED_REFERENCE` | 100.00 | partial: 200.00 remaining, status `PARTIALLY_PAID` |

Exceptions: `AMBIGUOUS_MATCH` - INV-1004 and INV-1005 (both Delta Co, 80.00) compete for T-004; nothing allocated, both candidates kept for review. Unmatched: INV-1006 (40.00, no match; 91+ days), payment T-005 (333.33). Aging: 0-30 = 360.00, 91+ = 40.00 (USD).

### 7. Output files

Stored in the run's **default key-value store** (described by `.actor/key_value_store_schema.json`) (CSV/JSON, `reconciliation.xlsx` when XLSX is enabled) and the **default dataset** (rows tagged `recordType`: allocations, exceptions, unmatched_invoices, unmatched_payments, discrepancies, duplicate_invoices, duplicate_payments; dataset views are defined in `.actor/dataset_schema.json`). `RUN_SUMMARY.json` is always in the key-value store; `RUN_STATUS` is written instead when a run fails.

| File | Content |
|---|---|
| `matched.csv` | one row per invoice/expense with at least one allocation (settled/remaining, status, rules) |
| `allocations.csv` | one row per allocation: rule, evidence, both source rows, original + normalized references, allocated amounts, FX rate, amount/date differences, adjustment, explanation, warnings |
| `unmatched_invoices.csv` | open / partially paid / excluded documents with reason (`NO_MATCH_FOUND`, `IN_EXCEPTION_QUEUE`, `PARTIALLY_PAID`, `DUPLICATE_RECORD`, `NON_POSITIVE_DOCUMENT`) |
| `unmatched_payments.csv` | unallocated or partially allocated payments with unallocated amount and reason |
| `exceptions.csv` | all review items (category, documents, payments, explanation, proposed action, review status) |
| `duplicate_invoices.csv`, `duplicate_payments.csv` | duplicate groups: exact id, same id with conflicting values, same party/amount/date, similar within tolerance. Never deleted. |
| `discrepancies.csv` | adjustments, FX conversions, partial payments, overpayments, missing FX, direction mismatches |
| `aging_report.csv` | invoice-level aging + totals by currency in `RUN_SUMMARY.json` |
| `review_sheet.csv` | the human review queue (section 8) |
| `RUN_SUMMARY.json` | counts, totals by currency, rules applied, limits reached, warnings (max 200 recorded), stage durations, billing, preview flag, disclaimer |

Column lists are fixed and ordered (see `src/reporting.py`): allocations 37 columns, matched 14, unmatched invoices 15, unmatched payments 15, exceptions 10, duplicates 8, discrepancies 8, aging 16. Rows are sorted deterministically; nulls are explicit (`null` in JSON, empty in CSV); amounts are plain decimal strings padded to the currency's minor units (source precision is never rounded).

**Spreadsheet safety.** In CSV and XLSX, cells beginning with `=`, `@`, tab/CR/LF, or `+`/`-` followed by non-numeric text are prefixed with `'` so they cannot execute as formulas. JSON and the canonical records keep the original value.

**Detail toggles.** `includeUnmatched`, `includeDuplicates`, `includeAging`, `includeExplanations` (explanation/warning/proposed-action columns), `includeSourceRows` (source file/row columns) and `detailLevel` (`SUMMARY` = exceptions + review sheet only). `review_sheet.csv` is never trimmed.

### 7b. Standby HTTP API (Endpoints tab) and storage schemas

The Actor can run in two ways: a normal batch run (everything above) or Apify **Standby mode**, where it stays up as a small HTTP API. Normal runs from the Console, API or schedules still work unchanged (`usesStandbyMode: true` only adds the standby option; this follows Apify's standby documentation and has not been tried on the live platform).

| Endpoint | Purpose |
|---|---|
| `POST /preview` | free dry run on the first `previewRows` rows; never charged |
| `POST /reconcile` | full job; one `reconciliation-job` charge per completed request, taken **before** results are returned |
| `GET /health`, `GET /` | liveness; `GET /` also answers Apify's readiness probe |

The request body is the same JSON as the Actor input. The response is JSON: `{status, summary, tables}` (summary = `RUN_SUMMARY.json` content, tables = allocations, exceptions, unmatched, discrepancies, duplicates, aging, review sheet). Errors carry `status`, `message`, `charged: false` and, for invalid input, the file/row/column issues, never record values. Details:

- The endpoint decides the mode: `dryRun` in the body is ignored.
- A refused or failed charge returns an error (402 `CHARGE_LIMIT_REACHED`, 500 `CHARGE_FAILED`) and **no results**. Invalid input, limit failures and errors are never charged. The response size is checked before charging (413 `RESPONSE_TOO_LARGE`; use a normal run for very large jobs).
- One job at a time per instance (429 + `Retry-After`), request time capped at 240 s, request body capped at 8 MB, response capped at 25 MB.
- Nothing from API requests is written to the run's dataset or key-value store. The same SSRF-safe loading applies to file URLs.
- Apify authenticates requests (standby URL + your API token); this server adds no extra credentials and sends no CORS headers.
- The OpenAPI 3.0 description is `.actor/openapi.json` (referenced as `webServerSchema` in `.actor/actor.json`); Apify renders it in the Actor's **Endpoints** tab and validates it at build time. The platform does not validate requests against it; the server does its own validation.

```
POST https://<standby-url>/preview      (Authorization: Bearer <APIFY_TOKEN>)
Content-Type: application/json
{"invoicesText": "...", "transactionsText": "...", "asOfDate": "2026-03-31"}
```

Local test of the server: `set APIFY_META_ORIGIN=STANDBY` and `set ACTOR_WEB_SERVER_PORT=4321` (PowerShell: `$env:APIFY_META_ORIGIN="STANDBY"`), then `apify run` and `curl -X POST http://localhost:4321/preview -H "Content-Type: application/json" --data-binary "@examples/sample_input.json"`.

**Key-value store schema.** `.actor/key_value_store_schema.json` groups the run's records into tabs in the Storage view: run summary, failure status, one tab per report (CSV + JSON copies), Excel workbook and dry-run preview files. `RUN_SUMMARY.json` and `RUN_STATUS` also have a JSON Schema that the platform checks when they are saved. A test keeps the schema in sync with what the Actor really writes.

### 8. Manual-review workflow

`review_sheet.csv` columns: `exception_id`, `exception_category`, `source_fingerprint`, `integrity_token`, `explanation`, `proposed_action`, `source_records` (original values), `candidates`, `selected_candidate`, `reviewer_decision` (`PENDING` / `APPROVE` / `REJECT` / `NEEDS_INFORMATION`), `reviewer_notes`, `review_timestamp`.

1. Fill `reviewer_decision` (and `selected_candidate`, e.g. `C1`, when an exception has several candidates), optionally notes and a timestamp. Do not edit the other columns.
2. Re-run with the same source files and the sheet in `reviewFileUrl` / `reviewText` / dataset / store.
3. Each row is validated: unknown or altered IDs (`UNKNOWN_ID`, `ALTERED`), source data that changed since export (`STALE`, by fingerprint), conflicting duplicate decisions (`CONFLICT`, all ignored), invalid decisions or candidates (`INVALID`).
4. `APPROVE` allocates the chosen engine candidate only if the ledger still allows it (never overallocates). The result is recorded as `origin = REVIEWER_APPROVED`, rule `MANUAL_REVIEW`, separate from the original engine result, and appears in `exceptions.csv` (`review_status`, `review_decision`) and the summary.
5. Edits to display columns (for example a changed amount inside `source_records`) are **never** accepted as new accounting facts: approvals always apply the engine's candidate built from the original source data.

Exception IDs are stable across runs of the same data (hash of category + source records). Note that exception IDs and source references are based on file label and row number, so re-exports that reorder rows invalidate old sheets (reported as `UNKNOWN_ID`/`STALE`).

### 9. Aging

As-of date = `asOfDate` (default: run date). Basis `DUE_DATE` (falls back to invoice date + default terms) or `INVOICE_DATE`. Days = as-of − basis date; not-yet-due and 0-30 share the `0-30` bucket, then `31-60`, `61-90`, `91+`. Buckets use the **open balance** after partial payments; settled invoices are listed as `SETTLED`; credit notes/zero documents are `CREDIT_OR_ZERO` and not netted; undated documents are `UNDATED`. Totals are per currency. These are informational figures, not accounting-certified balances.

### 10. Limits (all enforced)

Defaults (hard maximum): rows per file 50,000 (200,000); file size 20 MB (50 MB); total input 60 MB (150 MB); files 6; output rows 500,000 (1,000,000); output size 100 MB; candidates per record 50 (200); combination nodes 20,000 (200,000); invoices per combination 4 (6); run time 1,800 s (10,800 s); preview rows 100 (500); pasted CSV 1 MB. Limits are checked while reading (oversized or over-long inputs are rejected before matching). Exceeding a limit fails the run **without charging**; candidate/search limits instead send the affected records to review and mark the run `COMPLETE_WITH_LIMITS` with the reason. Memory: input files are read as bytes up to the size limit and rows are processed incrementally, but records and outputs are held in memory within those limits; an RSS check against 85% of the run's memory (when the platform reports it) aborts with a clear error. No unbounded file load, no unbounded combination search.

### 11. Dry-run preview

`dryRun: true` validates every file and mapping, then processes only the first `previewRows` rows of each file (hard cap 500). Output files are prefixed `PREVIEW_`, `RUN_SUMMARY` says `mode: PREVIEW`, `run_status: PREVIEW_INCOMPLETE`, and includes sampled-vs-total counts and a pair-count workload figure (an upper bound, not a time or accuracy promise). Matches in a preview are incomplete (a payment's partner row may be outside the sample). Previews are **never charged**, change no source data and perform no irreversible action.

### 12. Pricing and billing

Pay-per-event, one event: **`reconciliation-job`** - *one completed reconciliation job: a run that passed validation, finished matching and published its results.* You are never charged per match, exception or row.

Workflow (`src/billing.py`, `src/main.py`): compute everything in memory → render outputs → **charge once** (`Actor.charge`, idempotency key from run id + input fingerprint, `ChargeResult` checked) → only then publish results. Consequences:

- Preview, invalid input, resource-limit failures, interruptions and processing failures: **not charged**, no results published (a `RUN_STATUS` record explains why).
- If your maximum total charge cannot cover the job (or the platform refuses the charge): run fails with `CHARGE_LIMIT_REACHED`, **no results are published**, nothing is charged. Raise the limit and run again.
- A repeat charge in the same run is skipped (charge-count check; Apify's idempotency keys expire after a few minutes, so the key is a second line of defense, not a permanent guarantee).
- An empty but valid job (valid invoices, no matches) is a completed job and is charged.
- If publishing fails *after* a successful charge, the run fails with `PUBLISH_FAILED` and says so; the platform cannot be refunded automatically by the Actor - contact Apify support.
- Platform behavior to know: at the user's maximum charge the platform may abort the run and stop accepting dataset output. This Actor checks the charge result before publishing, so you never receive paid output that was not authorized; it does not promise partial results at that limit.
- Standby API: each `POST /reconcile` is its own job and one `reconciliation-job` charge. Apify documents that standby runs also bill the user for platform usage on top of events, so the all-in cost of a standby user is event price + usage; batch runs are event price only.
- Outside pay-per-event pricing (plain local runs) `Actor.charge` is a no-op; the summary reports `NOT_CHARGED_NOT_PPE`.

Sample charges at an illustrative **$1.50 per job** (you set the real price): 1 run = $1.50; 20 monthly client reconciliations = $30.00; previews = $0.00. The suggested price test range is $0.75-$3.00 per job.

**Apify Console setup:** *Actor → Publication → Monetization → Pay per event*. Add the event with technical name exactly `reconciliation-job`, title "Completed reconciliation job", description as above, and your price. Do **not** define `apify-default-dataset-item` (this Actor writes result rows to the dataset and must not charge per row). In local test mode the SDK logs a synthetic dataset-item charge at its default $1 test price; that appears only in the local `charging-log` dataset.

Local monetization test: `ACTOR_TEST_PAY_PER_EVENT=true` (and optionally `ACTOR_MAX_TOTAL_CHARGE_USD=0.5`) then `apify run`; charge calls are logged in `storage/datasets/charging-log`.

### 13. Privacy, security and retention

- No telemetry, no analytics, no LLM calls, no exchange-rate or other outbound calls except the single URL you provide for a file (validated as above).
- Logs contain counts and stage names only - never record values, references, descriptions, amounts or account details (tested, including a traceback-suppressing log filter).
- No unsafe deserialization (JSON/CSV/XLSX only); no formulas, macros or embedded content are executed; regular expressions are restricted as in section 4.
- Source records and outputs live only in the run's own default storages. **Retention is set by Apify, not this Actor**: unnamed (default run) storages beyond the most recent runs are deleted when your plan's retention period ends (Apify documents: free plan - the 10 most recent runs are kept for 4 months; paid plans follow the retention period in your billing settings; named storages are kept until you delete them). Delete a run's storages yourself for earlier removal. The Actor author cannot guarantee deletion from copies you or your tools downloaded or exported (CSV, XLSX, webhooks, integrations). Datasets or stores you supply as *inputs* stay under your control and are only read.
- Output rows contain your original record values (needed for the audit trail); treat run storages as confidential and manage sharing accordingly.

### 14. Limitations and common matching errors

- Duplicate/ambiguous data is sent to review by design; very repetitive data (many identical amounts and dates) yields many exceptions.
- `VENDOR_AMOUNT_DATE` relies on exact equality of *normalized* names (case, punctuation, legal suffixes, accents). "Acme" vs "Acme Holdings" is not matched; add a reference or map a better column.
- Names in non-Latin scripts are compared as written (no transliteration).
- Overpayments, credit notes and refunds are flagged, never auto-netted or auto-allocated.
- A payment in another currency is converted at your supplied rate; if the converted amount differs, it is a partial payment or review item unless within tolerance.
- Exception IDs and fingerprints depend on file label/row numbers: re-exports with different row order cannot reuse an old review sheet.
- Review-sheet APPROVE applies engine candidates only; it cannot invent a new match or amount. To record something the engine never proposed, fix the source data and re-run.
- Combination search is bounded by design; large groups are reviewed manually.
- Bank presets are generic layouts, not guarantees for any institution. No bank, accounting package or file format other than those listed above is claimed as tested.
- The Actor has been exercised locally and under Apify's local SDK runtime (see CHANGELOG for exactly what was and was not verified); it has not been published to the Store from this repository.

### 15. Local installation and execution

Supported: Python 3.12+ (tested on 3.13), Apify SDK for Python `>=4.1.0,<5` (tested with 4.1.0), `openpyxl 3.1.5`. Base image in `Dockerfile`: `apify/actor-python:3.13` (confirm the tag on your account before publishing).

```bash
## Windows (PowerShell)
py -3.13 -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements-dev.txt
python -m pytest                      # unit + golden + real-SDK integration tests
npm install -g apify-cli              # once
apify run --input-file examples\sample_input.json --purge

## macOS / Linux
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements-dev.txt
python -m pytest
apify run --input-file examples/sample_input.json --purge
```

Results appear in `storage/key_value_stores/default/` and `storage/datasets/default/`. Deploy: `apify login` then `apify push`.

### 16. Integration examples

Replace `USERNAME/invoice-expense-csv-reconciler` and the token. These follow Apify's documented v2 API and client; the endpoints and payloads are standard but were **not executed against a live account from this repository**.

**Python (apify-client)**

```python
from apify_client import ApifyClient

client = ApifyClient("<APIFY_TOKEN>")
run = client.actor("USERNAME/invoice-expense-csv-reconciler").call(run_input={
    "invoicesText": open("invoices.csv", encoding="utf-8").read(),
    "transactionsText": open("bank.csv", encoding="utf-8").read(),
    "asOfDate": "2026-03-31",
})
store = client.key_value_store(run["defaultKeyValueStoreId"])
summary = store.get_record("RUN_SUMMARY.json")["value"]
print(summary["run_status"], summary["exception_count"])
review_csv = store.get_record("review_sheet.csv")["value"]   # bytes for CSV
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    pass
```

**HTTP (any tool)**

```
POST https://api.apify.com/v2/acts/USERNAME~invoice-expense-csv-reconciler/run-sync-get-dataset-items?token=<APIFY_TOKEN>
Content-Type: application/json

{"invoicesFileUrl": "https://example.com/invoices.csv", "transactionsFileUrl": "https://example.com/bank.csv"}
```

(`run-sync…` has a platform timeout of a few minutes; for larger jobs use `POST /v2/acts/USERNAME~invoice-expense-csv-reconciler/runs`, poll the run, then read `GET /v2/key-value-stores/{storeId}/records/RUN_SUMMARY.json`.) Remember that the key-value-store file URL of a private store needs a token or signed URL; this Actor never forwards credentials, so for chaining Actors pass `invoicesDatasetId` / `invoicesStoreId` + `invoicesStoreKey` instead of URLs.

**n8n** *(configuration outline)*: *Apify* node → *Run an Actor* with the input JSON above (or an *HTTP Request* node to the endpoint above with the token as query parameter) → *Get dataset items* → branch on `recordType == "exceptions"` to notify reviewers.

**Make** *(configuration outline)*: *Apify* app → *Run an Actor*, input JSON above, wait for the run to finish → *Get Dataset Items* → filter `recordType = exceptions`.

**Zapier** *(configuration outline)*: *Apify* app → *Run Actor* action with the input JSON → *Fetch dataset items* → filter on `recordType`.

**Google Sheets** *(Apps Script, pseudocode-level - untested)*:

```javascript
function reconcile() {
  const url = "https://api.apify.com/v2/acts/USERNAME~invoice-expense-csv-reconciler/run-sync-get-dataset-items?token=" +
              PropertiesService.getScriptProperties().getProperty("APIFY_TOKEN");
  const inv = SpreadsheetApp.getActive().getSheetByName("Invoices");
  const bank = SpreadsheetApp.getActive().getSheetByName("Bank");
  const toCsv = s => s.getDataRange().getDisplayValues().map(r => r.map(c => '"' + String(c).replace(/"/g, '""') + '"').join(",")).join("\n");
  const res = UrlFetchApp.fetch(url, {method: "post", contentType: "application/json",
    payload: JSON.stringify({invoicesText: toCsv(inv), transactionsText: toCsv(bank)})});
  const rows = JSON.parse(res.getContentText()).filter(r => r.recordType === "exceptions");
  // write rows to an "Exceptions" sheet ...
}
```

### 17. Troubleshooting

| Message / status | Meaning and fix |
|---|---|
| `INVALID_INPUT` + `issues` in `RUN_STATUS` | file, row, column, problem and suggestion are listed; fix and re-run (not charged) |
| `AMBIGUOUS_DATE` / `AMBIGUOUS_AMOUNT` | set `dateFormat` / `decimalSeparator` |
| `MISSING_REQUIRED_COLUMN` / `AMBIGUOUS_COLUMN` | add an explicit mapping |
| `REMOTE_FILE_REJECTED` | URL must be public HTTPS to a CSV/XLSX/JSON file (no private addresses, no credentials) |
| `CHARGE_LIMIT_REACHED` | raise the maximum total charge for the run |
| `RESOURCE_LIMIT_EXCEEDED` | input/output/time limit exceeded; split files or raise the (capped) limit |
| `PUBLISH_FAILED` | storage write failed; see section 12 |
| Many `AMBIGUOUS_MATCH` | add references, map better party columns, or lower the date tolerance |
| `STALE` / `UNKNOWN_ID` / `ALTERED` in a review import | the review sheet no longer matches the source data (section 8) |

### 18. FAQ

**Does it use AI?** No. Matching is rule-based and deterministic.
**Can it pay or post anything?** No. It only reads inputs and writes reports.
**Why was my payment not matched automatically?** Check `exceptions.csv` and the `reason` column of `unmatched_payments.csv`.
**Are Excel formulas evaluated?** No; only cached cell values are read, and exported cells are neutralized.
**Can I rely on aging figures for filings?** No - they are informational.
**XLS / PDF / OCR / QuickBooks API?** Not supported.

***

Changelog: `CHANGELOG.md`. License: `LICENSE`.

#### Store listing (draft)

- **Title:** Invoice & Expense CSV Reconciler
- **SEO description:** Reconcile invoice, bank and expense CSV/XLSX exports: exact and normalized reference matching, partial payments, grouped settlements, duplicates, FX and aging, with an explainable human review queue. No AI, no scraping.
- **Categories:** finance / business, automation (choose the closest available in the Console).
- **Keywords:** invoice reconciliation, bank reconciliation, accounts payable, accounts receivable, bookkeeping, expense matching, CSV reconciliation, payment matching, aging report.
- **Icon concept:** two overlapping document sheets joined by a check mark.
- **Pricing:** pay-per-event, `reconciliation-job` (see section 12). Previews free.
- **Example run:** `examples/sample_input.json`.

# Changelog

This Actor's version history is a separate document: https://apify.com/makentest/invoice-expense-csv-reconciler/changelog.md

# Actor input Schema

## `invoicesFileUrl` (type: `string`):

Upload a CSV/XLSX/JSON file or paste a public HTTPS URL. Required. Set exactly one source mode per file.

## `invoicesText` (type: `string`):

Paste CSV text including a header row (max 1 MB).

## `invoicesDatasetId` (type: `string`):

Existing Apify dataset with flat records (one record per row; keys become column names).

## `invoicesStoreId` (type: `string`):

Key-value store holding the file; also set the record key below.

## `invoicesStoreKey` (type: `string`):

Record key of a CSV/XLSX file (or JSON array of flat objects) in the store above.

## `invoicesSheet` (type: `string`):

Sheet to read from an XLSX workbook. Empty = first sheet.

## `transactionsFileUrl` (type: `string`):

Upload a CSV/XLSX/JSON file or paste a public HTTPS URL. Required. Set exactly one source mode per file.

## `transactionsText` (type: `string`):

Paste CSV text including a header row (max 1 MB).

## `transactionsDatasetId` (type: `string`):

Existing Apify dataset with flat records (one record per row; keys become column names).

## `transactionsStoreId` (type: `string`):

Key-value store holding the file; also set the record key below.

## `transactionsStoreKey` (type: `string`):

Record key of a CSV/XLSX file (or JSON array of flat objects) in the store above.

## `transactionsSheet` (type: `string`):

Sheet to read from an XLSX workbook. Empty = first sheet.

## `expensesFileUrl` (type: `string`):

Upload a CSV/XLSX/JSON file or paste a public HTTPS URL. Optional. Set exactly one source mode per file.

## `expensesText` (type: `string`):

Paste CSV text including a header row (max 1 MB).

## `expensesDatasetId` (type: `string`):

Existing Apify dataset with flat records (one record per row; keys become column names).

## `expensesStoreId` (type: `string`):

Key-value store holding the file; also set the record key below.

## `expensesStoreKey` (type: `string`):

Record key of a CSV/XLSX file (or JSON array of flat objects) in the store above.

## `expensesSheet` (type: `string`):

Sheet to read from an XLSX workbook. Empty = first sheet.

## `fxFileUrl` (type: `string`):

Upload a CSV/XLSX/JSON file or paste a public HTTPS URL. Columns: base currency, quote currency, rate, rate date, optional convention. Set exactly one source mode per file.

## `fxText` (type: `string`):

Paste CSV text including a header row (max 1 MB).

## `fxDatasetId` (type: `string`):

Existing Apify dataset with flat records (one record per row; keys become column names).

## `fxStoreId` (type: `string`):

Key-value store holding the file; also set the record key below.

## `fxStoreKey` (type: `string`):

Record key of a CSV/XLSX file (or JSON array of flat objects) in the store above.

## `reviewFileUrl` (type: `string`):

Upload a CSV/XLSX/JSON file or paste a public HTTPS URL. The review_sheet.csv from an earlier run, with reviewer decisions filled in. Set exactly one source mode per file.

## `reviewText` (type: `string`):

Paste CSV text including a header row (max 1 MB).

## `reviewDatasetId` (type: `string`):

Existing Apify dataset with flat records (one record per row; keys become column names).

## `reviewStoreId` (type: `string`):

Key-value store holding the file; also set the record key below.

## `reviewStoreKey` (type: `string`):

Record key of a CSV/XLSX file (or JSON array of flat objects) in the store above.

## `encoding` (type: `string`):

Encoding of CSV files. Auto tries BOM, UTF-8, then Windows-1252.

## `defaultCurrency` (type: `string`):

ISO code used when a file has no currency column or the cell is empty (for example USD).

## `invoiceMapping` (type: `object`):

Fields: invoiceId, party, invoiceDate, dueDate, amount, currency, reference, tax.

## `transactionMapping` (type: `object`):

Fields: transactionId, date, amount, currency, reference, memo, counterparty, type, debit, credit.

## `expenseMapping` (type: `object`):

Fields: expenseId, date, vendor, amount, currency, category, reference.

## `fxMapping` (type: `object`):

Fields: baseCurrency, quoteCurrency, rate, rateDate, convention (QUOTE_PER_BASE or BASE_PER_QUOTE).

## `bankPreset` (type: `string`):

Editable generic layouts, not bank-specific guarantees. Explicit mapping always wins over a preset.

## `transactionAmountMode` (type: `string`):

How direction is encoded in the payment file. A positive amount is NOT assumed to be incoming.

## `incomingSign` (type: `string`):

Only used with the signed-amount convention.

## `creditTypeValues` (type: `array`):

Used with the type-column convention.

## `debitTypeValues` (type: `array`):

Used with the type-column convention.

## `invoiceKind` (type: `string`):

Decides the payment direction invoices expect. Expenses always expect money out.

## `dateFormat` (type: `string`):

Set DMY or MDY to resolve ambiguous numeric dates.

## `decimalSeparator` (type: `string`):

Set explicitly if your amounts are ambiguous.

## `invalidRowPolicy` (type: `string`):

With REPORT, rejected rows are counted and listed (max 200) in RUN_SUMMARY.json.

## `dateToleranceDays` (type: `integer`):

Days a payment may fall before the document date or after its due date and still count as in-window.

## `defaultPaymentTermsDays` (type: `integer`):

Used for the payment window and aging when an invoice has no due date.

## `amountTolerance` (type: `string`):

Absolute difference (in the document currency) accepted as a match, recorded as a TOLERANCE adjustment.

## `roundingTolerance` (type: `string`):

Absolute difference accepted as rounding; recorded as a ROUNDING adjustment.

## `bankFeeTolerance` (type: `string`):

Maximum shortfall (payment lower than invoice) accepted as a BANK_FEE adjustment.

## `processorFeeTolerance` (type: `string`):

Maximum shortfall accepted as a PROCESSOR_FEE adjustment.

## `taxTolerance` (type: `string`):

Maximum difference accepted as TAX_DIFFERENCE when the invoice has a tax amount.

## `enableVendorAmountDate` (type: `boolean`):

Match on normalized party name, compatible amount and payment window.

## `enableAmountDateFallback` (type: `boolean`):

Match on amount and date only. Never auto-approved when several candidates exist.

## `enablePartialPayments` (type: `boolean`):

Allow payments below the balance; multiple payments per invoice are tracked.

## `enableGroupedSettlement` (type: `boolean`):

Bounded combination search for payments that settle several invoices of one party.

## `referenceRegex` (type: `string`):

Optional regex to extract a reference from the payment memo (at most one capture group). Nested repetition, back-references and look-around are rejected. Example: INV\[- ]?\d{3,6}

## `referencePrefixes` (type: `array`):

Removed from the start of references during normalization.

## `ambiguityPolicy` (type: `string`):

Row order is never used to break ties.

## `minEvidence` (type: `integer`):

Independent evidence items required (reference/id, vendor, amount, date). Fewer goes to review.

## `paymentDirection` (type: `string`):

AUTO sends opposite-direction reference hits to review as possible refunds.

## `fxRateMode` (type: `string`):

Missing rates are flagged, never substituted.

## `fxDateWindowDays` (type: `integer`):

0 = exact date only; otherwise the closest earlier rate within the window.

## `outputFormats` (type: `array`):

CSV/JSON files go to the key-value store; XLSX is one workbook with a sheet per report.

## `includeUnmatched` (type: `boolean`):

unmatched_invoices and unmatched_payments.

## `includeDuplicates` (type: `boolean`):

duplicate_invoices and duplicate_payments.

## `includeExplanations` (type: `boolean`):

Explanation, warning and proposed-action columns (the review sheet always keeps them).

## `includeSourceRows` (type: `boolean`):

Source file and row columns (the review sheet always keeps them).

## `includeAging` (type: `boolean`):

Buckets 0-30, 31-60, 61-90, 91+ days on open invoice balances.

## `asOfDate` (type: `string`):

YYYY-MM-DD. Empty = run date.

## `agingBasis` (type: `string`):

Not-yet-due invoices fall in 0-30.

## `detailLevel` (type: `string`):

RUN_SUMMARY.json is always produced.

## `dryRun` (type: `boolean`):

Process only a capped sample. Outputs are prefixed PREVIEW\_ and are not a reconciliation result.

## `previewRows` (type: `integer`):

Hard maximum 500.

## `enableExpenses` (type: `boolean`):

Ignore the expense source when off.

## `maxRowsPerFile` (type: `integer`):

Hard maximum 200,000. Larger files are rejected before processing.

## `maxFileSizeMb` (type: `integer`):

Hard maximum 50 MB.

## `maxTotalSizeMb` (type: `integer`):

Hard maximum 150 MB.

## `maxOutputRows` (type: `integer`):

The run fails (uncharged) instead of producing more.

## `maxCandidatesPerRecord` (type: `integer`):

Records above the limit go to review (never silently truncated).

## `maxInvoicesPerCombination` (type: `integer`):

Largest number of invoices one payment may settle in a grouped settlement (2-6). Larger combinations are not searched.

## `maxCombinationNodes` (type: `integer`):

Per payment. When exhausted the case goes to review.

## `maxRuntimeSeconds` (type: `integer`):

The run fails uncharged when exceeded.

## `chunkSize` (type: `integer`):

Bounds work per step. Decisions do not depend on it.

## Actor input object example

```json
{
  "invoicesText": "Invoice ID,Customer,Invoice Date,Due Date,Amount,Currency,Reference\nINV-1001,Acme Ltd,2026-01-05,2026-02-04,1200.00,USD,PO-77\nINV-1002,Beta LLC,2026-01-08,2026-02-07,450.50,USD,\nINV-1003,Gamma Inc,2026-01-10,2026-02-09,300.00,USD,GAM-3",
  "transactionsText": "Date,Description,Amount,Reference,Transaction ID,Currency,Payee\n2026-01-20,Payment PO 77,1200.00,po77,T-1,USD,ACME LIMITED\n2026-01-21,Transfer,450.50,,T-2,USD,Beta LLC\n2026-01-25,Part payment GAM-3,100.00,GAM3,T-3,USD,Gamma",
  "encoding": "AUTO",
  "defaultCurrency": "USD",
  "invoiceMapping": {
    "invoiceId": "Invoice ID",
    "party": "Customer",
    "invoiceDate": "Invoice Date",
    "dueDate": "Due Date",
    "amount": "Amount",
    "currency": "Currency",
    "reference": "Reference"
  },
  "transactionMapping": {
    "transactionId": "Transaction ID",
    "date": "Date",
    "amount": "Amount",
    "currency": "Currency",
    "reference": "Reference",
    "memo": "Description",
    "counterparty": "Payee"
  },
  "transactionAmountMode": "SIGNED",
  "incomingSign": "POSITIVE",
  "creditTypeValues": [
    "CREDIT",
    "CR",
    "DEPOSIT",
    "IN"
  ],
  "debitTypeValues": [
    "DEBIT",
    "DR",
    "WITHDRAWAL",
    "OUT"
  ],
  "invoiceKind": "RECEIVABLE",
  "dateFormat": "AUTO",
  "decimalSeparator": "AUTO",
  "invalidRowPolicy": "FAIL",
  "dateToleranceDays": 5,
  "defaultPaymentTermsDays": 30,
  "amountTolerance": "0.00",
  "roundingTolerance": "0.01",
  "bankFeeTolerance": "0.00",
  "processorFeeTolerance": "0.00",
  "taxTolerance": "0.00",
  "enableVendorAmountDate": true,
  "enableAmountDateFallback": false,
  "enablePartialPayments": true,
  "enableGroupedSettlement": false,
  "referenceRegex": "INV[- ]?\\d{3,6}",
  "referencePrefixes": [
    "INV",
    "INVOICE",
    "REF",
    "PAYMENT"
  ],
  "ambiguityPolicy": "REVIEW",
  "minEvidence": 2,
  "paymentDirection": "AUTO",
  "fxRateMode": "TRANSACTION_DATE",
  "fxDateWindowDays": 0,
  "outputFormats": [
    "csv",
    "json"
  ],
  "includeUnmatched": true,
  "includeDuplicates": true,
  "includeExplanations": true,
  "includeSourceRows": true,
  "includeAging": true,
  "agingBasis": "DUE_DATE",
  "detailLevel": "STANDARD",
  "dryRun": true,
  "previewRows": 100,
  "enableExpenses": true,
  "maxRowsPerFile": 50000,
  "maxFileSizeMb": 20,
  "maxTotalSizeMb": 60,
  "maxOutputRows": 500000,
  "maxCandidatesPerRecord": 50,
  "maxInvoicesPerCombination": 4,
  "maxCombinationNodes": 20000,
  "maxRuntimeSeconds": 1800,
  "chunkSize": 5000
}
```

# Actor output Schema

## `runSummary` (type: `string`):

Counts, totals by currency, aging totals, rules applied, limits reached, warnings and billing status.

## `allocations` (type: `string`):

One row per allocation with rule, evidence and amounts.

## `exceptions` (type: `string`):

Items that need a human decision.

## `unmatched` (type: `string`):

Open invoices and unallocated payments.

## `reviewSheet` (type: `string`):

Fill reviewer_decision and re-import on the next run.

## `allocationsCsv` (type: `string`):

Spreadsheet-ready allocations report.

## `agingReport` (type: `string`):

Invoice-level aging buckets (informational).

## `allResults` (type: `string`):

Every result row, tagged by recordType.

## `reportFiles` (type: `string`):

Every file the run saved: CSV, JSON, XLSX, summary.

# 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 = {
    "invoicesText": `Invoice ID,Customer,Invoice Date,Due Date,Amount,Currency,Reference
INV-1001,Acme Ltd,2026-01-05,2026-02-04,1200.00,USD,PO-77
INV-1002,Beta LLC,2026-01-08,2026-02-07,450.50,USD,
INV-1003,Gamma Inc,2026-01-10,2026-02-09,300.00,USD,GAM-3`,
    "transactionsText": `Date,Description,Amount,Reference,Transaction ID,Currency,Payee
2026-01-20,Payment PO 77,1200.00,po77,T-1,USD,ACME LIMITED
2026-01-21,Transfer,450.50,,T-2,USD,Beta LLC
2026-01-25,Part payment GAM-3,100.00,GAM3,T-3,USD,Gamma`,
    "invoiceMapping": {
        "invoiceId": "Invoice ID",
        "party": "Customer",
        "invoiceDate": "Invoice Date",
        "dueDate": "Due Date",
        "amount": "Amount",
        "currency": "Currency",
        "reference": "Reference"
    },
    "transactionMapping": {
        "transactionId": "Transaction ID",
        "date": "Date",
        "amount": "Amount",
        "currency": "Currency",
        "reference": "Reference",
        "memo": "Description",
        "counterparty": "Payee"
    },
    "dryRun": true
};

// Run the Actor and wait for it to finish
const run = await client.actor("makentest/invoice-expense-csv-reconciler").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 = {
    "invoicesText": """Invoice ID,Customer,Invoice Date,Due Date,Amount,Currency,Reference
INV-1001,Acme Ltd,2026-01-05,2026-02-04,1200.00,USD,PO-77
INV-1002,Beta LLC,2026-01-08,2026-02-07,450.50,USD,
INV-1003,Gamma Inc,2026-01-10,2026-02-09,300.00,USD,GAM-3""",
    "transactionsText": """Date,Description,Amount,Reference,Transaction ID,Currency,Payee
2026-01-20,Payment PO 77,1200.00,po77,T-1,USD,ACME LIMITED
2026-01-21,Transfer,450.50,,T-2,USD,Beta LLC
2026-01-25,Part payment GAM-3,100.00,GAM3,T-3,USD,Gamma""",
    "invoiceMapping": {
        "invoiceId": "Invoice ID",
        "party": "Customer",
        "invoiceDate": "Invoice Date",
        "dueDate": "Due Date",
        "amount": "Amount",
        "currency": "Currency",
        "reference": "Reference",
    },
    "transactionMapping": {
        "transactionId": "Transaction ID",
        "date": "Date",
        "amount": "Amount",
        "currency": "Currency",
        "reference": "Reference",
        "memo": "Description",
        "counterparty": "Payee",
    },
    "dryRun": True,
}

# Run the Actor and wait for it to finish
run = client.actor("makentest/invoice-expense-csv-reconciler").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 '{
  "invoicesText": "Invoice ID,Customer,Invoice Date,Due Date,Amount,Currency,Reference\\nINV-1001,Acme Ltd,2026-01-05,2026-02-04,1200.00,USD,PO-77\\nINV-1002,Beta LLC,2026-01-08,2026-02-07,450.50,USD,\\nINV-1003,Gamma Inc,2026-01-10,2026-02-09,300.00,USD,GAM-3",
  "transactionsText": "Date,Description,Amount,Reference,Transaction ID,Currency,Payee\\n2026-01-20,Payment PO 77,1200.00,po77,T-1,USD,ACME LIMITED\\n2026-01-21,Transfer,450.50,,T-2,USD,Beta LLC\\n2026-01-25,Part payment GAM-3,100.00,GAM3,T-3,USD,Gamma",
  "invoiceMapping": {
    "invoiceId": "Invoice ID",
    "party": "Customer",
    "invoiceDate": "Invoice Date",
    "dueDate": "Due Date",
    "amount": "Amount",
    "currency": "Currency",
    "reference": "Reference"
  },
  "transactionMapping": {
    "transactionId": "Transaction ID",
    "date": "Date",
    "amount": "Amount",
    "currency": "Currency",
    "reference": "Reference",
    "memo": "Description",
    "counterparty": "Payee"
  },
  "dryRun": true
}' |
apify call makentest/invoice-expense-csv-reconciler --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,makentest/invoice-expense-csv-reconciler"
        }
    }
}
```

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/k43ReJgSPd4VegxoS/builds/PCRO6vqEhsq7jNs0s/openapi.json
