# Operational PDF Extension API 1.0.0 Public SDK contract in Free 0.12.10 (Core API 1.9.0), with advanced operational execution supplied by the separate Pro 0.14.3 companion. Installed trusted WordPress add-ons can keep the same v1 field definitions without editing Commerce Assistant. Lazy field-definition registration is available without Pro or a licence. Pro owns typed-field resolution, advanced configuration, preview/diagnostics and optional current-PDF account/email delivery; those features require its loaded runtime and existing signed `contract_production` entitlement. This is not a new REST, fiscalisation or remote connector service. Existing Fiscal/ERP REST v1/v1.1 is unchanged. Free includes the open registry, field definitions, DTOs, validators and read-only resolver guard. Its existing `PdfExtension\Access`, `Settings` and `Projection` PHP entry points remain compatibility facades, delegating advanced work to `Leanmerce\CommerceCompliance\Pro\OperationalPdf` when that separate implementation is installed. They do not contain the paid configuration, resolution or delivery implementation. `Access::allowed()` checks the Pro runtime and production guard through that delegation; `leanmerce_commerce_assistant_operational_pdf_authorized_v1` can further restrict Pro access, never grant it. Without entitled Pro, field definitions can still register, but the Pro resolver callbacks and advanced output do not run. Saved IDs/settings and historical documents remain. Basic Free confirmation/print/original-mail behavior remains available. No new licence host, protocol, signing key or remote call is introduced. ## Registration and selection Hook: `leanmerce_commerce_assistant_register_pdf_extensions_v1`. The argument is `Leanmerce\CommerceCompliance\PdfExtension\Registry`. `Registry::instance()` initializes it lazily and runs definition-registration callbacks without requiring a licence. Ordinary product pages and checkout do not initialize it merely because an add-on contains a definition. Registration does not resolve values, select fields or insert output. Pro initializes it for advanced configuration or a selected operational PDF; the merchant enables fields on its canonical additional-PDF-data page (`leanmerce-commerce-compliance-operational-pdf`; localized page.title). Resolver return values are untrusted data, never HTML. ## Neutral current-document filter capability `Leanmerce\CommerceCompliance\Application\Document\BasicPdfService::CURRENT_DOCUMENT_FILTER_API` is **`1.0.0`**. It identifies the neutral current-document hook independently of package version 0.12.10 and Core API 1.9.0. Compatible add-ons may inspect that capability rather than infer it from an unchanged release label. `leanmerce_commerce_assistant_current_document_v1` filters `(BasicOrderDocument $current, $order, string $audience)` in `BasicPdfService::current_document()`. It has no licence prerequisite. A trusted installed provider must return a `BasicOrderDocument` with the same order ID; an invalid return is rejected. The audience is the current request's merchant/customer context. Providers must preserve authorization, customer privacy, complete order facts and the current/original distinction; the hook is not a grant to disclose merchant-only data. Pro attaches its separately installed operational implementation to this hook and applies its own entitlement, selection, privacy and resource checks before resolving typed fields. Free supplies the hook and current-document service, not that paid implementation. The hook does not run to reconstruct or change an archived original or frozen contract. Existing public PHP facade signatures, the v1 field constructor and stored `lmcc_operational_pdf_v1` identifier remain stable. ```php 'Referenca','hr'=>'Referenca','sr'=>'Referenca','en'=>'Reference']; $help = ['bs'=>'Referenca ove narudžbe.','hr'=>'Referenca ove narudžbe.', 'sr'=>'Referenca ove narudžbe.','en'=>'Reference for this order.']; $ok = $registry->register_field(new \Leanmerce\CommerceCompliance\PdfExtension\FieldDefinition( 'example.order.reference', 'example', '1.0.0', '1.0.0', $copy, $help, 'text', static fn($order) => $order->metadata['_example_reference'] ?? null, ['_example_reference'], 'customer-visible', 'POST_ORDER_CURRENT', ['operational'] )); // false = controlled rejection, never overwrite an earlier provider's field. // Inspect $registry->errors() in your own authorized diagnostic workflow. }); ``` Constructor, in order: `id, provider_id, api_version, provider_version, labels, help, type, resolver, metadata_keys=[], privacy='merchant-private', phase='POST_ORDER_CURRENT', document_types=['operational'], format=[]`. IDs are case-sensitive lowercase namespaces with at least three dot-separated segments, e.g. `vendor.order.tracking`; first segment must match provider_id. ID ≤120 bytes; provider ID ≤48. API compatibility is `1.0.x` (x up to three digits), provider version is nonempty text ≤64 bytes. `labels` and `help` must contain exactly bs/hr/sr/en: labels ≤120 bytes, help ≤512. No HTML presentation is accepted. Duplicate IDs return false (`duplicate_field`), retaining the first definition. The register limit is 100 (`registry_budget`). Invalid definitions throw InvalidArgumentException before registration; add-ons should handle their own configuration errors. ## Return types (literal PHP shapes) | Type | Return value and limits | | --- | --- | | text | UTF-8 string ≤2,048 bytes; no C0/DEL controls other than tab/newlines. | | integer | Actual PHP int, −1,000,000,000…1,000,000,000; no implicit string/bool conversion. | | decimal | Canonical decimal string, optional minus, 1–9 integer digits and up to 4 fractional digits. No exponent/comma. | | money | Exactly `['amount'=>'55.20','currency'=>'BAM']`; canonical decimal amount and three uppercase currency letters. Presentation is two decimal places. | | date | Exact ISO `Y-m-d`, valid calendar date. Example `2026-10-20`. BS/HR/SR render `20.10.2026.`, EN `2026-10-20`. | | url | Valid credential-free HTTPS URL ≤2,048 bytes, valid host, no raw whitespace/backslash/control bytes or percent-encoded C0/DEL. UTF-8 URL bytes become percent-encoded ASCII. No URL fetch. | | list | Sequential array ≤20 plain strings, each ≤2,048 bytes. Use structured_block for linked rows. | | structured_block | Sequential array ≤20 rows, ≤16 KiB normalized JSON. Each row has `label` ≤120 bytes and `text` ≤2,048; optional safe `url` and nonempty `link_label` ≤80. No extra keys. | Return null, empty string or empty list for an unavailable value. Optional empty fields create no heading. Invalid values omit only that field and produce a diagnostic, never an unsafe link. A malformed linked block is rejected as a whole, not partly linked to a guessed destination. Both renderers support BS/HR/SR-Latin/EN and ČĆĐŠŽ/čćđšž. To keep fallback output honest, extension text must fit the common Latin/CP1252+BHS alphabet. Unsupported scripts/emoji yield `unsupported_text`, not a silent glyph substitution or whole-document crash. This is not a promise of arbitrary-script font support. Existing Pro WOFF2 support is unchanged. Example resolver return for three shipments: ```php return [ ['label'=>'1','text'=>'SYNTHETIC-001','url'=>'https://tracking.example.test/parcel/001'], ['label'=>'2','text'=>'SYNTHETIC-002','url'=>'https://tracking.example.test/parcel/002'], ['label'=>'3','text'=>'SYNTHETIC-003','url'=>'https://tracking.example.test/parcel/003'], ]; // format argument supplies short localized anchor text: $format = ['link_labels'=>['bs'=>'Prati pošiljku','hr'=>'Prati pošiljku', 'sr'=>'Prati pošiljku','en'=>'Track shipment']]; ``` Adapter date parsing is explicit, not a Core assumption: ```php if (!is_string($raw) || !preg_match('/^\d{6}$/D', $raw)) { throw new InvalidArgumentException('Expected YYMMDD'); } $date = DateTimeImmutable::createFromFormat('!ymd', $raw); if (!$date || $date->format('ymd') !== $raw) throw new InvalidArgumentException('Invalid date'); return $date->format('Y-m-d'); // 261020 -> 2026-10-20; document your century convention. ``` WordPress metadata scalars may be returned as strings on subsequent reads. Providers must validate and explicitly convert their declared integer types, not cast arbitrary values. The inline registration example above is the example distributed in this document; no separate provider plugin is included in the Free installation. Use synthetic data when testing your own provider. ## Projection, privacy and resource budgets The callback receives readonly `OrderProjection`: order_id, public_number, currency, language, bounded items (name/quantity/total), metadata, items_complete. No WC_Order, payment secrets, customer addresses or arbitrary product metadata are automatically exposed. Metadata is fetched through Woo CRUD for HPOS (sync off) or legacy. Each callback sees only its own declared keys. ≤16 keys/field, ≤64 selected-key union; each value ≤16 KiB, depth ≤6, 256 nodes, 128 children; aggregate metadata ≤64 KiB. Invalid values are absent. Items ≤200 /64 KiB; check items_complete if exhaustive items matter. These API projection bounds never truncate the mandatory order table itself. At most 32 enabled fields, 120 normalized output rows and 64 KiB total block JSON per PDF. Ordering is stable by zone, numeric order (0–999), then ID. Up to 100 registered and 32 stale selections can be managed. PHP form truncation is rejected using a last-field completeness sentinel, not silently saved. Optimistic revision plus DB advisory lock prevents lost concurrent settings edits. Callbacks have no hard PHP execution timeout; an installed add-on must keep work bounded and fast. Privacy defaults to merchant-private. `customer-visible` requires explicit provider classification AND merchant selection; it is the only data sent to account/email customer PDFs. `merchant-private` additionally requires an authorized merchant with Woo order edit permissions; `restricted` also requires the existing integration-management capability. Registration is not permission to expose data. A metadata allowlist is not a privacy policy change. During resolution WordPress HTTP requests are vetoed, wp_mail is blocked, Woo order/item saves are blocked, and emitted output is discarded/rejected. Hooks are always restored, including exceptions. **Installed PHP is trusted code, not a sandbox**: direct SQL, curl, filesystem/system calls or deliberate bypasses cannot be absolutely contained. Do not perform network access, writes or mail in resolvers. Resolve from already stored, explicitly approved local facts. No N+1 product fetches; do not loop wc_get_order/get_post_meta per item. ## Positions, formatting and complete-document preview Stable positions in order: `after_order_header`, `before_items`, `after_totals`, `end_of_document`. Both Fixed and Dompdf consume the same blocks. HTTPS anchors create actual PDF URI annotations, never executable actions. No renderer checks a carrier URL over the network. Link safety is URI syntax safety, not endorsement of a destination; the provider must use an approved carrier endpoint. Selection/position/order, typed text/link output, four-language custom labels, 8/9/10/11 pt sizes, plain/compact/boxed layouts and whole-order preview require entitled Pro. Configuration is separately versioned in `lmcc_operational_pdf_v1` (schema lmcc-operational-layout/1), not a published contract template. Dormant preferences survive Pro deactivation/expiry; Free-only advanced settings writes are rejected, not silently applied. Preview/diagnostics require Pro authorization, settings capability, edit_shop_orders, nonce and per-order Woo authorization; they send no email and create no archive. Diagnostic states show status/labels, not sensitive resolved values or exception contents. The existing advanced_v1 formatting filter cannot grant the Pro prerequisite. States: available, no_value, not_registered, not_visible, invalid_url, invalid_value, unsupported_text, resolver_failed, render_budget. Optional delivery failures emit `leanmerce_commerce_assistant_operational_pdf_failed_v1(order_id, code)`; never include secrets in an observer. Trusted internal advanced flag hook `leanmerce_commerce_assistant_operational_pdf_advanced_v1` is owned by the Pro bridge, not a licence bypass invitation. ## Original/current boundary and existing Pro v1 Operational blocks are transient DTO data and are deliberately absent from frozen BasicOrderDocument serialization. New current PDFs read live approved values; archived Free originals and Pro FORMATION_SNAPSHOT contracts never do. Existing historical hashes and template/snapshot values are not reinterpreted. New future originals get the improved table layout but no late operational fields. Keep existing Pro `leanmerce_commerce_assistant_pro_register_document_extensions` definitions/tokens unchanged. The entitled Pro adapter imports only POST_ORDER_CURRENT definitions supporting operational into this single Core registry, maps sensitivity to privacy and preserves provider version/metadata keys/typed resolver. First ID wins on collisions; do not register the same ID through both APIs. Pro FORMATION_SNAPSHOT, `{{EXT:…}}`, `{{EXT_BLOCK:…}}`, capture and historical records remain on the existing API 1.0.0. Old single-field preview remains but the shared full-order PDF is the new operational workflow. New neutral current fields should register directly in Core. Do not silently move a formation token to current phase. Breaking contracts require a new major API and explicit migration, never rewriting originals. The earlier text-only operational_annotations_v1 filter remains merchant-only because it has no customer privacy metadata. Migrate customer-bound late data to typed Core fields; it is not automatically exposed by the compatibility layer. ## Optional customer delivery Account and email are separately opt-in, off by default. Account requires a logged-in owner, order-bound nonce, exact ID and private no-store download; guest orders are not exposed through this account route. Email adds one current PDF to a selected existing eligible Woo customer notification, not a newly generated message. Original-pair routing/formation is unchanged. Only exact billing-email recipient without Cc/Bcc receives this optional attachment. Body content added by other plugins is untouched. Semantic version = SHA-256 of current serialized order facts + normalized visible blocks (not settings revision). The existing durable dispatch ledger records OPERATIONAL_ORDER_PDF UUID, PDF hash, settings revision and submission time/status. Lock spans transport; accepted/attempting/unknown versions do not auto-send again even on another route. Same-content settings saves do not duplicate attachments. A deliberate manual repeat of a native Woo email may still send its ordinary body without the same current attachment; this API does not suppress all Woo notifications. SMTP acceptance is not proof of inbox delivery. Optional current failure never removes already accepted original attachments. Code rollback must preserve the **same current database/private archive**, not restore an old DB dump over new orders. Disable optional current-PDF customer delivery before replacing code with a previously accepted matching pair: the dev10/dev14 baseline had a different Free/Pro execution boundary. It already knew the operational configuration; do not assume those settings are ignored. The new optional service/description settings and derived search cache are additive, and sealed files are retained, not regenerated. Do not treat this as proof that an untested older runtime understands every new optional setting. New Pro requires Core API 1.9.0; do not claim the new Pro runs on an older Free API. No automatic destructive migration or historical regeneration exists.