# Poland KSeF FA(3) Preflight Validator - e-Faktura XML (`kamerozkan/poland-ksef-preflight-validator`) Actor

Validate KSeF FA(3) invoice XML before submission with the official pinned XSD and documented offline technical checks. Offline e-faktura preflight for faktura ustrukturyzowana: catch schema, NIP, and cross-field errors in Polish invoices before KSeF e-invoicing submission.

- **URL**: https://apify.com/kamerozkan/poland-ksef-preflight-validator.md
- **Developed by:** [Kamer Ozkan](https://apify.com/kamerozkan) (community)
- **Categories:** Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $4.00 / 1,000 invoice validateds

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/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Poland KSeF FA(3) Preflight Validator - e-Faktura XML

[![KSeF FA(3)](https://img.shields.io/badge/KSeF-FA%283%29-DC143C)](https://github.com/CIRFMF/ksef-api)
[![Official schema](https://img.shields.io/badge/Schema-v1--0E-0057B8)](https://github.com/CIRFMF/ksef-api/blob/main/faktury/schemy/FA/schemat_FA%283%29_v1-0E.xsd)
[![Validation scope](https://img.shields.io/badge/Scope-OFFLINE__PREFLIGHT-137333)](https://apify.com/kamerozkan/poland-ksef-preflight-validator)
[![Billing](https://img.shields.io/badge/Billing-%240.004%20per%20evaluated%20invoice-6f42c1)](https://apify.com/kamerozkan/poland-ksef-preflight-validator)

Catch KSeF FA(3) XML errors before opening a submission session. The Actor returns one stable, agent-readable result per invoice with official XSD findings, documented offline technical checks, exact rule versions, and SHA-256 evidence.

> Technical preflight only. `ACCEPTED` does not establish legal or tax validity, KSeF authorization, correct encryption or session metadata, uniqueness in KSeF, successful submission, KSeF number assignment, or recipient acceptance.

[Run the live Actor](https://apify.com/kamerozkan/poland-ksef-preflight-validator)

### What is checked

| Layer | Pinned check |
|---|---|
| Structure | Official KSeF FA(3) v1-0E XML Schema |
| XML transport | UTF-8, no BOM, no processing instructions, KSeF prohibited Unicode ranges |
| KSeF limits | Document size with and without FA(3) attachments |
| Production identifiers | Polish NIP checksum and the NIP prefix in a Podmiot3 internal ID |
| Submission date | `P_1` is not later than the validation date |
| Batch integrity | Duplicate `NrWierszaFa` line numbers are rejected |
| ERP consistency diagnostics | Line arithmetic, P\_15 header totals, VAT plausibility when the rate is unambiguous, PLN conversion fields, settlement sums, and period ordering |

The rule package is downloaded during the build from the official Ministry of Finance GitHub organization at commit `1c34fe2799387d517b83a2fb21e31e83d5f66247`. Its archive and individual XSD files are SHA-256 verified. The patched offline main XSD also has its own manifest hash and is verified again before use. Runtime validation never downloads rules.

The ERP consistency layer returns `WARNING` findings because these checks are useful before submission but are not documented as KSeF server rejection rules. Official XSD and documented KSeF technical failures remain `ERROR` findings and produce `REJECTED`.

### Quick start

Run with no document source to validate the built-in accepted FA(3) fixture:

```json
{
  "resultDetail": "FINDINGS",
  "maxFindingsPerDocument": 100,
  "storeXmlReport": false,
  "storeHtmlReport": false
}
```

Each document can use exactly one source:

- Console file upload
- HTTPS URL with public-IP and redirect enforcement
- Inline XML
- Base64 XML
- A record in your Apify key-value store

The input and output schemas work with the Apify API, MCP clients, Make, n8n, webhooks, and standard SDKs.

### Structured results

Every input produces one dataset item. A technically invalid invoice is a successful evaluation with `conformanceStatus: REJECTED`. A source or engine failure is `NOT_EVALUATED`.

<details>
<summary><strong>Accepted FA(3) invoice</strong></summary>

```json
{
  "documentId": "valid-fa3",
  "processingStatus": "SUCCEEDED",
  "conformanceStatus": "ACCEPTED",
  "previewConformanceStatus": "NOT_EVALUATED",
  "validationScope": "OFFLINE_PREFLIGHT",
  "validationFamily": "POLAND_KSEF_FA3",
  "syntax": "KSEF_FA3",
  "profile": "FA(3)_V1-0E",
  "counts": {
    "fatal": 0,
    "error": 0,
    "warning": 0,
    "information": 0
  },
  "findings": [],
  "sha256": "e857b78383a10ca61c2a29ec81a2d7b35cba3bd3fc22d703b368fc4910bce9a0",
  "error": null
}
```

</details>

<details>
<summary><strong>Rejected invalid NIP</strong></summary>

```json
{
  "documentId": "invalid-nip",
  "processingStatus": "SUCCEEDED",
  "conformanceStatus": "REJECTED",
  "previewConformanceStatus": "NOT_EVALUATED",
  "validationScope": "OFFLINE_PREFLIGHT",
  "counts": {
    "fatal": 0,
    "error": 1,
    "warning": 0,
    "information": 0
  },
  "findings": [
    {
      "severity": "ERROR",
      "stage": "KSEF_TECHNICAL",
      "ruleId": "KSEF-NIP-CHECKSUM",
      "message": "The Polish NIP checksum is invalid",
      "location": "//NIP[text()='5260250275']"
    }
  ],
  "sha256": "a9fda0730e63602bb5b01f9efd5fe42340c9c12ef2bb959693d0a4b2c7fe9ef0",
  "error": null
}
```

</details>

<details>
<summary><strong>Source failure, never billed</strong></summary>

```json
{
  "documentId": "source-error",
  "processingStatus": "FAILED",
  "conformanceStatus": "NOT_EVALUATED",
  "previewConformanceStatus": "NOT_EVALUATED",
  "validationScope": "OFFLINE_PREFLIGHT",
  "counts": {
    "fatal": 0,
    "error": 0,
    "warning": 0,
    "information": 0
  },
  "findings": [],
  "sha256": null,
  "error": {
    "code": "SOURCE_FETCH_FAILED",
    "message": "Only HTTPS source URLs are allowed"
  }
}
```

</details>

These compact examples are taken from a real three-document Actor run. Every row also returns `externalStateStatus: NOT_EVALUATED_EXTERNAL_STATE` because KSeF authorization, session, submission, and final system state are outside offline preflight.

### Billing

The `invoice-validated` event costs **$0.004**.

- `ACCEPTED`: billed once
- `REJECTED`: billed once
- `NOT_EVALUATED`: free
- Dataset delivery does not add a second charge
- The Actor stops before processing unless the event price is exactly $0.004

One malformed or unavailable source does not kill the remaining batch.

### Release gates

Every build must pass:

1. The SHA-pinned official FA(3) XSD published by the Polish Ministry of Finance.
2. Local deterministic FA(3) acceptance and rejection fixtures for the documented technical checks.
3. Non-blocking regression fixtures for line and header arithmetic, VAT plausibility, currency conversion fields, settlement totals, and period ordering.
4. Runtime SHA-256 verification of every executed schema artifact.
5. Source, security, batch-independence, billing-guard, report, and output-contract tests.

The pinned upstream repository does not currently publish a complete official FA(3) invoice example. The regression invoices are therefore synthetic and are not described as government fixtures.

### Security and privacy

- DTDs, XML entities, and external references are blocked
- HTTPS URL sources reject private, loopback, link-local, and metadata addresses
- Redirects are revalidated
- Source XML is not copied into dataset results
- Optional reports are disabled by default
- Every loaded document receives a SHA-256 digest
- The container runs as a non-root user

### Important boundary

Offline validation cannot check KSeF authorization, server-side duplicate history, production availability, cryptographic session packaging, encrypted payload metadata, or the final system response. Use the official KSeF environment for the final submission decision.

For custom ERP integration or high-volume support, contact the Actor owner through the Apify profile.

This Actor is also exposed to AI agents through Apify's MCP server
(mcp.apify.com): an agent can discover it by search and run it with the same
pay-per-event billing, with no separate integration.

### E-invoice validator family

Same engine, same output contract, one validator per market:
[XRechnung & ZUGFeRD (Germany)](https://apify.com/kamerozkan/xrechnung-xml-batch-validator-api) | [Peppol BIS Billing](https://apify.com/kamerozkan/peppol-bis-preflight-validator) | [France E-Invoice](https://apify.com/kamerozkan/france-einvoice-validator) | [Italy FatturaPA](https://apify.com/kamerozkan/italy-fatturapa-validator)

# Actor input Schema

## `invoiceFiles` (type: `array`):

Upload KSeF FA(3) XML invoice files. Source documents are processed inside the Actor and are not copied to the output dataset.

## `documents` (type: `array`):

Each object needs one XML source: url, xml, or base64. HTTPS URLs only. documentId and fileName are optional.

## `sourceKeyValueStoreId` (type: `string`):

Optional. Select a key-value store that contains FA(3) XML records, then list the record keys below.

## `keyValueStoreKeys` (type: `array`):

Record keys to read from the selected source key-value store.

## `resultDetail` (type: `string`):

FINDINGS returns rule IDs, messages, and locations. SUMMARY returns only status and counts.

## `maxFindingsPerDocument` (type: `integer`):

Caps the findings array without changing the total severity counts.

## `storeXmlReport` (type: `boolean`):

Optional. Stores a normalized XML report in your run key-value store. Reports can contain invoice values.

## `storeHtmlReport` (type: `boolean`):

Optional. Stores a human-readable findings report in your run key-value store.

## Actor input object example

```json
{
  "documents": [],
  "resultDetail": "FINDINGS",
  "maxFindingsPerDocument": 100,
  "storeXmlReport": false,
  "storeHtmlReport": false
}
```

# Actor output Schema

## `validationResults` (type: `string`):

No description

## `summary` (type: `string`):

No description

# 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 = {
    "documents": []
};

// Run the Actor and wait for it to finish
const run = await client.actor("kamerozkan/poland-ksef-preflight-validator").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 = { "documents": [] }

# Run the Actor and wait for it to finish
run = client.actor("kamerozkan/poland-ksef-preflight-validator").call(run_input=run_input)

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

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

```

## CLI example

```bash
echo '{
  "documents": []
}' |
apify call kamerozkan/poland-ksef-preflight-validator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=kamerozkan/poland-ksef-preflight-validator",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/acts/VSlT3agPbOnI5BkDE/builds/JCIrNxcJIhTeJssnB/openapi.json
