Niniejsza dokumentacja opisuje interfejs wiersza poleceń, API Python, mikrousługę REST oraz potok walidacji dla pain001 v0.0.91. Każda wymieniona tu flaga, endpoint i zachowanie pochodzi z dostarczonego kodu, a nie z planów.
Pain001 obsługuje 13 definicji komunikatów ISO 20022: od pain.001.001.03 do pain.001.001.13 (Customer Credit Transfer Initiation, jedenaście wersji) oraz pain.008.001.02 / pain.008.001.08 (Customer Direct Debit Initiation).
1. Interfejs wiersza poleceń#
Program pain001 grupuje funkcje w podkomendy. Uruchomienie go wyłącznie z flagami generowania wywołuje niejawnie generate, dzięki czemu istniejąca automatyzacja działa bez zmian.
| Podkomenda | Przeznaczenie |
|---|---|
generate | Konwertuje plik danych na XML ISO 20022 zwalidowany względem schematu (komenda domyślna). |
validate | Waliduje dane wejściowe bez zapisywania XML. |
check <file>... [--scheme] [--format] | Check pain.001 or pain.008 files you already have: the XSD of the message type each file declares, the message definition's cross-element rules, and any scheme profiles, policy or Schematron rulebook you name. |
verify-signature <file>... --cert <PEM> | Verify the XML-DSig signature on each file against the signer's certificate or public key; --trust-embedded-cert checks integrity only (requires the sign extra). |
versions [--format json] | Wyświetla wszystkie 13 obsługiwanych definicji komunikatów. |
inspect <type> [--format json] | Pokazuje dołączony szablon, schemat, przykładowe dane i akceptowane formaty wejściowe dla typu komunikatu. |
init <type> [-o FILE] | Tworzy startowy szablon CSV dla typu komunikatu. |
serve [--host] [--port] [--reload] | Uruchamia mikrousługę REST FastAPI (wymaga dodatku api). |
mcp | Uruchamia wbudowany serwer Model Context Protocol biblioteki głównej przez stdio (wymaga dodatku mcp); pełny serwer jest dostarczany jako pain001-mcp. |
plugins list / show / disable | Wyświetla wykryte wtyczki ładowania, walidacji, schematów i zapisu, pokazuje jedną z nich lub informuje, jak wyłączyć wykrywanie wtyczek zewnętrznych. |
face <file> [--face] [--bindings] [-o] [--loss-report] | Project a pain.001 XML file into another standard's JSON shape, with a report of every element not carried. |
upload [<file>] --sftp <url> | Deliver a file atomically to an SFTP server you trust explicitly (requires the upload extra). |
Opcje generate
| Flaga | Opis |
|---|---|
-t, --xml-message-type <TYPE> | Definicja komunikatu, np. pain.001.001.09. |
-d, --data <FILE> | Dane wejściowe: .csv, .json, .jsonl, .db / .sqlite, .parquet lub zaszyfrowane PGP .gpg / .asc. |
-o, --output-dir <DIR> | Katalog, do którego trafia wygenerowany XML. |
-m, --template <FILE> / -s, --schema <FILE> | Zastępuje dołączony szablon Jinja2 lub schemat XSD. |
-c, --config <FILE> | Wczytuje wartości domyślne z profilu konfiguracji (--profile, --show-config). |
--dry-run (alias --validate-only) | Waliduje dane wejściowe względem JSON Schema, XSD i reguł schematu płatności bez zapisywania wyniku. |
--scheme <NAME[,NAME]> | Stosuje jeden lub kilka regulaminów schematu, rozdzielonych przecinkami. pain001 plugins list wymienia każdy zainstalowany regulamin. |
--explain / --format json | Z --scheme wypisuje wskazówkę naprawczą dla każdego naruszenia, jako tekst lub JSON. |
--rules <FILE> | Enforce a private YAML CEL policy before generation (requires the rules extra). |
--schematron <PRESET or FILE> | Apply Schematron business rules: the sepa, fednow or cbpr preset, or your own .sch file. |
--decrypt-key <FILE> / --decrypt-passphrase-env <VAR> | Import a GPG private key, and name the variable that holds its passphrase, for .gpg / .asc input (requires the gpg extra). |
--streaming / --chunk-size <N> | Przetwarzanie w porcjach o ograniczonym zużyciu pamięci dla dużych partii (domyślnie 1,000 transakcji na porcję; każda porcja staje się osobnym plikiem XML z przeliczonymi NbOfTxs i CtrlSum). |
--emit-metrics | Emituje odczytywalne maszynowo metryki uruchomienia dla potoków obserwowalności. |
--envelop-bah | Wrap generated payment XML into an ISO 20022 Business Application Header (head.001.001.03) and BizData (head.003.001.01) envelope. |
--bah-sender <BIC/ID> | Sender financial institution BIC or organisation identifier for BAH <Fr>. |
--bah-receiver <BIC/ID> | Receiver financial institution BIC or organisation identifier for BAH <To>. |
--bah-msg-id <ID> | Business Message Identifier for BAH <BizMsgIdr> (defaults to generated UUID). |
--xml-sign-key <FILE> | PEM private key (RSA, or EC P-256/P-384) for a W3C XML Digital Signature (XML-DSig); the algorithm follows the key. |
--xml-sign-cert <FILE> | Optional PEM X.509 certificate to embed in XML-DSig <ds:KeyInfo>. |
--xml-sign-alg <ALG> | rsa-sha256, rsa-pss-sha256, ecdsa-sha256 or ecdsa-sha384; by default an RSA key signs rsa-sha256. |
--xml-sign-passphrase-env <VAR> | Environment variable holding the passphrase for --xml-sign-key. |
--list-templates / --show-template <TYPE> | List the bundled templates, or show one template's metadata, and exit. |
Kody wyjścia są przyjazne dla CI: 0 oznacza sukces, 1 błąd walidacji, 2 błąd użycia.
XML signing and verify-signature need the sign extra (pip install "pain001[sign]", which installs cryptography and lxml).
Signatures: pain001 verify-signature
pain001 verify-signature checks the signature on files you received or wrote. Pass the signer's certificate or public key with --cert; that is the trust anchor. --trust-embedded-cert verifies with each file's own certificate instead, which proves the file is unchanged since it was signed but not who signed it. It exits 0 when every file verifies, 1 when any does not, and 2 when it cannot run; --format json prints one report per file. Verification uses exclusive C14N 1.0 and accepts only RSA-SHA256, RSA-PSS and ECDSA signatures with SHA-256 to SHA-512 digests over the whole document; the certificate's chain and validity dates are not checked.
Faces: pain001 face
A face projects a validated pain.001 document into another standard's JSON request body. --face uk_open_banking targets the Open Banking Read/Write API v4.0.1 domestic payment, --face berlin_group targets NextGenPSD2 v1.3.16 payment initiation, and --face iso_2018 renames every element to its ISO 20022 name in snake_case. A face refuses a document that lacks an element its target requires instead of inventing a value; --loss-report lists every source element it did not carry. Faces are outbound only.
Delivery: pain001 upload
pain001 upload sends a finished file to an SFTP server you name, and only after you have trusted its host key: from a known_hosts file (--known-hosts) or an OpenSSH SHA256 fingerprint you verified independently (--accept-host-key). --print-host-key shows the server's fingerprint without logging in. It logs in with a private key (--identity-file, with --passphrase-env), a password read from an environment variable (--password-env), or your SSH agent. The file is written under a temporary name and renamed on the server, so the receiving side never sees a partial file.
2. API Python#
# Generate a validated pain.001.001.09 file from CSV
Każdy wygenerowany dokument przechodzi przez trzy warstwy, zanim zostanie zapisany:
- Walidacja danych wejściowych: każdy rekord jest sprawdzany względem JSON Schema danego typu komunikatu, z normalizacją aliasów pól oraz kontrolą składni IBAN/BIC.
- Reguły schematu płatności (opcjonalnie): reguły wskazanego systemu płatności, od SEPA (SCT, Instant, SDD Core, B2B) po systemy krajowe, takie jak UK Faster Payments, CHAPS i Bacs, amerykańskie ACH i przelewy, oraz Swift CBPR+;
pain001 plugins listwymienia je wszystkie. - Walidacja XSD: wyrenderowany XML jest walidowany względem oficjalnego schematu ISO 20022 za pomocą
xmlschema, zanim choć jeden bajt trafi na dysk. Gdy zainstalowany jest opcjonalny dodatekfast(lxml), libxml2 szybciej akceptuje poprawne dokumenty; dokument, który odrzuci, jest ponownie sprawdzany przezxmlschema, którego werdykt jest ostateczny.
Kwoty pieniężne są przetwarzane jako decimal.Decimal podczas generowania XML i walidacji schematu (nigdy jako liczby zmiennoprzecinkowe IEEE 754), a sumy kontrolne NbOfTxs / CtrlSum są przeliczane na podstawie zwalidowanych rekordów, a nie przyjmowane z danych wejściowych.
Poza generowaniem pain.001 biblioteka podstawowa zawiera również parser i generator raportów statusu pain.002 (pozwalający odczytać odpowiedź banku o przyjęciu lub odrzuceniu) oraz parser i generator wyciągów camt.053 do uzgodnień na koniec dnia, a także VersionMapper, który migruje rekordy między wersjami komunikatów.
pain001.faces.project_face is the Python entry point for faces. sign_xml_document signs a document with XML-DSig, and verify_signature(signed_xml, trust_anchor=cert_pem) verifies one and returns a SignatureReport (valid, trust, algorithm, signer, reason); both need the sign extra. verify_xml_signature without a key or certificate still trusts the certificate inside the document, with a DeprecationWarning; pain001 0.0.91 refuses it.
Runnable, self-checking scripts for the public API and the CLI live in the library's examples/ directory.
3. Mikrousługa REST#
Wszystkie endpointy są zamontowane pod /api/v1 (z niewersjonowanym aliasem /api):
| Metoda i ścieżka | Przeznaczenie |
|---|---|
GET /api/v1/health | Sonda żywotności (liveness). |
POST /api/v1/validate | Waliduje rekordy; zwraca błędy na poziomie pól. |
POST /api/v1/generate | Synchroniczne generowanie XML. |
POST /api/v1/generate/async | Kolejkuje dużą partię do generowania w tle. |
GET /api/v1/status/{job_id} | Sprawdza stan zadania asynchronicznego. |
GET /api/v1/download/{job_id} | Pobiera gotowy XML. |
DELETE /api/v1/jobs/{job_id} | Usuwa zakończone zadanie. |
GET /api/v1/faces | List the faces and the binding keys each accepts. |
POST /api/v1/faces/{face} | Project a pain.001 document sent as XML text; returns the payload and the loss report, or 422 with the reason the face refused it. |
GET /metrics | Metryki Prometheus. |
Interaktywna dokumentacja jest dostępna pod /api/docs (Swagger UI), /api/redoc i /api/reference (Scalar), a dokument OpenAPI pod /openapi.json.
When the PAIN001_API_KEY environment variable is set, every endpoint except /health and /metrics requires it as a bearer token; when it is unset, the API is open. pain001 serve binds to 127.0.0.1 unless you pass --host.
4. Normalizacja danych wejściowych#
Pain001 przekształca rzeczywiste eksporty w poprawne rekordy jeszcze przed walidacją:
- Aliasy pól: typowe nazwy kolumn z systemów ERP są mapowane na pola kanoniczne (na przykład
amount→payment_amount). - Normalizacja IBAN / BIC: usunięcie spacji, ujednolicenie wielkości liter, a następnie kontrola (mod-97 wg ISO 13616 dla IBAN, struktura wg ISO 9362 dla BIC).
- Daty: parsowanie dat wykonania w formacie ISO 8601
YYYY-MM-DD. - Kwoty: przetwarzane przez
decimal.Decimal; zniekształcone kwoty nie przechodzą walidacji, zamiast być po cichu zaokrąglane. - Zestaw znaków: funkcje transliteracji sprowadzają treść do łacińskiego zestawu znaków ISO 20022 akceptowanego przez SWIFT i SEPA.
- Formula cells: CSV cells that start with
=,+,-or@are kept as supplied by default, so phone numbers and references survive;load_csv_data(path, sanitize_formula=True)escapes them with a leading quote instead.
5. Architektura wtyczek#
Pakiet można rozszerzać poprzez cztery grupy punktów wejścia: pain001.loaders, pain001.validators, pain001.schemes i pain001.writers. pain001-loader-xlsx rejestruje się przez ten mechanizm i jest wykrywany automatycznie po instalacji; pain001-loader-mt101 to samodzielna biblioteka parsująca używana bezpośrednio (oraz przez narzędzie convert_mt101 serwera MCP). Wyłącznik awaryjny PAIN001_DISABLE_PLUGINS=1 całkowicie wyłącza wykrywanie wtyczek zewnętrznych w środowiskach o zaostrzonych restrykcjach.
6. Bramki jakości#
Biblioteka podstawowa jest rozwijana według ścisłych, weryfikowalnych bramek: 100% pokrycia linii i gałęzi wymuszane w CI (--cov-fail-under=100), ścisłe typowanie mypy, 100% pokrycia docstringów oraz linting bezpieczeństwa (Bandit, pip-audit). Dla każdej kompilacji wydania generowany jest SBOM w formacie CycloneDX.
Dalsze materiały: przewodnik instalacji, serwer MCP dla agentów AI oraz słownik płatności.
