SIGNALS Docs
Exit Reader View
100%
Theme

Plugin data access

Guarded PluginContext read, list, update and operation methods — field allowlists, custom-field routing, whole-update rejection, audit metadata.plugin, and entity whitelist.

Use the package-bound PluginContext supplied to your handler for plugin operations. During framework-mediated plugin execution, a facade call targeting another package throws PluginPackageMismatchException with reason plugin_package_mismatch; core and admin calls outside a plugin scope retain their existing behaviour.

Context surface

Use the injected PluginContext $context in a handler, $this->context() in a PluginBase lifecycle method, or PluginContext::forPackage('acme/example') in a class-based extension. The package is already bound:

$record = $context->read('accounts', $id);
$page = $context->list('accounts', ['is_active' => ['eq' => true]], ['limit' => 25]);
$context->update('accounts', $id, ['custom_fields' => ['external_id' => $externalId]]);
$result = $context->operation('rentals.change_status', ['rental_id' => $rentalId, 'status' => $statusCode]);

Signatures: read(string $entity, int $id): array, list(string $entity, array $filters = [], array $options = []): array, update(string $entity, int $id, array $attributes): bool, operation(string $action, mixed ...$args): mixed. A list returns {data, next_cursor}. These calls require the corresponding manifest declarations.

Field catalogue / domain meaning of each entity: Plugin data models.

Entity access

Entity User permission Methods Sort keys
accounts accounts.view read, list, update id, name
rentals rentals.view read, list, update id, title
invoices invoices.view read, list, update id
credit_notes invoices.view read, list id
payments invoices.view read, list id
purchase_orders purchase_orders.view read, list id, number
vehicles vehicles.view read, list id, name
catalogue_items catalogue-items.view read, list, update id, name
assets assets.view read, list id
activities activities.view read, list id, title
warehouses settings.view read, list id, name
users users.view read, list id, name
custom_field_definitions custom-fields.view read, list id, name

Unknown entity declarations remain structurally valid but grant no runtime access. Read-only entities refuse writes. The accepted manifest operation delete is reserved and grants nothing: there is no SDK delete method.

Readable fields

These are the maximum supported fields, before manifest projection and acting-user restrictions. Hidden model fields are excluded. custom_fields also admits individual custom_fields.name declarations.

Entity Fields
credit_notes id, number, document_number, draft_identifier, invoice_id, account_id, warehouse_id, status, currency_code, money_unit_facts, exchange_rate, tax_inclusive, subtotal, tax_total, total, total_base, base_currency_code, base_exchange_rate, base_rate_date, document_date, tax_point_at, issued_at, applied_at, voided_at, due_at, posted_at, notes, created_at, updated_at, lines, taxes, custom_fields
payments original_payment_id, correction_kind, posting_date, value_date, id, number, invoice_id, account_id, kind, amount, signed_amount, currency_code, money_unit_facts, payment_method, reference, reference_origin, paid_at, notes, created_at, updated_at, custom_fields
purchase_orders is_billed, billed_reference, billed_at, billed_amount, billed_currency_code, id, number, title, po_type, status, supplier_id, warehouse_id, rental_id, venue_id, currency_code, money_unit_facts, exchange_rate, tax_inclusive, subtotal, tax_total, total, subtotal_base, tax_total_base, total_base, rounding_adjustment, base_currency_code, base_exchange_rate, base_rate_date, reference, supplier_reference, expected_at, starts_at, ends_at, ordered_at, sent_at, received_at, cancelled_at, delivery_at, return_at, aggregate_version, tag_list, supplier_notes, created_at, updated_at, deleted_at, lines
vehicles id, number, name, is_active, description, bookable, plate, vehicle_type_id, catalogue_item_id, payload, volume, width, height, length, tag_list, icon_url, icon_thumb_url, warehouse_ids, created_at, updated_at, deleted_at, custom_fields
accounts id, number, name, account_type, is_active, description, locale, default_currency_code, is_bookable, is_location, per_day, per_hour, per_distance, flat, lawful_basis, customer_tax_profile_id, supplier_tax_profile_id, tag_list, icon_url, icon_thumb_url, external_ref, account_number, tax_number, tax_number_validated, tax_number_validated_at, tax_number_validation, peppol_id, chamber_of_commerce_number, global_location_number, is_cash, is_on_stop, rating, owner_id, rate_band_id, rate_band_tier_id, discount_group_id, tax_zone_id, buyer_type, tax_exempt, invoice_term_id, invoice_term_length, credit_limit, credit_version, title, department, communication_preferences, last_activity_at, lifecycle_state, merged_into_account_id, privacy_restricted_at, purge_pending_at, lifecycle_hold_reason, aggregate_version, created_at, updated_at, deleted_at, history_version, history_projected_version, history_projected_at, last_changed_at, custom_fields, email, phones, emails, migration_ref
rentals id, money_unit_facts, base_money_unit_facts, state_id, title, description, number, reference, customer_notes, state, status, active_version_id, version_count, has_alternatives, account_id, venue_id, warehouse_id, rental_project_id, parent_rental_id, owner_id, starts_at, ends_at, billing_period_starts_at, billing_period_ends_at, ordered_at, quote_expires_at, late_return_notified_at, quote_expiring_notified_at, uses_billable_days, billable_days, is_open_ended, customer_collects, customer_returns, delivery_instructions, collection_instructions, delivery_address_id, collection_address_id, source_rental_id, priority, currency_code, exchange_rate, base_rate_source, exchange_rate_locked, tax_locked, accepted_pricing_manifest_id, accepted_pricing_manifest_hash, accepted_pricing_manifest_schema_version, accepted_pricing_manifest_revision, accepted_pricing_evidence_status, headline_source_digest, headline_calculator_version, subtotal, agreed_total, agreed_price_mode, agreed_price_original_total, rental_total, sale_total, service_total, sub_hire_total, transit_total, loss_damage_total, total, tax_total, base_currency_code, subtotal_base, tax_total_base, base_exchange_rate, base_rate_date, tax_inclusive, invoiced, has_shortage, tag_list, created_at, aggregate_version, base_evidence_snapshot, tree_revision, effective_out_at, on_hire_units, external_ref, updated_at, deleted_at, custom_fields, notes, lost_at, verified_subtotal_base, dashboard_source_revision, dashboard_total_current, dashboard_balance_current, base_evidence_complete, base_evidence_status, pricing_evidence_status
invoices id, state_id, number, draft_identifier, document_number, document_date, tax_point_at, posted_at, voided_at, type, is_posting, marks_rental_invoiced, status, is_locked, account_id, warehouse_id, rental_id, rental_version_id, rental_aggregate_version, rental_tree_revision, rental_headline_source_digest, rental_headline_calculator_version, rental_pricing_manifest_id, rental_pricing_manifest_hash, rental_project_id, generation_identity, supersedes_invoice_id, active_generation_key, issued_at, due_at, overdue_notified_at, paid_at, subtotal, tax_total, total, amount_paid, amount_outstanding, subtotal_base, total_base, amount_paid_base, outstanding_base, base_exchange_rate, base_rate_date, base_currency_code, base_rate_source, credited_total, cancelled_at, cancellation_credit_note_id, written_off_total, currency_code, money_unit_facts, base_money_unit_facts, exchange_rate, tax_inclusive, notes, reference, tag_list, created_at, updated_at, aggregate_version, external_ref, deleted_at, custom_fields, dashboard_source_revision, dashboard_total_current, dashboard_balance_current, base_evidence_complete, outstanding_evidence_complete, base_evidence_status, base_evidence_snapshot, verified_total_base, verified_outstanding_base, lines, taxes
catalogue_items id, name, description, catalogue_item_group_id, catalogue_item_type, preferred_catalogue_type, catalogue_method, weight, barcode, sku, replacement_value, reserve_percent, buffer_before_minutes, turnaround_minutes, track_availability, is_kit, is_flightcaseable, flightcase_template, flightcase_availability_mode, flightcase_checkin_mode, flightcase_max_nesting_depth, flightcase_repack_on_return, is_warehouse_addable, warehouse_add_default_charge, is_active, lifecycle_state, lifecycle_reason, lifecycle_actor_account_id, lifecycle_changed_at, merged_into_catalogue_item_id, current_composition_revision_id, standalone_allowed, system, discountable, item_tax_code_id, purchase_item_tax_code_id, sale_tax_category_id, purchase_tax_category_id, rental_revenue_account_id, sale_revenue_account_id, sub_hire_cost_category_id, sub_hire_price, purchase_cost_category_id, purchase_price, country_of_origin_id, tag_list, icon_url, icon_thumb_url, lock_version, normalized_sku, external_ref, created_at, updated_at, deleted_at, aggregate_version, custom_fields, migration_ref
assets id, catalogue_item_id, warehouse_id, account_id, item_name, asset_number, serial_number, barcode, location, quantity_on_hand, quantity_allocated, quantity_unavailable, starts_at, ends_at, is_virtual, created_at, updated_at, custom_fields
activities id, title, description, location, regarding_id, regarding_type, owner_id, starts_at, ends_at, priority, type_id, status_id, completed, created_at, updated_at
warehouses id, name, is_active, created_at, updated_at
users id, name, email, is_active
custom_field_definitions id, name, display_name, description, module_type, field_type, custom_field_group_id, option_list_id, sort_order, is_required, is_searchable, is_active, created_at, updated_at

Allowed filters

Declare every used field in data_access[].filters. Filters use {field: {operator: value}} with all conditions ANDed. in accepts at most 100 scalar values; contains treats %, _ and ! literally. Unknown fields/operators and wrongly typed values are refused and audited.

Entity Field Operators
credit_notes id eq, in, gte, lte
credit_notes invoice_id eq, in, gte, lte
credit_notes status eq, in
credit_notes warehouse_id eq, in, gte, lte
credit_notes issued_at eq, in, gte, lte
credit_notes applied_at eq, in, gte, lte
credit_notes created_at eq, in, gte, lte
payments id eq, in, gte, lte
payments invoice_id eq, in, gte, lte
payments payment_method eq, in
payments paid_at eq, in, gte, lte
payments created_at eq, in, gte, lte
purchase_orders id eq, in, gte, lte
purchase_orders status eq, in
purchase_orders po_type eq, in
purchase_orders supplier_id eq, in, gte, lte
purchase_orders warehouse_id eq, in, gte, lte
purchase_orders rental_id eq, in, gte, lte
purchase_orders ordered_at eq, in, gte, lte
purchase_orders sent_at eq, in, gte, lte
purchase_orders created_at eq, in, gte, lte
vehicles id eq, in, gte, lte
vehicles name eq, in, contains
vehicles number eq, in, contains
vehicles plate eq, in, contains
vehicles is_active eq, in
vehicles bookable eq, in
vehicles vehicle_type_id eq, in, gte, lte
accounts id eq, in, gte, lte
accounts name eq, in, contains
accounts account_type eq, in
accounts is_active eq, in
accounts created_at eq, in, gte, lte
accounts updated_at eq, in, gte, lte
rentals id eq, in, gte, lte
rentals title eq, in, contains
rentals status eq, in
rentals state eq, in
rentals account_id eq, in, gte, lte
rentals warehouse_id eq, in, gte, lte
rentals starts_at eq, in, gte, lte
rentals ends_at eq, in, gte, lte
rentals created_at eq, in, gte, lte
invoices id eq, in, gte, lte
invoices status eq, in
invoices account_id eq, in, gte, lte
invoices rental_id eq, in, gte, lte
invoices warehouse_id eq, in, gte, lte
invoices total eq, in, gte, lte
invoices issued_at eq, in, gte, lte
invoices due_at eq, in, gte, lte
catalogue_items id eq, in, gte, lte
catalogue_items name eq, in, contains
catalogue_items catalogue_item_type eq, in
catalogue_items catalogue_item_group_id eq, in, gte, lte
catalogue_items is_active eq, in
assets id eq, in, gte, lte
assets item_name eq, in, contains
assets catalogue_item_id eq, in, gte, lte
assets warehouse_id eq, in, gte, lte
assets account_id eq, in, gte, lte
assets asset_number eq, in, contains
assets is_virtual eq, in
activities id eq, in, gte, lte
activities title eq, in, contains
activities owner_id eq, in, gte, lte
activities status_id eq, in, gte, lte
activities completed eq, in
activities starts_at eq, in, gte, lte
activities ends_at eq, in, gte, lte
warehouses id eq, in, gte, lte
warehouses name eq, in, contains
warehouses is_active eq, in
users id eq, in, gte, lte
users name eq, in, contains
users is_active eq, in
custom_field_definitions id eq, in, gte, lte
custom_field_definitions name eq, in, contains
custom_field_definitions module_type eq, in
custom_field_definitions field_type eq, in
custom_field_definitions is_active eq, in

read() semantics

  • Single record by integer id.
  • Returns only fields allowed by the effective read allowlist from the manifest (read_fields override, else fields[]).
  • Requires read in the entity’s operations list.
  • Applies the acting user's entity and warehouse permissions. Account identity, contact PII, credit and commercial fields require the corresponding account field permission; unavailable fields are omitted. Without a signed-in user those fields remain hidden.
  • Account privacy restrictions and purge-pending records, including related rentals and invoices, remain hidden unless the acting user has accounts.privacy.case.
  • Successful single reads do not write audit rows. Audit storage failures do not fail reads or lists.

list() semantics

Declare both read and list, a nonempty readable field list, and each permitted filter in data_access[].filters. Filters use operator maps such as ['is_active' => ['eq' => true]]; values must match the column type. The entity allowlist determines the available operators. Filtering or sorting on a hidden account field is refused.

The result contains data and next_cursor. Options are limit (positive integer, default 25, clamped to 100), sort (default id), direction (asc or desc) and cursor. A non-id sort key must also be a declared read field. The id is the stable ordering tie-breaker. Cursors are signed and bound to the package, entity, filters, ordering, user and tenant. Reusing a cursor for another query is refused. Privacy filtering happens before pagination. Each list call writes one audit event, with no per-record audit rows.

Acting users and system execution

With a signed-in user, reads and lists require the entity permission above and retain normal model scopes. Rentals, invoices and assets use warehouse scoping; models without that scope do not gain one through the SDK. Without a user (jobs, schedules or CLI), reads and lists run in the current tenant without a user warehouse filter. They still enforce the stored manifest, readable fields and privacy rules; list audits identify actor: system.

Account identity, contact PII, credit and commercial fields require their corresponding accounts.identity.view, accounts.contact-pii.view, accounts.credit.view and accounts.commercial.view permissions. Those fields are redacted when no user is present, and cannot be used to infer values by filtering or sorting. Privacy-restricted/purge-pending accounts and linked rentals/invoices are excluded unless the user has accounts.privacy.case. See Runtime visibility for the field groups.

Operations require an acting user and retain the action's Gate checks. No-user calls are refused and audited. SDK 2.1 background jobs may use an explicitly granted integration identity, with direct permissions, field and warehouse clamps. Declaring an operation never grants the actor an additional permission.

update() semantics

  • Each write produces one audit row. Unchanged writes use plugin.data_write on the plugin record, so an audit does not trigger account or rental change listeners.
  • Single record by integer id; transactional write of the submitted attributes.
  • Requires write in operations.
  • Effective write allowlist from write_fields (override) or fields[].
  • Whole-update rejection: any undeclared top-level or nested custom-field key fails the entire update — no partial apply.
  • Successful updates fire AuditableEvent with metadata: ['plugin' => $package] (stored on action_logs.metadata). Action name is {singular}.updated when that name exists in EventRegistry, otherwise plugin.data_updated.
  • Denials fire plugin.data_access_denied with the same metadata shape.

Custom-field routing

  • Nested writes use attribute key custom_fields (flat map of name → value).
  • Nested key x is allowed when the write allowlist declares custom_fields or custom_fields.x.
  • Reads project allowed custom fields into the returned array under the same conventions.

Special case: accounts.email

email is a virtual field for the account’s primary email sync path. It is not a SchemaRegistry core column; declare it explicitly in data_access when needed (as Ledger does).

operation() semantics

  • Name must appear in manifest operations[] and be mapped in PluginOperationRegistry.
  • Seeded mappings include activities.create, activities.complete, favourites.toggle, rentals.change_status, rentals.allocate_assets, documents.generate, and payments.record_external.
  • Operations require a signed-in user; Gate / authorisation still runs inside the target action class.
  • Each successful operation writes one plugin.operation audit row with the operation result and metadata.plugin provenance alongside the acting user.
  • rentals.change_status accepts rental_id, status, optional expected_version and idempotency_key, forwarding the key to the core action.
  • documents.generate accepts the document generation fields plus an optional idempotency_key. Repeating that key reuses the generated document; keys are scoped to the plugin. Without a key, each call creates a new document. Normal source authorization still runs on retries.
  • rentals.allocate_assets accepts the allocation action's idempotency_key.

Contract: Plugin Operation Registry.

Available operations

The first three operations below retain their existing typed arguments; the newer adapters take one plain array. All require a matching operations[] declaration and an acting user or a granted integration identity. IDs resolve inside the current tenant with normal scopes.

Operation Arguments Result
activities.create CreateActivityData $data; use the ordinary acting-user path ActivityData
activities.complete Activity $activity supplied by a framework callback ActivityData
favourites.toggle Model $favouritable, optional User $user subject to the action's authorisation bool
rentals.change_status Array: positive rental_id, nonnegative composite status (state * 100 + status); optional nonnegative expected_version and idempotency_key (max 255) {id, status}
rentals.allocate_assets Array: positive rental_id, nonempty allocations of {rental_line_id, asset_id}; optional expected_version and nonblank idempotency_key (max 255) {id}
payments.record_external Array: connection, invoice, minor-unit amount, currency and external payment identity; optional revision and reconciliation metadata Durable recorded or replayed payment receipt (see below)
payments.refund_external Array: connection, invoice, original payment, amount, currency, reason and external identity Refunded or replayed payment receipt
payments.reverse_external Array: connection, invoice, imported original, remaining amount, currency, reason and external identity Reversed or replayed payment receipt
credit_notes.allocate_external Array: connection, credit note, its invoice, full amount, currency and external identity Allocated, already allocated or replayed receipt
purchase_orders.mark_billed_external Array: connection, purchase order, external identity, billed date and optional amount/currency Marked or replayed billing receipt
purchase_orders.unmark_billed_external Array: connection, purchase order and external identity Unmarked or replayed billing receipt
documents.generate Array: document_template_id or document_type, and source_id or documentable_id; optional documentable_type, output_format (preview, pdf, html_download; default pdf) and idempotency_key {document_id}

Do not query core Eloquent models to manufacture arguments for the older operations. Use a model supplied by a framework callback, or use the array adapters where appropriate. The adapters convert validation failures and unresolved IDs into PluginDataException; action authorisation refusals remain authorisation exceptions.

Asymmetric read / write fields

Ledger declares separate lists so hooks can read contact fields but only write the Ledger id custom field:

- entity: accounts
  read_fields: [name, email, custom_fields.ledger_contact_id]
  write_fields: [custom_fields.ledger_contact_id]
  operations: [read, write]

What you cannot do

Not available Instead
Eloquent on core models from plugin code Use this facade
Partial updates with extra keys Drop undeclared keys before calling update()
Core table migrations plugin_ tables only

Finance collections and money (SDK 2.1)

Declare lines and taxes as whole read fields. Dotted declarations such as lines.unit_cost are refused. Nested rows use these closed projections, ordered by sort_order, id for lines and id for taxes:

Entity Field Nested fields
credit_notes lines id, sort_order, invoice_item_id, description, quantity, unit_price, discount, tax, total, tax_treatment, item_tax_code
credit_notes taxes id, invoice_tax_id, original_invoice_tax_id, tax_rate_id, tax_rate_name, rate_percentage, taxable_amount, tax_amount, tax_group_key, result_type, legal_text, tax_point_at
purchase_orders lines id, sort_order, catalogue_item_id, description, quantity, received_quantity, unit_cost, tax, total, item_tax_code
invoices lines id, sort_order, description, quantity, invoiced_quantity, unit_price, discount, tax, total, tax_treatment, tax_group_key, tax_inclusive, currency_code, catalogue_item_id, source_type, item_tax_code, revenue_account
invoices taxes id, tax_rate_id, tax_rate_name, rate_percentage, taxable_amount, tax_amount, tax_group_key, result_type, legal_text, tax_rule_id, zone_tax_rule_id

item_tax_code and revenue_account contain only {id, name}, or null when absent. Internal cost lineage and tax-allocation JSON are excluded. A record with more than 500 lines fails the entire read or list with PluginDataException::$reason === 'nested_limit' and an audited denial; collections are never silently truncated.

Every money field is an integer in minor units of currency_code; money_unit_facts.decimal_places supplies the exponent. Quantities and rates are decimal strings. Fields ending _base use base_currency_code. Payments expose an absolute amount, raw signed_amount, and kind (payment or refund); account and currency come from the invoice. No original-payment id is exposed because it is not stored on this projection.

Privacy restrictions follow the invoice account for credit notes/payments and the supplier for purchase orders. Acting users require the entity permission and access to the warehouse. Vehicles without warehouse assignments remain globally visible; assigned vehicles must match an accessible warehouse. With no actor, reads remain tenant-wide except for privacy restrictions and field redaction. purchase_orders.tax_inclusive is a derived boolean false, available only when declared. Core has no stored header or per-line inclusive mode: purchase-order unit costs are always exclusive. The flag is not a cost amount and remains visible without costs.view; cost redaction still applies. Purchase-order reads omit totals and each line's unit_cost, tax and total unless the actor has costs.view; no actor also means these fields are omitted. Each list emits one plugin.data_read audit entry.

Finance line calculation contract

Read the frozen amounts; do not re-price a posted document from current catalogue prices or tax rates. All amounts below, including discount, are integer minor units, not percentages. tax is an amount, not a rate. Quantities are decimal strings, not money.

Field Invoice lines Credit-note lines Purchase-order lines
quantity Display/document quantity for this invoice line, not the original rental's remaining quantity Positive quantity being credited from the original invoice line Full ordered quantity
invoiced_quantity Nullable source-ledger contribution consumed by this invoice, at up to six decimal places; not cumulative invoiced quantity and not an extra multiplier Not exposed; use quantity Not exposed; received_quantity records receipts, not the basis of the order's expected totals
unit_price / unit_cost Captured unit-price fact; duration, agreed-price allocation, currency conversion and partial billing can make multiplication insufficient Negated original invoice unit price; do not negate it again unit_cost is tax-exclusive minor units per ordered unit
discount Total discount fact for the entire line, already reflected in total; never per unit and never subtract it again. Rental snapshots can derive it as max(0, rounded(quantity × unit_price) - frozen net), so it is not necessarily a standalone commercial discount Signed negative discount reversal, proportionally apportioned for a partial credit and already included in the signed net total No discount field
tax Frozen allocated line tax, including all applicable groups Signed reversal of original allocated tax; normally negative Expected tax on the ordered quantity, not actual receipt tax
total Net line amount after discounts, before tax. Gross = total + tax Signed net credited amount; normally negative. Signed gross = total + tax Gross expected line amount. Net = total - tax
tax_inclusive Captured pricing mode on the document and invoice line. It does not change total from net to gross Document mode inherited from the invoice; no separate line flag Derived document flag is always false; there is no separate stored header or line mode

For newly entered standalone invoice lines, the net is max(0, rounded(quantity × unit_price) - discount). Existing frozen lines retain their stored net, even when this simple equation cannot reconstruct it. Source-inclusive pricing is normalized before frozen net/tax amounts are exported; do not divide an invoice total by 1 + rate again, even when tax_inclusive is true.

Partial rental billing scales frozen net, discount and tax amounts by the selected contribution and apportions residual pennies; amount-based billing targets the requested gross amount. It does not re-price unit_price × invoiced_quantity. Project-cost lines can display quantity = "1.00" for a fractional source contribution while invoiced_quantity retains the six-decimal value. Export the frozen net and tax; keep both quantities as metadata if a destination cannot represent the same pricing basis.

Invoice and credit-note headers reconcile as subtotal + tax_total = total; line total values represent net contributions. Flat agreed-price headlines can differ from the sum of display-line nets; preserve the header totals and require review when the destination needs a line allocation the projection does not supply. Tax rows carry frozen rate/group evidence. Multiple rates can apply to the same taxable basis: do not sum tax-row taxable_amount values as though they were separate invoice lines. Use tax_group_key where supplied and preserve the tax amounts and result types (standard, zero_rated, exempt, reverse_charge, outside_scope). A zero tax amount alone does not identify a tax treatment.

Purchase-order totals reconcile as subtotal + tax_total + rounding_adjustment = total, and sum(lines.total) + rounding_adjustment = total. Expected line net is the minor-unit result of unit_cost × quantity with quantity normalized to two decimals and HalfUp rounding. Receipt quantities and actual receipt tax do not redefine these expected order amounts. Orders are not supplier bills or payment records.

Worked finance examples

These examples use GBP (two decimal places). Stored snapshot amounts are authoritative; the calculations explain their meaning rather than prescribe re-calculation by plugins.

Example Quantity / source contribution Unit price or cost Discount Line net Line tax Line gross
Exclusive standalone invoice 2.00 1000 100 1900 380 at 20% 2280
Inclusive invoice snapshot 1.00 Captured inclusive price 1200 Use the stored discount fact Stored total = 1000 200 1200; do not extract tax from 1000 again
Half of a frozen rental line Original 4.00, billed 2.00, invoiced_quantity = "2.000000" 1000 Full 400, billed 200 Full 3600, billed 1800 Full 720, billed 360 Billed 2160
Partial credit of the exclusive example Credit 1.00 of original 2.00 -1000 -50 -950 -190 -1140
Two independent tax groups Net bases 1000 at 20% and 2000 at 5% Frozen source facts Already applied 3000 combined 200 + 100 = 300 3300
Two rates on one line One net basis 1000, rates 20% and 5% Frozen source facts Already applied 1000, not 2000 200 + 50 = 250 1250
Purchase order Ordered 2.00, received 1.00 unit_cost = 1000 Not available 2000 400 lines.total = 2400, still the full order
Purchase-order half penny 0.50 unit_cost = 101 Not available 51 (HalfUp from 50.5) 0 51

For invoices, quantity arithmetic follows the tenant's captured rounding policy (HalfUp or Bankers); tax allocation and partial/credit apportionment preserve whole minor units and reconcile to the frozen document totals. For example, 101 × 0.50 can round to 51 with HalfUp or 50 with Bankers. A series of partial invoices or credits can assign a residual penny to the closing document. Reusing a percentage on each line can therefore disagree with stored tax by a penny. Never invent a balancing line to hide a mismatch.

The 500-line limit and pagination

Exactly 500 lines are supported. Requesting lines for a document with 501 or more lines raises nested_limit for the entire read() or list() call. No partial line collection is returned. The limit applies only when lines is requested; a manifest that declares header fields without lines can still read or page document headers.

Nested lines cannot currently be paged through the SDK. list() options limit and cursor page parent documents only; even limit: 1 cannot bypass nested_limit. There is no line entity, line cursor or streaming snapshot endpoint. To page documents (each with at most 500 lines), declare read and list, retain next_cursor, and pass it to the same query:

$cursor = null;
do {
    $page = $context->list('invoices', [], ['limit' => 25, 'cursor' => $cursor]);
    foreach ($page['data'] as $invoice) {
        $context->log('Read invoice', ['invoice_id' => $invoice['id']]);
    }
    $cursor = $page['next_cursor'];
} while ($cursor !== null);

For larger documents, keep the identity and show a review state. A supported line-paging API would need a revision-bound snapshot contract; direct core-table reads and truncation are not supported substitutes.

Record an external payment

SDK 2.1 payments.record_external applies one positive external payment to one invoice through the existing finance action. Declare the operation and a connection. The actor needs payments.record, invoices.view, warehouse access and normal privacy access. Background work may enter a granted integration identity.

$result = $context->operation('payments.record_external', [
    'connection' => 'acme.ledger',
    'invoice_id' => 42,
    'amount' => 125000,
    'currency_code' => 'GBP',
    'external_id' => 'payment-1001#invoice-42',
    'expected_revision' => 17,
    'reference' => 'REM-1001',
    'value_date' => '2026-11-08',
]);

amount is an integer in the invoice currency's minor units and must be positive. Currency must match; there is no FX conversion. external_id is a printable string of at most 191 characters. Optional connection_id selects one connection when the key has multiple installation connections. Optional external_tenant_id (at most 191 characters) defaults to the connection's selected organisation, or an empty string. Optional payment_method is a PaymentMethod value and defaults to bank_transfer; reference is at most 255 characters and notes at most 2000. expected_revision is a nonnegative invoice aggregate version and is recommended.

The result contains status (recorded or replayed), receipt_id, payment_id, invoice_id, invoice_revision, invoice_status and amount_outstanding. Replay returns the original stored result. Keep the same external identity and payload, including the original expected revision, when retrying. Changing only notes does not change identity. A different normalized payload for the same external identity is a conflict. Receipt identity includes tenant database, package, operation, external tenant and external ID; concurrency creates only one payment. Replay resolves the stored receipt before current document visibility lookups and still requires current actor permissions and connection access and emits only plugin.operation.replayed, without another finance posting or payment event.

PluginDataException::$reason distinguishes invalid_fields, connection_unavailable, currency_mismatch, revision_conflict, external_payment_conflict, amount_exceeds_outstanding and invoice_not_payable. Permission failures retain the framework authorization error and a denial audit. Missing or inaccessible invoice IDs are reported as invalid fields without revealing another warehouse's records.

A successful payment records an integration mapping using the connection key as provider and external organisation as tenant. The operation audit includes connection, receipt, external identity and acting user or principal. Finance effects retain their normal after-commit delivery.

value_date accepts Y-m-d. Starting with SDK 2.2, imported payments use an eligible external value date for ledger posting; paid_at, receipt timestamps and document update times stay at the recording instant. Reference origin stays manual. For a multi-invoice external settlement, send one allocation per invoice with a distinct external ID such as payment-1001#invoice-42. Existing receipts replay their stored result unchanged, including older results without posting-date keys.

Posting dates for imported money

SDK 2.2 uses UTC calendar dates, independently of company timezone. The first matching rule wins:

Condition Posting date Reason
No value date Today value_date_absent
Value date is after today Today value_date_in_future
Value date is on or before the effective lock Today period_locked
Value date precedes the source posting Today before_source_posting
Invoice uses carrying-balance settlement Today carrying_balance_policy
Foreign-currency rate cannot be resolved at the value date Today base_rate_unavailable
Otherwise Value date null

The effective lock is the latest of finance.posting_lock_date, any closed currency revaluation period, and (for foreign cash) any recorded revaluation for that currency. The source floor is the invoice issue posting for a payment and the original payment posting for a refund or reversal. A today posting still requires the existing valid currency and balance evidence.

settings.manage can change or reopen the posting lock in Finance settings. It is nullable and must precede today. The immutable event captures posting_date_facts: schema and policy versions, requested value date, posting date, basis, reason, recorded date, effective lock, individual lock sources and source floor. Replay uses those captured facts. Receipts return posting_date, posting_date_basis (value_date or recorded_date), posting_date_reason and value_date. Mappings retain posting_date, posting_basis and value_date. Older receipts replay without these additional result keys.

External refunds and reversals

Declare sdk: ^2.2, the operation and a connection. Both operations require payments.record, invoices.view, warehouse and privacy access on first execution. Replays first validate actor permissions, connection and the canonical payload, then return the stored receipt before current record lookups. Granted integration identities can call them.

$result = $context->operation('payments.refund_external', [
    'connection' => 'acme.ledger',
    'invoice_id' => 42,
    'original_external_id' => 'payment-1001#invoice-42',
    'external_id' => 'refund-77',
    'amount' => 2500,
    'currency_code' => 'GBP',
    'reason' => 'Returned deposit',
    'expected_revision' => 18,
    'value_date' => '2026-11-08',
]);

Specify exactly one of original_payment_id and original_external_id. External originals resolve only through this package's external payment mapping in the same connection and external tenant. Optional inputs are connection_id, external_tenant_id, payment_method, reference, expected_revision and value_date. reason is required retained financial evidence. The receipt hash covers all normalised inputs except connection_id; changing a reason or supplied revision conflicts with an existing correction receipt.

payments.reverse_external accepts the same inputs but requires an imported original belonging to this package and tenant, and an explicit amount equal to its remaining refundable balance. A partial refund can precede reversal of the remainder. A second reversal under another external ID is refused. Provider-origin cash uses its provider refund flow and cannot be externally refunded here.

Both return status (recorded or replayed), receipt_id, kind (refund or reversal), payment_id, original_payment_id, invoice_id, invoice_revision, invoice_status, amount_outstanding, original_refundable_remaining and the posting-date fields. They use the existing operator-refund posting and publish payment.refunded once; reversal is distinguished by kind and readable correction_kind. Mapping meta.kind preserves the distinction after operation receipts are pruned; fully refunded originals return already_refunded.

Refusal reasons are invalid_fields, connection_unavailable, revision_conflict, external_payment_conflict, currency_mismatch, original_payment_not_found, original_payment_not_refundable, amount_exceeds_refundable, and invoice_not_refundable. Reversal adds original_not_imported, already_reversed, already_refunded, and reversal_amount_mismatch. Permission refusals remain authorization exceptions. Replay reauthorizes but emits only plugin.operation.replayed, with no new cash or domain event.

Credit-note allocation

credit_notes.allocate_external requires sdk: ^2.2, credit-notes.apply and invoices.view. Inputs are connection, external_id, credit_note_id, invoice_id, positive amount (the full magnitude of the signed credit total), and currency_code; optionally connection_id, external_tenant_id, and expected_revision (the invoice revision). Supplying value_date, including null, is a validation error.

A draft is applied to its own invoice and returns allocated. An issued or applied credit returns already_allocated without another posting. Replay returns replayed. Results also contain receipt_id, credit_note_id, credit_note_status, legal_number, invoice_id, invoice_revision, invoice_status, and amount_outstanding. Results omit value_date. No integration mapping is created for an allocation. Credits post on the recording date under the existing tax-point rules.

Refusals include common validation/connection/revision reasons plus external_credit_allocation_conflict, cross_invoice_allocation_unsupported, partial_allocation_unsupported, currency_mismatch, credit_note_not_allocatable, and credit_note_out_of_date. Unallocation is not supported; surface the remote unallocation for review. Cross-invoice allocations and partial allocations are also unsupported.

External purchase-order billing markers

purchase_orders.mark_billed_external and purchase_orders.unmark_billed_external require sdk: ^2.2, purchase_orders.view, purchase_orders.edit, costs.view, warehouse access and supplier privacy access. They may run as granted integration identities. These operations record an external billing marker only; they create no supplier bill, payment, tax or ledger entries.

Both take connection, purchase_order_id, external_id, optional connection_id, external_tenant_id, and expected_revision. Marking additionally requires billed_at (a date or ISO timestamp, normalised to UTC); accepts external_reference (defaults to external_id); and accepts optional non-negative integer billed_amount in minor units paired with currency_code matching the PO. Only sent, partially received, or received orders may be marked. Unmarking clears all billing fields and prohibits mark-only inputs.

The marker is separate from the purchasing lifecycle status. Results contain status (marked, unmarked, or replayed), receipt_id, purchase_order_id, purchase_order_revision, is_billed, billed_reference, billed_at, billed_amount, and billed_currency_code. Receipt replay precedes current PO visibility lookups, after checking actor permissions, connection and canonical payload. Each accepted mutation advances the PO revision and publishes purchase_order.updated; identical receipt replay does neither. Fresh calls can correct the marker using the current revision. Conflicts use external_billing_conflict; other refusals include purchase_order_not_billable, currency_mismatch, revision_conflict and the common validation/connection reasons.

The marker appears on the PO page, REST/MCP reads, and declared SDK PO read fields and v2 event data. Billed amount is hidden without costs.view.