From 06131f93140215cfd6beb493b4386d6325b515e6 Mon Sep 17 00:00:00 2001 From: Dimitri Dovgan Date: Sun, 22 Nov 2026 20:53:01 +0100 Subject: [PATCH 1/4] feat: add client delivery addresses and client_delivery_address_id Billomat's API docs gained a "Lieferadressen" page and a new field on invoices and recurring invoices (#102). Both already work in the sandbox. - $billomat->clients->deliveryAddresses (ClientDeliveryAddressesApi): list/listPage/iterateAll, get/getOrFail, create, update, delete on /client-delivery-addresses, with the generated read model and options. label, address_line_2/3 and is_default are only in Billomat's example responses; the sandbox accepts and returns them. No customfield (405). - Marked @experimental: Billomat says the endpoints only become binding on 2027-01-01. New "Experimental API" section in the BC docs and a definition key `experimental` for generated classes. - clientDeliveryAddressId on Invoice, Recurring and their create/update options, appended at the end so existing constructor positions stay. - Spec refreshed from a full mirror (also adds the e-invoice page, which is not implemented yet); the extractor now normalizes paths without a leading slash. - Contract fixtures for the new resource (recorded on the sample client), the new field added to the invoice/recurring fixtures; the fixture anonymizer now also replaces address_line_2/3. - Integration tests create, update and delete addresses on the sample client and reference one from a draft invoice. --- AGENTS.md | 6 +- CHANGELOG.md | 4 + docs/audit.md | 2 + docs/concepts/backward-compatibility.md | 11 + docs/resources/client-delivery-addresses.md | 160 +++++++++++++ docs/resources/clients.md | 1 + docs/resources/invoices.md | 4 +- docs/resources/recurrings.md | 2 + .../client-delivery-addresses.create.json | 11 + docs/spec/billomat.json | 190 ++++++++++++++- .../ClientDeliveryAddressCreateOptions.php | 218 +++++++++++++++++ .../ClientDeliveryAddressUpdateOptions.php | 224 ++++++++++++++++++ src/Api/ClientDeliveryAddressesApi.php | 139 +++++++++++ src/Api/ClientsApi.php | 9 + src/Api/InvoiceCreateOptions.php | 17 ++ src/Api/InvoiceUpdateOptions.php | 16 ++ src/Api/RecurringCreateOptions.php | 16 ++ src/Api/RecurringUpdateOptions.php | 16 ++ src/Model/ClientDeliveryAddress.php | 161 +++++++++++++ src/Model/Invoice.php | 9 + src/Model/Recurring.php | 9 + tests/Api/ClientDeliveryAddressesApiTest.php | 221 +++++++++++++++++ tests/Api/CustomFieldTest.php | 4 +- tests/Api/GetOrFailTest.php | 4 +- tests/Api/ListPagingTest.php | 4 + tests/Contract/ContractFixturesTest.php | 1 + .../client-delivery-addresses/get.json | 21 ++ .../client-delivery-addresses/list.json | 26 ++ tests/Fixtures/Contract/invoices/get.json | 1 + tests/Fixtures/Contract/invoices/list.json | 3 + tests/Fixtures/Contract/recurrings/get.json | 1 + tests/Fixtures/Contract/recurrings/list.json | 1 + ...ClientDeliveryAddressesIntegrationTest.php | 120 ++++++++++ tools/audit-spec-vs-code.php | 4 + .../definitions/client-delivery-addresses.php | 81 +++++++ tools/codegen/definitions/clients.php | 2 + tools/codegen/definitions/invoices.php | 7 +- tools/codegen/definitions/recurrings.php | 7 +- tools/extract-billomat-spec.php | 3 +- tools/generate-json-examples.php | 12 +- tools/generate.php | 10 +- tools/record-fixtures.php | 5 +- 42 files changed, 1742 insertions(+), 21 deletions(-) create mode 100644 docs/resources/client-delivery-addresses.md create mode 100644 docs/snippets/json/client-delivery-addresses.create.json create mode 100644 src/Api/ClientDeliveryAddressCreateOptions.php create mode 100644 src/Api/ClientDeliveryAddressUpdateOptions.php create mode 100644 src/Api/ClientDeliveryAddressesApi.php create mode 100644 src/Model/ClientDeliveryAddress.php create mode 100644 tests/Api/ClientDeliveryAddressesApiTest.php create mode 100644 tests/Fixtures/Contract/client-delivery-addresses/get.json create mode 100644 tests/Fixtures/Contract/client-delivery-addresses/list.json create mode 100644 tests/Integration/ClientDeliveryAddresses/ClientDeliveryAddressesIntegrationTest.php create mode 100644 tools/codegen/definitions/client-delivery-addresses.php diff --git a/AGENTS.md b/AGENTS.md index 2012948b..0a003c87 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,12 +75,12 @@ When adding a new resource, add it as a lazy property hook on `BillomatClient` ( ### Sub-resources -Items, payments, comments, tags, properties and property values hang off their parent `*Api` as lazy property hooks (`public private(set) CommentsApi $comments { get => $this->comments ??= new CommentsApi(...); }`), not on `BillomatClient`. They use one generic class per kind — `CommentsApi`, `TagsApi`, `ItemsApi`, `PaymentsApi`, `PropertiesApi`, `PropertyValuesApi` — extending `AbstractSubResourceApi`, which derives path, envelope keys and parent filter from the parent slug (`'credit-note'` → `/credit-note-comments`, `credit-note-comment`, `credit_note_id`). The property's `@var` carries the `@template` types; the constructor gets the hydrator, the expected `*CreateOptions` class (checked at runtime, the native type is only `WriteOptions`; `ItemsApi` also gets the `*ItemUpdateOptions` class for `update()`) for payments and property values the expected `*Filter` class and for comments the `*CommentActionKey` enum. Methods are uniform: `list()`/`listPage()`/`iterateAll()` take `int $parentId` (payments/property values: `?int $parentId = null`) plus `$filters` — the generated `*PaymentFilter`/`*PropertyValueFilter`, the handwritten `CommentFilter` (action keys, checked against the resource's `*CommentActionKey`), otherwise the handwritten `SubResourceFilter` (sorting and pagination only) — or an array; `create(int $parentId, $options)` adds the parent field to the payload (the parent ID is never a field of the create options); `get()`, `update()`, `delete(): void`. Sub-resources that don't fit (`ReminderItemsApi`, `RecurringEmailReceiversApi`) are small classes on the same base. `ContactsApi` (`$billomat->clients->contacts`) extends `AbstractApi` directly because Billomat's path is `/contacts`, not `/client-contacts`, but has the same signatures (`list(int $parentId, SubResourceFilter|array $filters)`, `create(int $parentId, ContactCreateOptions $options)`). +Items, payments, comments, tags, properties and property values hang off their parent `*Api` as lazy property hooks (`public private(set) CommentsApi $comments { get => $this->comments ??= new CommentsApi(...); }`), not on `BillomatClient`. They use one generic class per kind — `CommentsApi`, `TagsApi`, `ItemsApi`, `PaymentsApi`, `PropertiesApi`, `PropertyValuesApi` — extending `AbstractSubResourceApi`, which derives path, envelope keys and parent filter from the parent slug (`'credit-note'` → `/credit-note-comments`, `credit-note-comment`, `credit_note_id`). The property's `@var` carries the `@template` types; the constructor gets the hydrator, the expected `*CreateOptions` class (checked at runtime, the native type is only `WriteOptions`; `ItemsApi` also gets the `*ItemUpdateOptions` class for `update()`) for payments and property values the expected `*Filter` class and for comments the `*CommentActionKey` enum. Methods are uniform: `list()`/`listPage()`/`iterateAll()` take `int $parentId` (payments/property values: `?int $parentId = null`) plus `$filters` — the generated `*PaymentFilter`/`*PropertyValueFilter`, the handwritten `CommentFilter` (action keys, checked against the resource's `*CommentActionKey`), otherwise the handwritten `SubResourceFilter` (sorting and pagination only) — or an array; `create(int $parentId, $options)` adds the parent field to the payload (the parent ID is never a field of the create options); `get()`, `update()`, `delete(): void`. Sub-resources that don't fit (`ReminderItemsApi`, `RecurringEmailReceiversApi`) are small classes on the same base. `ContactsApi` (`$billomat->clients->contacts`) extends `AbstractApi` directly because Billomat's path is `/contacts`, not `/client-contacts`, but has the same signatures (`list(int $parentId, SubResourceFilter|array $filters)`, `create(int $parentId, ContactCreateOptions $options)`). `ClientDeliveryAddressesApi` (`$billomat->clients->deliveryAddresses`, `/client-delivery-addresses`) follows the same pattern. ### Generated code -Some model/options classes are generated by `tools/generate.php` from `docs/spec/billomat.json` plus a per-resource definition in `tools/codegen/definitions/` (currently Clients, Contacts, Suppliers, Articles, Taxes, Templates, Invoices, Offers, Credit Notes, Recurrings, Letters, Reminders, Delivery Notes, Confirmations and Incomings → `Client`, `Contact`, `Supplier`, `Article`, `TaxRate`, `Template`, `Invoice`, `Offer`, `CreditNote`, `Recurring`, `Letter`, `Reminder`, `DeliveryNote`, `Confirmation`, `Incoming` plus their `*CreateOptions`/`*UpdateOptions`; the five `*Property` definitions with the shared `PropertyCreateOptions`; `*Tag`, `*TagCloudEntry` and `*TagCreateOptions` for all twelve tag resources; `*Comment`, `*Payment`, `*PropertyValue` and the document `*Item` classes with their `*CreateOptions`; `RecurringEmailReceiver` with `RecurringEmailReceiverCreateOptions`; the typed list filters `ClientFilter`, the `*PaymentFilter` and `*PropertyValueFilter` of the sub-resources, `SupplierFilter`, `ArticleFilter`, `UserFilter`, `InvoiceFilter`, `OfferFilter`, `ConfirmationFilter`, `CreditNoteFilter`, `DeliveryNoteFilter`, `LetterFilter`, `ReminderFilter`, `IncomingFilter`, `RecurringFilter` and `TemplateFilter` (definition key `filter`; field types are derived from the spec's filter names and descriptions, enums come from the definition); the lookup models `Unit`, `FreeText`, `EmailTemplate`, `ReminderText` and `CountryTax` with their `*CreateOptions`/`*UpdateOptions`; and the read-only models `Country`, `Currency`, `User` and `IncomingCategory`). Their class docblock says "Generiert aus …". **Never edit these files by hand** — change the definition and run `composer generate`; CI runs `composer generate:check`. The definition holds field order, German docs, read-only response fields and BC overrides; the spec supplies types, defaults and enum values. Property names are the camelCase of the wire name; Billomat's one-word compounds (`actionkey`, `customfield`, `base64file`, `mimetype`, `filesize`) are split via `COMPOUND_WORDS` in `tools/generate.php` (`actionKey`, …) — add new ones there, and use the same names in handwritten classes. Fields Billomat always sends (`id`, item `unit_price`/`quantity`, payment `amount`, parent IDs, tag names, … — verify against `tests/Fixtures/Contract/` first) carry `'model' => ['required' => true]`: non-nullable, no constructor default, and `fromArray()` throws `UnexpectedResponseException` via `ScalarCaster::required()` when they are missing or empty. Every other field is nullable; there is no silent `0`/`''`/`false` fallback (`model.nonNull` was removed and aborts generation). Tests build minimal payloads with `Tests\Support\RequiredFields::of($class)` / `forHydrator()` / `::ANY` instead of hand-written required-field lists. Every generated model ends with `public array $extra = []`: `fromArray()` puts all keys not in its `FIELDS` constant there, `toArray()` spreads them first. A spec field missing from the definition aborts generation, and so does a spec field with a fixed value set (`enum` in the spec) whose definition has no `'enum' => 'SomeEnum'` (or `'enum' => false` to keep it a string on purpose). Comma-separated value lists (payment types) use `'enumList' => true` and become `list`; objects of enum values (user rights, area → level) use `'type' => 'map', 'enum' => 'AccessLevel'` (read-only) and become `array`, dropping empty and unknown values. `*Api` classes stay handwritten. +Some model/options classes are generated by `tools/generate.php` from `docs/spec/billomat.json` plus a per-resource definition in `tools/codegen/definitions/` (currently Clients, Contacts, Client Delivery Addresses, Suppliers, Articles, Taxes, Templates, Invoices, Offers, Credit Notes, Recurrings, Letters, Reminders, Delivery Notes, Confirmations and Incomings → `Client`, `Contact`, `ClientDeliveryAddress`, `Supplier`, `Article`, `TaxRate`, `Template`, `Invoice`, `Offer`, `CreditNote`, `Recurring`, `Letter`, `Reminder`, `DeliveryNote`, `Confirmation`, `Incoming` plus their `*CreateOptions`/`*UpdateOptions`; the five `*Property` definitions with the shared `PropertyCreateOptions`; `*Tag`, `*TagCloudEntry` and `*TagCreateOptions` for all twelve tag resources; `*Comment`, `*Payment`, `*PropertyValue` and the document `*Item` classes with their `*CreateOptions`; `RecurringEmailReceiver` with `RecurringEmailReceiverCreateOptions`; the typed list filters `ClientFilter`, the `*PaymentFilter` and `*PropertyValueFilter` of the sub-resources, `SupplierFilter`, `ArticleFilter`, `UserFilter`, `InvoiceFilter`, `OfferFilter`, `ConfirmationFilter`, `CreditNoteFilter`, `DeliveryNoteFilter`, `LetterFilter`, `ReminderFilter`, `IncomingFilter`, `RecurringFilter` and `TemplateFilter` (definition key `filter`; field types are derived from the spec's filter names and descriptions, enums come from the definition); the lookup models `Unit`, `FreeText`, `EmailTemplate`, `ReminderText` and `CountryTax` with their `*CreateOptions`/`*UpdateOptions`; and the read-only models `Country`, `Currency`, `User` and `IncomingCategory`). Their class docblock says "Generiert aus …". **Never edit these files by hand** — change the definition and run `composer generate`; CI runs `composer generate:check`. The definition holds field order, German docs, read-only response fields and BC overrides; the spec supplies types, defaults and enum values. Property names are the camelCase of the wire name; Billomat's one-word compounds (`actionkey`, `customfield`, `base64file`, `mimetype`, `filesize`) are split via `COMPOUND_WORDS` in `tools/generate.php` (`actionKey`, …) — add new ones there, and use the same names in handwritten classes. Fields Billomat always sends (`id`, item `unit_price`/`quantity`, payment `amount`, parent IDs, tag names, … — verify against `tests/Fixtures/Contract/` first) carry `'model' => ['required' => true]`: non-nullable, no constructor default, and `fromArray()` throws `UnexpectedResponseException` via `ScalarCaster::required()` when they are missing or empty. Every other field is nullable; there is no silent `0`/`''`/`false` fallback (`model.nonNull` was removed and aborts generation). Tests build minimal payloads with `Tests\Support\RequiredFields::of($class)` / `forHydrator()` / `::ANY` instead of hand-written required-field lists. Every generated model ends with `public array $extra = []`: `fromArray()` puts all keys not in its `FIELDS` constant there, `toArray()` spreads them first. A spec field missing from the definition aborts generation, and so does a spec field with a fixed value set (`enum` in the spec) whose definition has no `'enum' => 'SomeEnum'` (or `'enum' => false` to keep it a string on purpose). Comma-separated value lists (payment types) use `'enumList' => true` and become `list`; objects of enum values (user rights, area → level) use `'type' => 'map', 'enum' => 'AccessLevel'` (read-only) and become `array`, dropping empty and unknown values. `*Api` classes stay handwritten. ### HTTP layer @@ -128,7 +128,7 @@ Billomat has no REST endpoint for webhook subscriptions (UI only) — never add - Every list API has `list()`, `listPage()` and `iterateAll()` with the parameter name `$filters` (parent ID first for sub-resources). List methods take `XFilter|array $filters`; `AbstractApi::filterQuery()` turns a `ListFilter` into query parameters. Sorting goes through `OrderBy`, never a hand-written `'order_by' => 'date+DESC'` in SDK code. - Amounts are `Model\Money` (exact decimal on `BcMath\Number`, `ext-bcmath`), never `float`. The generator maps `FLOAT` fields listed in `MONEY_FIELDS` (`tools/generate.php`) to `money`; add new amount fields there. Quantities, tax/discount rates and `quote` stay `float`. Document tax rows are `Model\TaxSummary` (`taxes` field type in the generator). Payloads and `toArray()` carry amounts as strings (`Money::toString()`). Fields with a fixed value set are enums from `src/Model/Enum/`; every enum uses the `FromApi` trait (`fromApi(?string): ?self`, `null`/`""`/unknown → `null`) — exceptions: `RecurringEmailReceiverType` (own case-insensitive `fromApi()`), `WebhookEvent`/`WebhookAction` (parsed strictly, unknown events throw `InvalidWebhookException`) and `Clear` (write-only marker, not backed); generated models hydrate with native `tryFrom()` (`model.fromApi` switches to `fromApi()` for enums with their own tolerance), and enum fields are never `required` (unknown values become `null`); keep `string` only for open sets (salutation, locale, currency code). - All write options implement `WriteOptions` and are immutable: no property assignment, use named arguments or `with*()`. PHP-CS-Fixer is configured to write `clone($this, [...])` without a space. -- The BC promise (`docs/concepts/backward-compatibility.md`) covers everything public that isn't `@internal`, including parameter names. `AbstractApi`, `AbstractSubResourceApi`, all `*Api` constructors, the constructors of `Event\*`, `Page`/`PageInfo` and `HttpException`, `WebhookEvent::envelopeKey()`, `Internal\*`, the `FromApi` trait and `BillomatHttpClient`'s `$sleep` hook (last constructor parameter) are `@internal`; mark new SDK plumbing the same way. Exceptions below `BillomatException`/`HttpException` are `final`; new handwritten read models get `public array $extra = []` like the generated ones. +- The BC promise (`docs/concepts/backward-compatibility.md`) covers everything public that isn't `@internal`, including parameter names. Classes marked `@experimental` (endpoints Billomat still calls preliminary; definition key `experimental` in `tools/codegen/definitions/` adds the tag to generated classes) are excluded until the marker is dropped, see the "Experimental API" section there. `AbstractApi`, `AbstractSubResourceApi`, all `*Api` constructors, the constructors of `Event\*`, `Page`/`PageInfo` and `HttpException`, `WebhookEvent::envelopeKey()`, `Internal\*`, the `FromApi` trait and `BillomatHttpClient`'s `$sleep` hook (last constructor parameter) are `@internal`; mark new SDK plumbing the same way. Exceptions below `BillomatException`/`HttpException` are `final`; new handwritten read models get `public array $extra = []` like the generated ones. - `new Foo()->bar` needs no parentheses (PHP 8.4+); don't write `(new Foo())->bar`. - All API classes are `final`; models are `final readonly`. - PSR-4: `Justpilot\Billomat\` → `src/`, `Justpilot\Billomat\Tests\` → `tests/`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 74964eea..52d63118 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on Keep a Changelog, and this project adheres to Semantic Ve ## [Unreleased] +### Added +- Client delivery addresses (`/client-delivery-addresses`, new in Billomat's API docs): `$billomat->clients->deliveryAddresses` with `list()`/`listPage()`/`iterateAll()`, `get()`/`getOrFail()`, `create()`, `update()` and `delete()`, the read model `ClientDeliveryAddress` and `ClientDeliveryAddressCreateOptions`/`ClientDeliveryAddressUpdateOptions`. Marked `@experimental` until Billomat makes the endpoints binding (2027-01-01), see [Backward compatibility](docs/concepts/backward-compatibility.md#experimental-api) (#102). +- `clientDeliveryAddressId` on `Invoice`, `Recurring` and their create/update options (`client_delivery_address_id`) (#102). + ### Changed - `main` is the 4.x line now (`dev-main` is aliased to `4.x-dev`); security fixes for 3.x go to the `3.x` branch. diff --git a/docs/audit.md b/docs/audit.md index 4a121dc9..f57ea54c 100644 --- a/docs/audit.md +++ b/docs/audit.md @@ -26,6 +26,7 @@ Legende: ✓ vorhanden · ✗ fehlt · — nicht erwartet | `benutzer` | Benutzer | ✓ | ✓ | — | — | ✓ | Read-only; Billomat exponiert kein POST/PUT/DELETE für /users — Benutzerverwaltung ist UI-only. | | `benutzerdefinierte-attribute-filtern` | Benutzerdefinierte Attribute filtern | — | — | — | — | — | Konzept-Doku, kein Api erwartet. | | `briefe` | Briefe | ✓ | ✓ | ✓ | ✓ | ✓ | | +| `e-rechnungen` | E-Rechnungen | ✗ | ✗ | ✗ | ✗ | ✗ | Kein Mapping definiert – Audit-Skript erweitern. | | `eingangsrechnungen` | Eingangsrechnungen | ✓ | ✓ | ✓ | ✓ | ✓ | | | `eingangsrechnungen/attribute` | Attribute | ✓ | — | — | — | ✓ | | | `eingangsrechnungen/inbox` | Inbox | ✓ | ✓ | ✓ | — | ✓ | | @@ -67,6 +68,7 @@ Legende: ✓ vorhanden · ✗ fehlt · — nicht erwartet | `kunden/kontakte` | Kontakte | ✓ | ✓ | ✓ | ✓ | ✓ | | | `kunden/schlagworte` | Schlagworte | ✓ | ✓ | ✓ | — | ✓ | | | `laender` | Länder | ✓ | ✓ | — | — | ✓ | | +| `lieferadressen` | Lieferadressen | ✓ | ✓ | ✓ | ✓ | ✓ | | | `lieferanten` | Lieferanten | ✓ | ✓ | ✓ | ✓ | ✓ | | | `lieferanten/attribute` | Attribute | ✓ | — | — | — | ✓ | | | `lieferanten/schlagworte` | Schlagworte | ✓ | ✓ | ✓ | — | ✓ | | diff --git a/docs/concepts/backward-compatibility.md b/docs/concepts/backward-compatibility.md index dac752cc..ddc6bd5b 100644 --- a/docs/concepts/backward-compatibility.md +++ b/docs/concepts/backward-compatibility.md @@ -23,3 +23,14 @@ Everything public under `Justpilot\Billomat\` that is not marked `@internal`: - **Additions**, which may come with any minor release: new classes, methods, optional parameters at the end of a method, read model properties, enum cases and keys in `$extra`. If you `match` over an SDK enum, add a `default` arm, because Billomat extends its value sets from time to time. - **Message texts** of exceptions and log entries, and the order of log entries and events. Log levels only change in a minor release, with a CHANGELOG entry. - **Billomat's behaviour.** If Billomat stops sending a field, the property stays but becomes `null`; fields Billomat drops for good are removed in the next major version. +- **`@experimental` code**, see below. + +## Experimental API + +Billomat sometimes publishes endpoints before they are final. The SDK supports them early, but marks the classes `@experimental` as long as Billomat calls them preliminary. Experimental classes may change in a minor release (renamed fields, changed types, removed methods) when Billomat changes the endpoint; each change gets a CHANGELOG entry. Once Billomat declares the endpoint final, a minor release drops the marker and the class falls under the promise above. + +Currently experimental, because Billomat's documentation says the endpoints only become binding on 2027-01-01: + +- [Client delivery addresses](../resources/client-delivery-addresses.md): `ClientsApi::$deliveryAddresses`, `ClientDeliveryAddressesApi`, `ClientDeliveryAddress`, `ClientDeliveryAddressCreateOptions`, `ClientDeliveryAddressUpdateOptions`. + +The `clientDeliveryAddressId` field on invoices and recurring invoices is a plain ID and covered as usual. diff --git a/docs/resources/client-delivery-addresses.md b/docs/resources/client-delivery-addresses.md new file mode 100644 index 00000000..27744eac --- /dev/null +++ b/docs/resources/client-delivery-addresses.md @@ -0,0 +1,160 @@ + + +# Client delivery addresses (Lieferadressen) + +API wrapper for client delivery addresses under `/client-delivery-addresses`. A delivery address belongs to exactly one client (`client_id`), so the API is a sub-resource of `clients`, like contacts. Invoices and recurring invoices reference one through `clientDeliveryAddressId`. + +::: warning Experimental +Billomat is still finishing this resource: its documentation says the endpoints only become binding on 2027-01-01. Until then `ClientDeliveryAddressesApi`, `ClientDeliveryAddress` and the two options classes are marked `@experimental` and may change in a minor release, see [Backward compatibility](../concepts/backward-compatibility.md#experimental-api). The endpoints already work in the sandbox (checked on 2026-11-22). +::: + +## Access + +```php +$billomat->clients->deliveryAddresses +``` + +`Justpilot\Billomat\Api\ClientDeliveryAddressesApi`. + +## Endpoint overview + +| Method | HTTP | Path | +|---|---|---| +| `list($parentId, $filters?)` | GET | `/client-delivery-addresses?client_id={id}` | +| `listPage($parentId, $filters?)` | GET | `/client-delivery-addresses?client_id={id}` (page with metadata) | +| `iterateAll($parentId, $filters?, $pageSize?)` | GET | `/client-delivery-addresses?client_id={id}` (lazy over all pages) | +| `get($id)` / `getOrFail($id)` | GET | `/client-delivery-addresses/{id}` | +| `create($parentId, $options)` | POST | `/client-delivery-addresses` | +| `update($id, $options)` | PUT | `/client-delivery-addresses/{id}` | +| `delete($id)` | DELETE | `/client-delivery-addresses/{id}` | + +## Methods + +### `list(int $parentId, SubResourceFilter|array $filters = []): list` + +Lists the delivery addresses of a client. + +```php +foreach ($billomat->clients->deliveryAddresses->list(98765) as $address) { + printf("#%d %s: %s, %s %s%s\n", + $address->id, + $address->label ?? '—', + $address->street ?? '', + $address->zip ?? '', + $address->city ?? '', + $address->isDefault ? ' (default)' : '', + ); +} +``` + +`$filters` takes a `SubResourceFilter` (sorting and pagination) or an array of query parameters; `client_id` always comes from `$parentId`. `listPage()` and `iterateAll()` work as on every list API, see [Pagination](../advanced/pagination.md). + +### `get(int $id): ?ClientDeliveryAddress` + +Returns `null` on 404. `getOrFail(int $id): ClientDeliveryAddress` throws a `NotFoundException` instead. + +### `create(int $parentId, ClientDeliveryAddressCreateOptions $options): ClientDeliveryAddress` + +```php +use Justpilot\Billomat\Api\ClientDeliveryAddressCreateOptions; + +$address = $billomat->clients->deliveryAddresses->create(98765, new ClientDeliveryAddressCreateOptions( + label: 'Warehouse Berlin', + name: 'Musterfirma GmbH', + street: 'Lagerweg 5', + addressLine2: 'Gate 3', + zip: '10115', + city: 'Berlin', + countryCode: 'DE', + isDefault: true, +)); +``` + +The client ID is the first argument of `create()`; the SDK adds it to the payload as `client_id`. All fields of the options are optional. + +### `update(int $id, ClientDeliveryAddressUpdateOptions $options): ClientDeliveryAddress` + +```php +use Justpilot\Billomat\Api\ClientDeliveryAddressUpdateOptions; + +$billomat->clients->deliveryAddresses->update($address->id, new ClientDeliveryAddressUpdateOptions(city: 'Bremen')); +``` + +A partial update: only non-`null` fields are sent, `Clear::Field` empties a field. The client can't be changed. + +### `delete(int $id): void` + +Removes the delivery address. + +## Using a delivery address on an invoice + +```php +use Justpilot\Billomat\Api\InvoiceCreateOptions; + +$invoice = $billomat->invoices->create(new InvoiceCreateOptions( + clientId: 98765, + clientDeliveryAddressId: $address->id, +)); + +$invoice->clientDeliveryAddressId; // same ID, also on get() +``` + +`RecurringCreateOptions`/`RecurringUpdateOptions`, `InvoiceUpdateOptions` and the read models `Invoice` and `Recurring` have the same field. Other document types (offers, confirmations, credit notes, delivery notes) don't have it, neither in Billomat's docs nor in the sandbox responses. + +## Write model: `ClientDeliveryAddressCreateOptions` + +All fields are optional, nullable constructor parameters passed as named arguments. The object is immutable; each field has a `with*()` method. + +| Property | Billomat field | Type | Notes | +|---|---|---|---| +| `label` | `label` | `?string` | Name of the address (e.g. `Warehouse Berlin`) | +| `name` | `name` | `?string` | Company name | +| `salutation` | `salutation` | `?string` | | +| `firstName` | `first_name` | `?string` | | +| `lastName` | `last_name` | `?string` | | +| `street` | `street` | `?string` | | +| `addressLine2` | `address_line_2` | `?string` | Additional address line | +| `addressLine3` | `address_line_3` | `?string` | Additional address line | +| `zip` | `zip` | `?string` | | +| `city` | `city` | `?string` | | +| `state` | `state` | `?string` | State/region | +| `countryCode` | `country_code` | `?string` | ISO 3166-1 alpha-2; Billomat rejects unknown codes with a `ValidationException` | +| `isDefault` | `is_default` | `?bool` | Default delivery address of the client; sent as `1`/`0` | + +Billomat's field table only lists part of these; `label`, `address_line_2`, `address_line_3` and `is_default` appear in its example responses. The sandbox accepts and returns all of them. + +## Write model: `ClientDeliveryAddressUpdateOptions` + +Same fields as the create options, typed `string|Clear|null` (`isDefault`: `bool|Clear|null`). `null` means "leave unchanged", `Clear::Field` sends JSON `null` to empty the field. + +## Read model: `ClientDeliveryAddress` + +| Property | Type | +|---|---| +| `id` | `int` | +| `clientId` | `int` | +| `created` | `?\DateTimeImmutable` | +| `updated` | `?\DateTimeImmutable` | +| `label`, `name`, `salutation`, `firstName`, `lastName` | `?string` | +| `street`, `addressLine2`, `addressLine3`, `zip`, `city`, `state`, `countryCode` | `?string` | +| `isDefault` | `?bool` | +| `extra` | `array` (unmapped fields, see [Models](../concepts/models.md)) | + + +## JSON on the wire + +Billomat's API documentation only shows XML. These are the JSON bodies the SDK sends and receives: requests as the SDK serializes them, responses recorded in the Billomat sandbox and anonymized ([contract fixtures](../../tests/Fixtures/Contract)). Billomat sends every value as a string; the read models cast them (see [Read models](../concepts/models.md)). + +::: code-group +<<< @/snippets/json/client-delivery-addresses.create.json [POST /client-delivery-addresses] +<<< @/../tests/Fixtures/Contract/client-delivery-addresses/get.json [GET /client-delivery-addresses/{id} (response)] +<<< @/../tests/Fixtures/Contract/client-delivery-addresses/list.json [GET /client-delivery-addresses (response)] +::: + + +## Pitfalls + +- **No `customfield`.** Unlike contacts, Billomat answers `GET /client-delivery-addresses/{id}/customfield` with 405, so there are no `getCustomField()`/`setCustomField()` methods. +- **Single-item list quirk.** With exactly one address Billomat returns an object instead of a list; `list()` normalizes it. +- **One default per client.** Creating or updating an address with `isDefault: true` resets the flag on the client's previous default address (checked in the sandbox on 2026-11-22). Reload other addresses if you cache them. +- **No duplicates.** Billomat rejects an address whose fields match an existing address of the same client with a `ValidationException` ("an equal delivery address already exists for this client"). `label` doesn't count: two addresses that only differ in the label are duplicates. diff --git a/docs/resources/clients.md b/docs/resources/clients.md index e1ebb9dc..49b187a6 100644 --- a/docs/resources/clients.md +++ b/docs/resources/clients.md @@ -9,6 +9,7 @@ API wrapper for the Billomat "clients" resource, covering the endpoints under `/ ```php $billomat->clients $billomat->clients->contacts // contact persons of a client, see contacts.md +$billomat->clients->deliveryAddresses // delivery addresses of a client (experimental), see client-delivery-addresses.md $billomat->clients->tags // tags on a client, see client-tags.md $billomat->clients->properties // custom property definitions, see properties.md $billomat->clients->propertyValues // custom property values on a client diff --git a/docs/resources/invoices.md b/docs/resources/invoices.md index 56a1f532..73512e44 100644 --- a/docs/resources/invoices.md +++ b/docs/resources/invoices.md @@ -318,6 +318,7 @@ Constructor: `new InvoiceCreateOptions(int $clientId, …)`. `clientId` is requi |---|---|---| | `clientId` | `client_id` | `int` (required) | | `contactId` | `contact_id` | `?int` | +| `clientDeliveryAddressId` | `client_delivery_address_id` | `?int` (see [delivery addresses](client-delivery-addresses.md)) | | `address` | `address` | `?string` (default: the client's address) | | `numberPre` | `number_pre` | `?string` | | `number` | `number` | `?int` | @@ -387,7 +388,7 @@ For partial updates; it has the same fields as `InvoiceCreateOptions` except `it | Property | Billomat field | Type | |---|---|---| -| `clientId`, `contactId` | same | `int\|Clear\|null` | +| `clientId`, `contactId`, `clientDeliveryAddressId` | same | `int\|Clear\|null` | | `number`, `numberPre`, `numberLength` | same | `int\|Clear\|null`, `string\|Clear\|null`, `int\|Clear\|null` | | `date`, `supplyDate`, `dueDate`, `discountDate` | same | `\DateTimeImmutable\|Clear\|null` | | `supplyDateType` | `supply_date_type` | `SupplyDateType\|Clear\|null` | @@ -450,6 +451,7 @@ Payload for `mail()` (Pixelletter), shared by all document types (invoices, offe | `id` | `int` | | `clientId` | `int` | | `contactId` | `?int` | +| `clientDeliveryAddressId` | `?int` (see [delivery addresses](client-delivery-addresses.md)) | | `created` | `?\DateTimeImmutable` | | `invoiceNumber` | `?string` (empty for `DRAFT`) | | `number`, `numberPre`, `numberLength` | `?int`, `?string`, `?int` | diff --git a/docs/resources/recurrings.md b/docs/resources/recurrings.md index 44813888..ebf787fb 100644 --- a/docs/resources/recurrings.md +++ b/docs/resources/recurrings.md @@ -148,6 +148,7 @@ Constructor: `new RecurringCreateOptions(int $clientId, …)`. `clientId` is req |---|---|---| | `clientId` | `client_id` | `int` (required) | | `contactId` | `contact_id` | `?int` | +| `clientDeliveryAddressId` | `client_delivery_address_id` | `?int` (see [delivery addresses](client-delivery-addresses.md)) | | `address` | `address` | `?string` | | `numberPre` | `number_pre` | `?string` | | `name` | `name` | `?string`, internal name | @@ -229,6 +230,7 @@ Has the same fields as `RecurringCreateOptions`, but `clientId` is optional (for | `id` | `int` | | `clientId` | `int` | | `contactId` | `?int` | +| `clientDeliveryAddressId` | `?int` (see [delivery addresses](client-delivery-addresses.md)) | | `created` | `?\DateTimeImmutable` | | `address` | `?string` | | `supplyDate`, `startDate`, `endDate` | `?\DateTimeImmutable` | diff --git a/docs/snippets/json/client-delivery-addresses.create.json b/docs/snippets/json/client-delivery-addresses.create.json new file mode 100644 index 00000000..c6b060f2 --- /dev/null +++ b/docs/snippets/json/client-delivery-addresses.create.json @@ -0,0 +1,11 @@ +{ + "client-delivery-address": { + "label": "Warehouse Berlin", + "street": "Lagerweg 5", + "zip": "10115", + "city": "Berlin", + "country_code": "DE", + "is_default": 1, + "client_id": 1001 + } +} diff --git a/docs/spec/billomat.json b/docs/spec/billomat.json index ee9c1137..89443320 100644 --- a/docs/spec/billomat.json +++ b/docs/spec/billomat.json @@ -5,7 +5,7 @@ "abo-rechnungen": { "title": "Abo-Rechnungen", "source_url": "https://www.billomat.com/api/abo-rechnungen/", - "content_sha256": "0713b117d9edd19812fb547f08200f008905274a2886690362c36c6862310bdb", + "content_sha256": "31ec3a81c740483f4faf3e8094d99cd5ad2926a582bfd0b663ea136dabfe8ca0", "endpoints": [ { "name": "Alle Abo-Rechnungen auflisten", @@ -77,6 +77,13 @@ "default": null, "required": false }, + { + "name": "client_delivery_address_id", + "type": "INT", + "description_de": "ID der Lieferadresse", + "default": null, + "required": false + }, { "name": "template_id", "type": "INT", @@ -2159,6 +2166,72 @@ } ] }, + "e-rechnungen": { + "title": "E-Rechnungen", + "source_url": "https://www.billomat.com/api/e-rechnungen/", + "content_sha256": "956703c7e75f8a411e970c4c14e9f803a3169089a215df802d60e197f5b1d275", + "endpoints": [ + { + "name": "Rechnung validieren", + "method": "GET", + "path": "/api/finax-e-invoice/{id}/validate", + "description_de": "Prüft, ob aus der Rechnung eine gültige E-Rechnung erzeugt werden kann. Die Rechnung wird dabei nur zur Prüfung an den E-Rechnungs-Dienst übergeben: Es wird kein Dokument erzeugt, gespeichert oder zurückgegeben." + }, + { + "name": "Abo-Rechnung validierien", + "method": "GET", + "path": "/api/finax-e-invoice/{id}/validate-recurring", + "description_de": "Prüft, ob aus der Abo-Rechnung gültige E-Rechnungen erzeugt werden können. Die Abo-Rechnung wird dabei nur zur Prüfung an den E-Rechnungs-Dienst übergeben: Es wird kein Dokument erzeugt, gespeichert oder zurückgegeben." + }, + { + "name": "E-Rechnung (XML) einer Rechnung aufrufen", + "method": "GET", + "path": "/api/finax-e-invoice/{id}/xml", + "description_de": "Gibt das CII-XML einer Rechnung zurück. Die Rechnung muss abgeschlossen sein, ihr Status darf also nicht DRAFT sein.", + "fields": [ + { + "name": "element_id", + "type": "INT", + "description_de": "ID der Rechnung", + "default": null, + "required": false + }, + { + "name": "type", + "type": "ALNUM („e-invoice“, „zugferd“)", + "description_de": "Format des Dokuments", + "default": null, + "required": false + }, + { + "name": "filename", + "type": "ALNUM", + "description_de": "Dateiname, unter dem das Dokument angeboten wird", + "default": null, + "required": false + }, + { + "name": "url", + "type": "ALNUM", + "description_de": "Download-Link des Dokuments", + "default": null, + "required": false + } + ] + }, + { + "name": "ZUGFeRD-PDF einer Rechnung aufrufen", + "method": "GET", + "path": "/api/finax-e-invoice/{id}/zugferd", + "description_de": "Gibt das ZUGFeRD-PDF einer Rechnung zurück, also das PDF der Rechnung mit eingebettetem CII-XML. Die Rechnung muss abgeschlossen sein, ihr Status darf also nicht DRAFT sein." + }, + { + "name": "Status-Codes", + "method": null, + "path": null + } + ] + }, "eingangsrechnungen": { "title": "Eingangsrechnungen", "source_url": "https://www.billomat.com/api/eingangsrechnungen/", @@ -5648,6 +5721,110 @@ } ] }, + "lieferadressen": { + "title": "Lieferadressen", + "source_url": "https://www.billomat.com/api/lieferadressen/", + "content_sha256": "31ce1da57393129c8be12e9750824c11574d20ef42891dd604c50ffc9ec365d7", + "endpoints": [ + { + "name": "Alle Lieferadressen auflisten", + "method": "GET", + "path": "/api/client-delivery-addresses" + }, + { + "name": "Einzelne Lieferadresse abrufen", + "method": "GET", + "path": "/api/client-delivery-addresses/{id}" + }, + { + "name": "Lieferadresse erstellen", + "method": "POST", + "path": "/api/client-delivery-addresses", + "fields": [ + { + "name": "client_id", + "type": "INT", + "description_de": "ID des zur Lieferadresse gehörenden Kunden", + "default": null, + "required": true + }, + { + "name": "name", + "type": "ALNUM", + "description_de": "Firmenname", + "default": null, + "required": false + }, + { + "name": "street", + "type": "ALNUM", + "description_de": "Straße", + "default": null, + "required": false + }, + { + "name": "zip", + "type": "ALNUM", + "description_de": "PLZ", + "default": null, + "required": false + }, + { + "name": "city", + "type": "ALNUM", + "description_de": "Ort", + "default": null, + "required": false + }, + { + "name": "state", + "type": "ALNUM", + "description_de": "Bundesland, Bezirk, Region", + "default": null, + "required": false + }, + { + "name": "country_code", + "type": "Ländercode nach ISO 3166 Alpha-2", + "description_de": "Land", + "default": null, + "required": false + }, + { + "name": "first_name", + "type": "ALNUM", + "description_de": "Vorname", + "default": null, + "required": false + }, + { + "name": "last_name", + "type": "ALNUM", + "description_de": "Nachname", + "default": null, + "required": false + }, + { + "name": "salutation", + "type": "ALNUM", + "description_de": "Anrede", + "default": null, + "required": false + } + ] + }, + { + "name": "Lieferadresse bearbeiten", + "method": "PUT", + "path": "/api/client-delivery-addresses/{id}" + }, + { + "name": "Lieferadresse löschen", + "method": "DELETE", + "path": "/api/client-delivery-addresses/{id}" + } + ] + }, "lieferanten": { "title": "Lieferanten", "source_url": "https://www.billomat.com/api/lieferanten/", @@ -6750,7 +6927,7 @@ "rechnungen": { "title": "Rechnungen", "source_url": "https://www.billomat.com/api/rechnungen/", - "content_sha256": "be4bb021896358985968c8c27e608a8bb015cbeecaa4fe7e8de74a3e877e38e0", + "content_sha256": "eb1beb77ad3731a6bc286462855a31a2a89c8a0cec6d574fdc809e37f628d094", "endpoints": [ { "name": "Alle Rechnungen auflisten", @@ -6840,6 +7017,13 @@ "default": null, "required": false }, + { + "name": "client_delivery_address_id", + "type": "INT", + "description_de": "ID der Lieferadresse", + "default": null, + "required": false + }, { "name": "address", "type": "ALNUM", @@ -7173,7 +7357,7 @@ { "name": "Rechnung an Inkassodienstleister übergeben", "method": "PUT", - "path": "/api/invoices/{invoiceId}&amp;gt;/encash" + "path": "/api/invoices/{invoiceId}&amp;amp;gt;/encash" } ] }, diff --git a/src/Api/ClientDeliveryAddressCreateOptions.php b/src/Api/ClientDeliveryAddressCreateOptions.php new file mode 100644 index 00000000..2b6b66cd --- /dev/null +++ b/src/Api/ClientDeliveryAddressCreateOptions.php @@ -0,0 +1,218 @@ + $label]); + } + + /** Kopie mit geändertem `name`. */ + public function withName(?string $name): self + { + return clone($this, ['name' => $name]); + } + + /** Kopie mit geändertem `salutation`. */ + public function withSalutation(?string $salutation): self + { + return clone($this, ['salutation' => $salutation]); + } + + /** Kopie mit geändertem `firstName`. */ + public function withFirstName(?string $firstName): self + { + return clone($this, ['firstName' => $firstName]); + } + + /** Kopie mit geändertem `lastName`. */ + public function withLastName(?string $lastName): self + { + return clone($this, ['lastName' => $lastName]); + } + + /** Kopie mit geändertem `street`. */ + public function withStreet(?string $street): self + { + return clone($this, ['street' => $street]); + } + + /** Kopie mit geändertem `addressLine2`. */ + public function withAddressLine2(?string $addressLine2): self + { + return clone($this, ['addressLine2' => $addressLine2]); + } + + /** Kopie mit geändertem `addressLine3`. */ + public function withAddressLine3(?string $addressLine3): self + { + return clone($this, ['addressLine3' => $addressLine3]); + } + + /** Kopie mit geändertem `zip`. */ + public function withZip(?string $zip): self + { + return clone($this, ['zip' => $zip]); + } + + /** Kopie mit geändertem `city`. */ + public function withCity(?string $city): self + { + return clone($this, ['city' => $city]); + } + + /** Kopie mit geändertem `state`. */ + public function withState(?string $state): self + { + return clone($this, ['state' => $state]); + } + + /** Kopie mit geändertem `countryCode`. */ + public function withCountryCode(?string $countryCode): self + { + return clone($this, ['countryCode' => $countryCode]); + } + + /** Kopie mit geändertem `isDefault`. */ + public function withIsDefault(?bool $isDefault): self + { + return clone($this, ['isDefault' => $isDefault]); + } + + /** + * Serialisiert die Options in ein Billomat-Payload-Array. + * + * @return array + */ + public function toArray(): array + { + return array_filter([ + 'label' => $this->label, + 'name' => $this->name, + 'salutation' => $this->salutation, + 'first_name' => $this->firstName, + 'last_name' => $this->lastName, + 'street' => $this->street, + 'address_line_2' => $this->addressLine2, + 'address_line_3' => $this->addressLine3, + 'zip' => $this->zip, + 'city' => $this->city, + 'state' => $this->state, + 'country_code' => $this->countryCode, + 'is_default' => null === $this->isDefault ? null : ($this->isDefault ? 1 : 0), + ], static fn (mixed $v): bool => null !== $v); + } +} diff --git a/src/Api/ClientDeliveryAddressUpdateOptions.php b/src/Api/ClientDeliveryAddressUpdateOptions.php new file mode 100644 index 00000000..4b16b483 --- /dev/null +++ b/src/Api/ClientDeliveryAddressUpdateOptions.php @@ -0,0 +1,224 @@ + $label]); + } + + /** Kopie mit geändertem `name`. */ + public function withName(string|Clear|null $name): self + { + return clone($this, ['name' => $name]); + } + + /** Kopie mit geändertem `salutation`. */ + public function withSalutation(string|Clear|null $salutation): self + { + return clone($this, ['salutation' => $salutation]); + } + + /** Kopie mit geändertem `firstName`. */ + public function withFirstName(string|Clear|null $firstName): self + { + return clone($this, ['firstName' => $firstName]); + } + + /** Kopie mit geändertem `lastName`. */ + public function withLastName(string|Clear|null $lastName): self + { + return clone($this, ['lastName' => $lastName]); + } + + /** Kopie mit geändertem `street`. */ + public function withStreet(string|Clear|null $street): self + { + return clone($this, ['street' => $street]); + } + + /** Kopie mit geändertem `addressLine2`. */ + public function withAddressLine2(string|Clear|null $addressLine2): self + { + return clone($this, ['addressLine2' => $addressLine2]); + } + + /** Kopie mit geändertem `addressLine3`. */ + public function withAddressLine3(string|Clear|null $addressLine3): self + { + return clone($this, ['addressLine3' => $addressLine3]); + } + + /** Kopie mit geändertem `zip`. */ + public function withZip(string|Clear|null $zip): self + { + return clone($this, ['zip' => $zip]); + } + + /** Kopie mit geändertem `city`. */ + public function withCity(string|Clear|null $city): self + { + return clone($this, ['city' => $city]); + } + + /** Kopie mit geändertem `state`. */ + public function withState(string|Clear|null $state): self + { + return clone($this, ['state' => $state]); + } + + /** Kopie mit geändertem `countryCode`. */ + public function withCountryCode(string|Clear|null $countryCode): self + { + return clone($this, ['countryCode' => $countryCode]); + } + + /** Kopie mit geändertem `isDefault`. */ + public function withIsDefault(bool|Clear|null $isDefault): self + { + return clone($this, ['isDefault' => $isDefault]); + } + + /** + * Serialisiert die Options in ein Billomat-Payload-Array. + * + * Nicht gesetzte Felder (null) fehlen im Payload, {@see Clear::Field} wird als null gesendet und leert das Feld. + * + * @return array + */ + public function toArray(): array + { + return array_map( + static fn (mixed $v): mixed => $v instanceof Clear ? null : $v, + array_filter([ + 'label' => $this->label, + 'name' => $this->name, + 'salutation' => $this->salutation, + 'first_name' => $this->firstName, + 'last_name' => $this->lastName, + 'street' => $this->street, + 'address_line_2' => $this->addressLine2, + 'address_line_3' => $this->addressLine3, + 'zip' => $this->zip, + 'city' => $this->city, + 'state' => $this->state, + 'country_code' => $this->countryCode, + 'is_default' => \is_bool($this->isDefault) ? ($this->isDefault ? 1 : 0) : $this->isDefault, + ], static fn (mixed $v): bool => null !== $v), + ); + } +} diff --git a/src/Api/ClientDeliveryAddressesApi.php b/src/Api/ClientDeliveryAddressesApi.php new file mode 100644 index 00000000..bb13a96a --- /dev/null +++ b/src/Api/ClientDeliveryAddressesApi.php @@ -0,0 +1,139 @@ +clients->deliveryAddresses`. + * + * Doku: https://www.billomat.com/api/lieferadressen/ + * + * Endpoints: + * - GET /client-delivery-addresses?client_id={id} + * - GET /client-delivery-addresses/{id} + * - POST /client-delivery-addresses + * - PUT /client-delivery-addresses/{id} + * - DELETE /client-delivery-addresses/{id} + * + * Eine Lieferadresse nutzt man über `clientDeliveryAddressId` in den Options von Rechnungen + * und Abo-Rechnungen. Ein `customfield` unterstützt die Ressource nicht. + * + * @experimental Billomat stellt die Lieferadressen noch fertig; laut Doku gelten die Endpunkte erst ab dem + * 01.01.2027 verbindlich. Bis dahin kann sich die Klasse auch in einem Minor-Release ändern + * (siehe docs/concepts/backward-compatibility.md). + */ +final class ClientDeliveryAddressesApi extends AbstractApi +{ + /** + * Listet die Lieferadressen eines Kunden. + * + * @param int $parentId ID des Kunden (`client_id`) + * @param SubResourceFilter|array|null> $filters Sortierung, Seite, … + * + * @return list + */ + #[NoDiscard] + public function list(int $parentId, SubResourceFilter|array $filters = []): array + { + return $this->listResource('/client-delivery-addresses', 'client-delivery-addresses', 'client-delivery-address', ClientDeliveryAddress::fromArray(...), $this->clientFilter($parentId, $filters)); + } + + /** + * Wie {@see list()}, liefert aber zusätzlich die Pagination-Metadaten. + * + * @param int $parentId ID des Kunden (`client_id`) + * @param SubResourceFilter|array|null> $filters Sortierung, Seite, … + * + * @return Page + */ + #[NoDiscard] + public function listPage(int $parentId, SubResourceFilter|array $filters = []): Page + { + return $this->listResourcePage('/client-delivery-addresses', 'client-delivery-addresses', 'client-delivery-address', ClientDeliveryAddress::fromArray(...), $this->clientFilter($parentId, $filters)); + } + + /** + * Iteriert lazy über alle Lieferadressen eines Kunden. + * + * @param int $parentId ID des Kunden (`client_id`) + * @param SubResourceFilter|array|null> $filters Sortierung, Seite, … + * + * @return Generator + */ + #[NoDiscard] + public function iterateAll(int $parentId, SubResourceFilter|array $filters = [], int $pageSize = 100): Generator + { + yield from $this->iterateResource('/client-delivery-addresses', 'client-delivery-addresses', 'client-delivery-address', ClientDeliveryAddress::fromArray(...), $this->clientFilter($parentId, $filters), $pageSize); + } + + #[NoDiscard] + public function get(int $id): ?ClientDeliveryAddress + { + return $this->getResource("/client-delivery-addresses/{$id}", 'client-delivery-address', ClientDeliveryAddress::fromArray(...), 'fetching client delivery address'); + } + + /** + * Wie {@see get()}, wirft aber eine {@see NotFoundException} statt null zurückzugeben. + * + * @throws NotFoundException wenn es den Datensatz nicht gibt (404) + */ + #[NoDiscard] + public function getOrFail(int $id): ClientDeliveryAddress + { + return $this->get($id) ?? throw $this->notFound("/client-delivery-addresses/{$id}"); + } + + /** + * Legt eine Lieferadresse bei einem Kunden an. + * + * @param int $parentId ID des Kunden (`client_id`) + * + * @throws ValidationException z. B. bei einem ungültigen Ländercode („no valid country_code given“) + * @throws AuthenticationException + * @throws HttpException + */ + public function create(int $parentId, ClientDeliveryAddressCreateOptions $options): ClientDeliveryAddress + { + $payload = ['client-delivery-address' => [...$options->toArray(), 'client_id' => $parentId]]; + + $data = $this->postJson('/client-delivery-addresses', $payload); + + return ClientDeliveryAddress::fromArray($this->unwrapEnvelope($data, 'client-delivery-address', 'creating client delivery address')); + } + + public function update(int $id, ClientDeliveryAddressUpdateOptions $options): ClientDeliveryAddress + { + $payload = ['client-delivery-address' => $options->toArray()]; + + $data = $this->putJson("/client-delivery-addresses/{$id}", $payload); + + return ClientDeliveryAddress::fromArray($this->unwrapEnvelope($data, 'client-delivery-address', 'updating client delivery address')); + } + + public function delete(int $id): void + { + $this->deleteVoid("/client-delivery-addresses/{$id}"); + } + + /** + * `client_id` ist die Grundlage der Liste und hat Vorrang vor einem gleichnamigen Filter. + * + * @param SubResourceFilter|array|null> $filters + * + * @return array|null> + */ + private function clientFilter(int $parentId, SubResourceFilter|array $filters): array + { + return ['client_id' => $parentId] + self::filterQuery($filters); + } +} diff --git a/src/Api/ClientsApi.php b/src/Api/ClientsApi.php index b263958e..46222fd1 100644 --- a/src/Api/ClientsApi.php +++ b/src/Api/ClientsApi.php @@ -39,6 +39,15 @@ final class ClientsApi extends AbstractApi get => $this->contacts ??= new ContactsApi($this->http); } + /** + * Lieferadressen der Kunden, siehe {@see ClientDeliveryAddressesApi}. + * + * @experimental wie {@see ClientDeliveryAddressesApi}: Billomat stellt die Endpunkte noch fertig (verbindlich ab 01.01.2027) + */ + public private(set) ClientDeliveryAddressesApi $deliveryAddresses { + get => $this->deliveryAddresses ??= new ClientDeliveryAddressesApi($this->http); + } + /** * Schlagworte, siehe {@see TagsApi}. * diff --git a/src/Api/InvoiceCreateOptions.php b/src/Api/InvoiceCreateOptions.php index 8a328cc2..18ab6d42 100644 --- a/src/Api/InvoiceCreateOptions.php +++ b/src/Api/InvoiceCreateOptions.php @@ -260,6 +260,15 @@ public function __construct( * Typ: INT */ public ?int $freeTextId = null, + /** + * ID der Lieferadresse des Kunden. + * + * Siehe ClientDeliveryAddressesApi ($billomat->clients->deliveryAddresses). + * + * Billomat-Feld: client_delivery_address_id + * Typ: INT + */ + public ?int $clientDeliveryAddressId = null, /** * Positionen, die beim Anlegen mitgesendet werden. * @@ -447,6 +456,12 @@ public function withFreeTextId(?int $freeTextId): self return clone($this, ['freeTextId' => $freeTextId]); } + /** Kopie mit geändertem `clientDeliveryAddressId`. */ + public function withClientDeliveryAddressId(?int $clientDeliveryAddressId): self + { + return clone($this, ['clientDeliveryAddressId' => $clientDeliveryAddressId]); + } + /** Kopie mit einer zusätzlichen Position. */ public function withItem(InvoiceItemCreateOptions $item): self { @@ -496,6 +511,7 @@ public static function fromArray(array $data): self paymentTypes: ListCaster::toEnumList($data['payment_types'] ?? null, PaymentType::class), templateId: ScalarCaster::toIntOrNull($data['template_id'] ?? null), freeTextId: ScalarCaster::toIntOrNull($data['free_text_id'] ?? null), + clientDeliveryAddressId: ScalarCaster::toIntOrNull($data['client_delivery_address_id'] ?? null), ); } @@ -509,6 +525,7 @@ public function toArray(): array $data = array_filter([ 'client_id' => $this->clientId, 'contact_id' => $this->contactId, + 'client_delivery_address_id' => $this->clientDeliveryAddressId, 'address' => $this->address, 'number_pre' => $this->numberPre, 'number' => $this->number, diff --git a/src/Api/InvoiceUpdateOptions.php b/src/Api/InvoiceUpdateOptions.php index d4c22e82..b03d47b5 100644 --- a/src/Api/InvoiceUpdateOptions.php +++ b/src/Api/InvoiceUpdateOptions.php @@ -240,6 +240,15 @@ public function __construct( * Typ: INT */ public int|Clear|null $freeTextId = null, + /** + * ID der Lieferadresse des Kunden. + * + * Siehe ClientDeliveryAddressesApi ($billomat->clients->deliveryAddresses). + * + * Billomat-Feld: client_delivery_address_id + * Typ: INT + */ + public int|Clear|null $clientDeliveryAddressId = null, ) { } @@ -421,6 +430,12 @@ public function withFreeTextId(int|Clear|null $freeTextId): self return clone($this, ['freeTextId' => $freeTextId]); } + /** Kopie mit geändertem `clientDeliveryAddressId`. */ + public function withClientDeliveryAddressId(int|Clear|null $clientDeliveryAddressId): self + { + return clone($this, ['clientDeliveryAddressId' => $clientDeliveryAddressId]); + } + /** * Serialisiert die Options in ein Billomat-Payload-Array. * @@ -435,6 +450,7 @@ public function toArray(): array array_filter([ 'client_id' => $this->clientId, 'contact_id' => $this->contactId, + 'client_delivery_address_id' => $this->clientDeliveryAddressId, 'address' => $this->address, 'number_pre' => $this->numberPre, 'number' => $this->number, diff --git a/src/Api/RecurringCreateOptions.php b/src/Api/RecurringCreateOptions.php index b67ea75a..0dd93b00 100644 --- a/src/Api/RecurringCreateOptions.php +++ b/src/Api/RecurringCreateOptions.php @@ -338,6 +338,15 @@ public function __construct( * Typ: INT */ public ?int $confirmationId = null, + /** + * ID der Lieferadresse des Kunden. + * + * Siehe ClientDeliveryAddressesApi ($billomat->clients->deliveryAddresses). + * + * Billomat-Feld: client_delivery_address_id + * Typ: INT + */ + public ?int $clientDeliveryAddressId = null, /** * Positionen, die beim Anlegen mitgesendet werden. * @@ -591,6 +600,12 @@ public function withConfirmationId(?int $confirmationId): self return clone($this, ['confirmationId' => $confirmationId]); } + /** Kopie mit geändertem `clientDeliveryAddressId`. */ + public function withClientDeliveryAddressId(?int $clientDeliveryAddressId): self + { + return clone($this, ['clientDeliveryAddressId' => $clientDeliveryAddressId]); + } + /** Kopie mit einer zusätzlichen Position. */ public function withItem(RecurringItemCreateOptions $item): self { @@ -607,6 +622,7 @@ public function toArray(): array $data = array_filter([ 'client_id' => $this->clientId, 'contact_id' => $this->contactId, + 'client_delivery_address_id' => $this->clientDeliveryAddressId, 'address' => $this->address, 'number_pre' => $this->numberPre, 'supply_date' => $this->supplyDate?->format('Y-m-d'), diff --git a/src/Api/RecurringUpdateOptions.php b/src/Api/RecurringUpdateOptions.php index b9b1aec1..ad4deb42 100644 --- a/src/Api/RecurringUpdateOptions.php +++ b/src/Api/RecurringUpdateOptions.php @@ -318,6 +318,15 @@ public function __construct( * Typ: INT */ public int|Clear|null $confirmationId = null, + /** + * ID der Lieferadresse des Kunden. + * + * Siehe ClientDeliveryAddressesApi ($billomat->clients->deliveryAddresses). + * + * Billomat-Feld: client_delivery_address_id + * Typ: INT + */ + public int|Clear|null $clientDeliveryAddressId = null, ) { } @@ -565,6 +574,12 @@ public function withConfirmationId(int|Clear|null $confirmationId): self return clone($this, ['confirmationId' => $confirmationId]); } + /** Kopie mit geändertem `clientDeliveryAddressId`. */ + public function withClientDeliveryAddressId(int|Clear|null $clientDeliveryAddressId): self + { + return clone($this, ['clientDeliveryAddressId' => $clientDeliveryAddressId]); + } + /** * Serialisiert die Options in ein Billomat-Payload-Array. * @@ -579,6 +594,7 @@ public function toArray(): array array_filter([ 'client_id' => $this->clientId, 'contact_id' => $this->contactId, + 'client_delivery_address_id' => $this->clientDeliveryAddressId, 'address' => $this->address, 'number_pre' => $this->numberPre, 'supply_date' => $this->supplyDate instanceof DateTimeImmutable ? $this->supplyDate->format('Y-m-d') : $this->supplyDate, diff --git a/src/Model/ClientDeliveryAddress.php b/src/Model/ClientDeliveryAddress.php new file mode 100644 index 00000000..457c014c --- /dev/null +++ b/src/Model/ClientDeliveryAddress.php @@ -0,0 +1,161 @@ + true, + 'client_id' => true, + 'created' => true, + 'updated' => true, + 'label' => true, + 'name' => true, + 'salutation' => true, + 'first_name' => true, + 'last_name' => true, + 'street' => true, + 'address_line_2' => true, + 'address_line_3' => true, + 'zip' => true, + 'city' => true, + 'state' => true, + 'country_code' => true, + 'is_default' => true, + ]; + + /** @param array $extra */ + public function __construct( + /** Interne Billomat-ID der Lieferadresse. */ + public int $id, + /** ID des Kunden, zu dem die Lieferadresse gehört. */ + public int $clientId, + /** Erstellungszeitpunkt der Lieferadresse. */ + public ?DateTimeImmutable $created = null, + /** Zeitpunkt der letzten Änderung. */ + public ?DateTimeImmutable $updated = null, + /** + * Bezeichnung der Lieferadresse. + * + * Beispiel: "Lager Berlin" + */ + public ?string $label = null, + /** Firmenname. */ + public ?string $name = null, + /** Anrede. */ + public ?string $salutation = null, + /** Vorname. */ + public ?string $firstName = null, + /** Nachname. */ + public ?string $lastName = null, + /** Straße. */ + public ?string $street = null, + /** Adresszusatz (Zeile 2). */ + public ?string $addressLine2 = null, + /** Adresszusatz (Zeile 3). */ + public ?string $addressLine3 = null, + /** Postleitzahl. */ + public ?string $zip = null, + /** Ort. */ + public ?string $city = null, + /** Bundesland / Bezirk / Region. */ + public ?string $state = null, + /** + * Ländercode (ISO 3166-1 Alpha-2). + * + * Beispiel: "DE", "AT", "CH" + */ + public ?string $countryCode = null, + /** Standard-Lieferadresse des Kunden? */ + public ?bool $isDefault = null, + /** + * Felder, die Billomat liefert, das SDK aber (noch) nicht abbildet – roh, wie in der Response. + * + * Neue Billomat-Felder gehen so nicht verloren; toArray() gibt sie mit aus. + */ + public array $extra = [], + ) { + } + + /** + * Hydriert das Model aus einem Billomat-Response-Array. + * + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + id: ScalarCaster::required(ScalarCaster::toIntOrNull($data['id'] ?? null), self::class, 'id'), + clientId: ScalarCaster::required(ScalarCaster::toIntOrNull($data['client_id'] ?? null), self::class, 'client_id'), + created: ScalarCaster::toDateTimeOrNull($data['created'] ?? null), + updated: ScalarCaster::toDateTimeOrNull($data['updated'] ?? null), + label: ScalarCaster::toStringOrNull($data['label'] ?? null), + name: ScalarCaster::toStringOrNull($data['name'] ?? null), + salutation: ScalarCaster::toStringOrNull($data['salutation'] ?? null), + firstName: ScalarCaster::toStringOrNull($data['first_name'] ?? null), + lastName: ScalarCaster::toStringOrNull($data['last_name'] ?? null), + street: ScalarCaster::toStringOrNull($data['street'] ?? null), + addressLine2: ScalarCaster::toStringOrNull($data['address_line_2'] ?? null), + addressLine3: ScalarCaster::toStringOrNull($data['address_line_3'] ?? null), + zip: ScalarCaster::toStringOrNull($data['zip'] ?? null), + city: ScalarCaster::toStringOrNull($data['city'] ?? null), + state: ScalarCaster::toStringOrNull($data['state'] ?? null), + countryCode: ScalarCaster::toStringOrNull($data['country_code'] ?? null), + isDefault: ScalarCaster::toBoolOrNull($data['is_default'] ?? null), + extra: array_diff_key($data, self::FIELDS), + ); + } + + /** + * Exportiert das Model als Array mit Billomat-Feldnamen. + * + * Praktisch für Debugging oder Log-Ausgaben. + * + * @return array + */ + public function toArray(): array + { + return [ + ...$this->extra, + 'id' => $this->id, + 'client_id' => $this->clientId, + 'created' => $this->created?->format(DATE_ATOM), + 'updated' => $this->updated?->format(DATE_ATOM), + 'label' => $this->label, + 'name' => $this->name, + 'salutation' => $this->salutation, + 'first_name' => $this->firstName, + 'last_name' => $this->lastName, + 'street' => $this->street, + 'address_line_2' => $this->addressLine2, + 'address_line_3' => $this->addressLine3, + 'zip' => $this->zip, + 'city' => $this->city, + 'state' => $this->state, + 'country_code' => $this->countryCode, + 'is_default' => $this->isDefault, + ]; + } +} diff --git a/src/Model/Invoice.php b/src/Model/Invoice.php index af2df3ec..2acb7b55 100644 --- a/src/Model/Invoice.php +++ b/src/Model/Invoice.php @@ -79,6 +79,7 @@ 'facturx_reference' => true, 'total_reduction' => true, 'dig_proceeded' => true, + 'client_delivery_address_id' => true, ]; /** @@ -184,6 +185,12 @@ public function __construct( public ?Money $totalReduction = null, /** Wurde die Rechnung digital weiterverarbeitet? */ public ?bool $digProceeded = null, + /** + * ID der Lieferadresse des Kunden. + * + * Siehe ClientDeliveryAddressesApi ($billomat->clients->deliveryAddresses). + */ + public ?int $clientDeliveryAddressId = null, /** * Felder, die Billomat liefert, das SDK aber (noch) nicht abbildet – roh, wie in der Response. * @@ -247,6 +254,7 @@ public static function fromArray(array $data): self facturxReference: ScalarCaster::toStringOrNull($data['facturx_reference'] ?? null), totalReduction: ScalarCaster::toMoneyOrNull($data['total_reduction'] ?? null), digProceeded: ScalarCaster::toBoolOrNull($data['dig_proceeded'] ?? null), + clientDeliveryAddressId: ScalarCaster::toIntOrNull($data['client_delivery_address_id'] ?? null), extra: array_diff_key($data, self::FIELDS), ); } @@ -306,6 +314,7 @@ public function toArray(): array 'facturx_reference' => $this->facturxReference, 'total_reduction' => $this->totalReduction?->toString(), 'dig_proceeded' => $this->digProceeded, + 'client_delivery_address_id' => $this->clientDeliveryAddressId, ]; if ([] !== $this->taxes) { diff --git a/src/Model/Recurring.php b/src/Model/Recurring.php index 432a16f5..eb3e4ae0 100644 --- a/src/Model/Recurring.php +++ b/src/Model/Recurring.php @@ -87,6 +87,7 @@ 'letter_paper_weight' => true, 'offer_id' => true, 'confirmation_id' => true, + 'client_delivery_address_id' => true, ]; /** @@ -220,6 +221,12 @@ public function __construct( public ?int $offerId = null, /** ID der Quell-Auftragsbestätigung. */ public ?int $confirmationId = null, + /** + * ID der Lieferadresse des Kunden. + * + * Siehe ClientDeliveryAddressesApi ($billomat->clients->deliveryAddresses). + */ + public ?int $clientDeliveryAddressId = null, /** * Felder, die Billomat liefert, das SDK aber (noch) nicht abbildet – roh, wie in der Response. * @@ -293,6 +300,7 @@ public static function fromArray(array $data): self letterPaperWeight: ScalarCaster::toIntOrNull($data['letter_paper_weight'] ?? null), offerId: ScalarCaster::toIntOrNull($data['offer_id'] ?? null), confirmationId: ScalarCaster::toIntOrNull($data['confirmation_id'] ?? null), + clientDeliveryAddressId: ScalarCaster::toIntOrNull($data['client_delivery_address_id'] ?? null), extra: array_diff_key($data, self::FIELDS), ); } @@ -362,6 +370,7 @@ public function toArray(): array 'letter_paper_weight' => $this->letterPaperWeight, 'offer_id' => $this->offerId, 'confirmation_id' => $this->confirmationId, + 'client_delivery_address_id' => $this->clientDeliveryAddressId, ]; if ([] !== $this->taxes) { diff --git a/tests/Api/ClientDeliveryAddressesApiTest.php b/tests/Api/ClientDeliveryAddressesApiTest.php new file mode 100644 index 00000000..95128a77 --- /dev/null +++ b/tests/Api/ClientDeliveryAddressesApiTest.php @@ -0,0 +1,221 @@ +api($captured, '{"client-delivery-addresses":{"client-delivery-address":['.self::SANDBOX_ADDRESS.'],"@page":"1","@per_page":"100","@total":"1"}}'); + + $addresses = $api->list(10651661); + + self::assertCount(1, $addresses); + self::assertSame('SDK-Beispiel Lager', $addresses[0]->label); + self::assertSame('GET', $captured->method); + self::assertSame('https://mycompany.billomat.net/api/client-delivery-addresses?client_id=10651661', $captured->url); + } + + #[Test] + public function aSingleAddressInTheListIsNormalized(): void + { + $api = $this->api(new CapturedRequest(), '{"client-delivery-addresses":{"client-delivery-address":'.self::SANDBOX_ADDRESS.',"@total":"1"}}'); + + $addresses = $api->list(10651661); + + self::assertCount(1, $addresses); + self::assertSame(2, $addresses[0]->id); + } + + #[Test] + public function theParentIdWinsOverAFilterOfTheSameName(): void + { + $captured = new CapturedRequest(); + $api = $this->api($captured, '{"client-delivery-addresses":{"@page":"2","@per_page":"5","@total":"0"}}'); + + self::assertSame([], $api->list(42, new SubResourceFilter(orderBy: OrderBy::desc('created'), page: 2, perPage: 5))); + self::assertSame(['client_id' => '42', 'order_by' => 'created DESC', 'page' => '2', 'per_page' => '5'], $captured->query()); + + (void) $api->listPage(42, ['client_id' => 7]); + self::assertSame(['client_id' => '42'], $captured->query()); + } + + #[Test] + public function itIsReachableAsSubResourceOfClients(): void + { + $captured = new CapturedRequest(); + $mock = new MockHttpClient(static function (string $method, string $url) use ($captured): MockResponse { + $captured->record($method, $url); + + return new MockResponse('{"client-delivery-addresses":{"@total":"0"}}'); + }); + $billomat = BillomatClient::create(billomatId: 'mycompany', apiKey: 'k', httpClient: new Psr18Client($mock)); + + // Lazy erzeugt und danach wiederverwendet. + self::assertSame($billomat->clients->deliveryAddresses, $billomat->clients->deliveryAddresses); + + self::assertSame([], $billomat->clients->deliveryAddresses->list(42)); + self::assertSame('https://mycompany.billomat.net/api/client-delivery-addresses?client_id=42', $captured->url); + } + + #[Test] + public function itHydratesTheSandboxResponse(): void + { + $captured = new CapturedRequest(); + $api = $this->api($captured, '{"client-delivery-address":'.self::SANDBOX_ADDRESS.'}'); + + $address = $api->getOrFail(2); + + self::assertSame('https://mycompany.billomat.net/api/client-delivery-addresses/2', $captured->url); + self::assertSame(2, $address->id); + self::assertSame(10651661, $address->clientId); + self::assertEquals(new DateTimeImmutable('2026-11-22T20:35:22+01:00'), $address->created); + self::assertSame('SDK-Beispiel GmbH', $address->name); + self::assertSame('Frau', $address->salutation); + self::assertSame('Erika', $address->firstName); + self::assertSame('Musterfrau', $address->lastName); + self::assertSame('Lagerweg 5', $address->street); + self::assertSame('Tor 3', $address->addressLine2); + self::assertSame('Rampe B', $address->addressLine3); + self::assertSame('10115', $address->zip); + self::assertSame('Berlin', $address->city); + self::assertSame('DE', $address->countryCode); + self::assertFalse($address->isDefault); + self::assertSame([], $address->extra); + } + + #[Test] + public function getReturnsNullAndGetOrFailThrowsForAMissingAddress(): void + { + $api = $this->api(new CapturedRequest(), '{"errors":{"error":"item not found"}}', 404); + + self::assertNull($api->get(3)); + + $this->expectException(NotFoundException::class); + (void) $api->getOrFail(3); + } + + #[Test] + public function itCreatesAnAddressForTheGivenClient(): void + { + $captured = new CapturedRequest(); + $api = $this->api($captured, '{"client-delivery-address":'.self::SANDBOX_ADDRESS.'}', 201); + + $created = $api->create(10651661, new ClientDeliveryAddressCreateOptions( + label: 'SDK-Beispiel Lager', + street: 'Lagerweg 5', + addressLine2: 'Tor 3', + countryCode: 'DE', + isDefault: true, + )); + + self::assertSame(2, $created->id); + self::assertSame('POST', $captured->method); + self::assertSame('https://mycompany.billomat.net/api/client-delivery-addresses', $captured->url); + self::assertSame(['client-delivery-address' => [ + 'label' => 'SDK-Beispiel Lager', + 'street' => 'Lagerweg 5', + 'address_line_2' => 'Tor 3', + 'country_code' => 'DE', + 'is_default' => 1, + 'client_id' => 10651661, + ]], $captured->json()); + } + + #[Test] + public function anUpdateOnlySendsTheGivenFields(): void + { + $captured = new CapturedRequest(); + $api = $this->api($captured, '{"client-delivery-address":'.self::SANDBOX_ADDRESS.'}'); + + $api->update(2, new ClientDeliveryAddressUpdateOptions(city: 'Bremen', isDefault: false)); + + self::assertSame('PUT', $captured->method); + self::assertSame('https://mycompany.billomat.net/api/client-delivery-addresses/2', $captured->url); + self::assertSame(['client-delivery-address' => ['city' => 'Bremen', 'is_default' => 0]], $captured->json()); + } + + #[Test] + public function itDeletesAnAddress(): void + { + $captured = new CapturedRequest(); + $api = $this->api($captured, ''); + + $api->delete(2); + + self::assertSame('DELETE', $captured->method); + self::assertSame('https://mycompany.billomat.net/api/client-delivery-addresses/2', $captured->url); + } + + #[Test] + public function billomatErrorsBecomeValidationExceptions(): void + { + $api = $this->api(new CapturedRequest(), '{"errors":{"error":"no valid country_code given"}}', 400); + + $this->expectException(ValidationException::class); + $this->expectExceptionMessageIsOrContains('no valid country_code given'); + + $api->create(42, new ClientDeliveryAddressCreateOptions(countryCode: 'XX')); + } + + private function api(CapturedRequest $captured, string $body, int $status = 200): ClientDeliveryAddressesApi + { + $mock = new MockHttpClient(static function (string $method, string $url, array $options) use ($captured, $body, $status): MockResponse { + $captured->record($method, $url, $options); + + return new MockResponse($body, ['http_code' => $status]); + }); + + return new ClientDeliveryAddressesApi(new BillomatHttpClient( + new Psr18Client($mock), + new BillomatConfig('mycompany', 'secret-key', retry: new RetryPolicy(maxRetries: 0)), + )); + } +} diff --git a/tests/Api/CustomFieldTest.php b/tests/Api/CustomFieldTest.php index 2ec31962..31789267 100644 --- a/tests/Api/CustomFieldTest.php +++ b/tests/Api/CustomFieldTest.php @@ -176,13 +176,13 @@ private function api(BillomatClient $billomat, string $resource, string $subReso } /** - * Envelope-Schlüssel aus dem Pfad: /credit-notes/7 → credit-note, /taxes/7 → tax, /article-properties/7 → article-property. + * Envelope-Schlüssel aus dem Pfad: /credit-notes/7 → credit-note, /taxes/7 → tax, /article-properties/7 → article-property, /client-delivery-addresses/7 → client-delivery-address. */ private static function envelopeKey(string $url): string { $slug = explode('/', (string) parse_url($url, PHP_URL_PATH))[2] ?? ''; - return (string) preg_replace(['/ies$/', '/(x)es$/', '/s$/'], ['y', '$1', ''], $slug); + return (string) preg_replace(['/ies$/', '/(x|ss)es$/', '/(? RequiredFields::ANY])); }); diff --git a/tests/Api/ListPagingTest.php b/tests/Api/ListPagingTest.php index 2575581f..89921d71 100644 --- a/tests/Api/ListPagingTest.php +++ b/tests/Api/ListPagingTest.php @@ -6,6 +6,7 @@ use Closure; use Generator; +use Justpilot\Billomat\Api\ClientDeliveryAddressesApi; use Justpilot\Billomat\Api\ContactsApi; use Justpilot\Billomat\Api\CountriesApi; use Justpilot\Billomat\Api\CurrenciesApi; @@ -34,6 +35,7 @@ * `listPage()`/`iterateAll()` der Ressourcen, die bis 4.0.0-alpha.1 nur `list()` hatten. */ #[CoversClass(ContactsApi::class)] +#[CoversClass(ClientDeliveryAddressesApi::class)] #[CoversClass(TaxesApi::class)] #[CoversClass(TemplatesApi::class)] #[CoversClass(ReminderTextsApi::class)] @@ -62,6 +64,7 @@ public static function resources(): iterable $filter = ['name' => 'x']; yield 'contacts' => ['/contacts', 'contacts', 'contact', static fn (BillomatClient $b): Page => $b->clients->contacts->listPage(9, $page), static fn (BillomatClient $b): Generator => $b->clients->contacts->iterateAll(9, $filter, 2)]; + yield 'client-delivery-addresses' => ['/client-delivery-addresses', 'client-delivery-addresses', 'client-delivery-address', static fn (BillomatClient $b): Page => $b->clients->deliveryAddresses->listPage(9, $page), static fn (BillomatClient $b): Generator => $b->clients->deliveryAddresses->iterateAll(9, $filter, 2)]; yield 'taxes' => ['/taxes', 'taxes', 'tax', static fn (BillomatClient $b): Page => $b->taxes->listPage($page), static fn (BillomatClient $b): Generator => $b->taxes->iterateAll($filter, 2)]; yield 'templates' => ['/templates', 'templates', 'template', static fn (BillomatClient $b): Page => $b->templates->listPage($page), static fn (BillomatClient $b): Generator => $b->templates->iterateAll($filter, 2)]; yield 'reminder texts' => ['/reminder-texts', 'reminder-texts', 'reminder-text', static fn (BillomatClient $b): Page => $b->reminderTexts->listPage($page), static fn (BillomatClient $b): Generator => $b->reminderTexts->iterateAll($filter, 2)]; @@ -116,6 +119,7 @@ public function iterateAllFetchesEveryPage(string $path, string $outer, string $ public static function defaultIterators(): iterable { yield 'contacts' => ['contacts', 'contact', static fn (BillomatClient $b): Generator => $b->clients->contacts->iterateAll(9)]; + yield 'client-delivery-addresses' => ['client-delivery-addresses', 'client-delivery-address', static fn (BillomatClient $b): Generator => $b->clients->deliveryAddresses->iterateAll(9)]; yield 'taxes' => ['taxes', 'tax', static fn (BillomatClient $b): Generator => $b->taxes->iterateAll()]; yield 'templates' => ['templates', 'template', static fn (BillomatClient $b): Generator => $b->templates->iterateAll()]; yield 'reminder texts' => ['reminder-texts', 'reminder-text', static fn (BillomatClient $b): Generator => $b->reminderTexts->iterateAll()]; diff --git a/tests/Contract/ContractFixturesTest.php b/tests/Contract/ContractFixturesTest.php index 68bd8de5..e209302f 100644 --- a/tests/Contract/ContractFixturesTest.php +++ b/tests/Contract/ContractFixturesTest.php @@ -162,6 +162,7 @@ private function calls(): array return [ 'clients' => ['key' => 'client', 'list' => static fn (BillomatClient $b): array => $b->clients->list(), 'get' => static fn (BillomatClient $b): ?object => $b->clients->get(1)], 'contacts' => ['key' => 'contact', 'list' => static fn (BillomatClient $b): array => $b->clients->contacts->list(1), 'get' => static fn (BillomatClient $b): ?object => $b->clients->contacts->get(1)], + 'client-delivery-addresses' => ['key' => 'client-delivery-address', 'list' => static fn (BillomatClient $b): array => $b->clients->deliveryAddresses->list(1), 'get' => static fn (BillomatClient $b): ?object => $b->clients->deliveryAddresses->get(1)], 'client-tags' => ['key' => 'client-tag', 'list' => static fn (BillomatClient $b): array => $b->clients->tags->list(1), 'get' => static fn (BillomatClient $b): ?object => $b->clients->tags->get(1)], 'client-properties' => ['key' => 'client-property', 'list' => static fn (BillomatClient $b): array => $b->clients->properties->list(), 'get' => static fn (BillomatClient $b): ?object => $b->clients->properties->get(1)], 'client-property-values' => ['key' => 'client-property-value', 'list' => static fn (BillomatClient $b): array => $b->clients->propertyValues->list(), 'get' => static fn (BillomatClient $b): ?object => $b->clients->propertyValues->get(1)], diff --git a/tests/Fixtures/Contract/client-delivery-addresses/get.json b/tests/Fixtures/Contract/client-delivery-addresses/get.json new file mode 100644 index 00000000..92df00b5 --- /dev/null +++ b/tests/Fixtures/Contract/client-delivery-addresses/get.json @@ -0,0 +1,21 @@ +{ + "client-delivery-address": { + "id": "2", + "created": "2026-11-22T20:35:22+01:00", + "updated": "2026-11-22T20:35:22+01:00", + "client_id": "10651661", + "label": "Text 2", + "name": "Name 2", + "salutation": "Frau", + "first_name": "Vorname4", + "last_name": "Nachname4", + "street": "Musterstraße 5", + "address_line_2": "Adresszusatz 1", + "address_line_3": "Adresszusatz 2", + "zip": "10003", + "city": "Musterstadt 4", + "state": "Bundesland 1", + "country_code": "DE", + "is_default": "0" + } +} diff --git a/tests/Fixtures/Contract/client-delivery-addresses/list.json b/tests/Fixtures/Contract/client-delivery-addresses/list.json new file mode 100644 index 00000000..0d09a25f --- /dev/null +++ b/tests/Fixtures/Contract/client-delivery-addresses/list.json @@ -0,0 +1,26 @@ +{ + "client-delivery-addresses": { + "client-delivery-address": { + "id": "2", + "created": "2026-11-22T20:35:22+01:00", + "updated": "2026-11-22T20:35:22+01:00", + "client_id": "10651661", + "label": "Text 2", + "name": "Name 2", + "salutation": "Frau", + "first_name": "Vorname4", + "last_name": "Nachname4", + "street": "Musterstraße 5", + "address_line_2": "Adresszusatz 1", + "address_line_3": "Adresszusatz 2", + "zip": "10003", + "city": "Musterstadt 4", + "state": "Bundesland 1", + "country_code": "DE", + "is_default": "0" + }, + "@page": "1", + "@per_page": "3", + "@total": "1" + } +} diff --git a/tests/Fixtures/Contract/invoices/get.json b/tests/Fixtures/Contract/invoices/get.json index da7f7d0f..d6716966 100644 --- a/tests/Fixtures/Contract/invoices/get.json +++ b/tests/Fixtures/Contract/invoices/get.json @@ -5,6 +5,7 @@ "updated": "2025-12-31T15:00:35+01:00", "client_id": "9347139", "contact_id": "", + "client_delivery_address_id": "", "invoice_number": "RE352500001", "number": "1", "number_pre": "RE3525", diff --git a/tests/Fixtures/Contract/invoices/list.json b/tests/Fixtures/Contract/invoices/list.json index 61384a42..86c76c0d 100644 --- a/tests/Fixtures/Contract/invoices/list.json +++ b/tests/Fixtures/Contract/invoices/list.json @@ -7,6 +7,7 @@ "updated": "2025-12-31T15:00:35+01:00", "client_id": "9347139", "contact_id": "", + "client_delivery_address_id": "", "invoice_number": "RE352500001", "number": "1", "number_pre": "RE3525", @@ -68,6 +69,7 @@ "updated": "2025-12-31T15:12:02+01:00", "client_id": "9347139", "contact_id": "", + "client_delivery_address_id": "", "invoice_number": "RE362500002", "number": "2", "number_pre": "RE3625", @@ -129,6 +131,7 @@ "updated": "2025-12-31T15:06:46+01:00", "client_id": "9347139", "contact_id": "", + "client_delivery_address_id": "", "invoice_number": "RE3525000003", "number": "3", "number_pre": "RE3525", diff --git a/tests/Fixtures/Contract/recurrings/get.json b/tests/Fixtures/Contract/recurrings/get.json index 95242ad1..64637f26 100644 --- a/tests/Fixtures/Contract/recurrings/get.json +++ b/tests/Fixtures/Contract/recurrings/get.json @@ -5,6 +5,7 @@ "updated": "2026-10-26T16:59:08+01:00", "client_id": "10651661", "contact_id": "", + "client_delivery_address_id": "", "title": "Text 41", "name": "Name 14", "supply_date": "", diff --git a/tests/Fixtures/Contract/recurrings/list.json b/tests/Fixtures/Contract/recurrings/list.json index a94c5153..444d8814 100644 --- a/tests/Fixtures/Contract/recurrings/list.json +++ b/tests/Fixtures/Contract/recurrings/list.json @@ -6,6 +6,7 @@ "updated": "2026-10-26T16:59:08+01:00", "client_id": "10651661", "contact_id": "", + "client_delivery_address_id": "", "title": "Text 41", "name": "Name 14", "supply_date": "", diff --git a/tests/Integration/ClientDeliveryAddresses/ClientDeliveryAddressesIntegrationTest.php b/tests/Integration/ClientDeliveryAddresses/ClientDeliveryAddressesIntegrationTest.php new file mode 100644 index 00000000..b1e55a63 --- /dev/null +++ b/tests/Integration/ClientDeliveryAddresses/ClientDeliveryAddressesIntegrationTest.php @@ -0,0 +1,120 @@ +createBillomatClientOrSkip(); + $clientId = $this->seedClientId($billomat); + + $address = $billomat->clients->deliveryAddresses->create($clientId, new ClientDeliveryAddressCreateOptions( + label: 'IT-Lieferadresse', + // Eindeutig, weil Billomat gleiche Adressen eines Kunden ablehnt (das Label zählt dabei nicht). + street: 'Teststraße '.uniqid(), + addressLine2: 'Hinterhof', + zip: '10115', + city: 'Berlin', + countryCode: 'DE', + isDefault: false, + )); + + try { + self::assertSame($clientId, $address->clientId); + self::assertSame('Hinterhof', $address->addressLine2); + self::assertFalse($address->isDefault); + + $updated = $billomat->clients->deliveryAddresses->update($address->id, new ClientDeliveryAddressUpdateOptions(city: 'Bremen')); + self::assertSame('Bremen', $updated->city); + // Partial Update: nicht gesendete Felder bleiben erhalten. + self::assertSame($address->street, $updated->street); + + $ids = array_map(static fn (ClientDeliveryAddress $a): int => $a->id, $billomat->clients->deliveryAddresses->list($clientId)); + self::assertContains($address->id, $ids); + } finally { + $billomat->clients->deliveryAddresses->delete($address->id); + } + + self::assertNull($billomat->clients->deliveryAddresses->get($address->id)); + } + + #[Group('integration')] + #[Test] + public function anInvalidCountryCodeIsAValidationError(): void + { + $billomat = $this->createBillomatClientOrSkip(); + $clientId = $this->seedClientId($billomat); + + $this->expectException(ValidationException::class); + $this->expectExceptionMessageIsOrContains('country_code'); + + $billomat->clients->deliveryAddresses->create($clientId, new ClientDeliveryAddressCreateOptions(countryCode: 'XX')); + } + + #[Group('integration')] + #[Test] + public function anInvoiceCanReferenceADeliveryAddress(): void + { + $billomat = $this->createBillomatClientOrSkip(); + $clientId = $this->seedClientId($billomat); + + $address = $billomat->clients->deliveryAddresses->create($clientId, new ClientDeliveryAddressCreateOptions( + label: 'IT-Rechnung', + street: 'Rechnungsweg '.uniqid(), + city: 'Hamburg', + countryCode: 'DE', + )); + + try { + $invoice = $billomat->invoices->create(new InvoiceCreateOptions( + clientId: $clientId, + label: 'Integrationstest Lieferadresse', + clientDeliveryAddressId: $address->id, + )); + + try { + self::assertSame($address->id, $invoice->clientDeliveryAddressId); + self::assertSame($address->id, $billomat->invoices->getOrFail($invoice->id)->clientDeliveryAddressId); + } finally { + $billomat->invoices->delete($invoice->id); + } + } finally { + $billomat->clients->deliveryAddresses->delete($address->id); + } + } + + private function seedClientId(BillomatClient $billomat): int + { + foreach ($billomat->clients->list(['name' => self::SEED_CLIENT]) as $client) { + if (self::SEED_CLIENT === $client->name) { + return $client->id; + } + } + + self::markTestSkipped('Beispielkunde „'.self::SEED_CLIENT.'“ fehlt in der Sandbox.'); + } +} diff --git a/tools/audit-spec-vs-code.php b/tools/audit-spec-vs-code.php index e94a5a41..5ecf5d75 100644 --- a/tools/audit-spec-vs-code.php +++ b/tools/audit-spec-vs-code.php @@ -51,6 +51,9 @@ 'kunden/attribute' => ['api' => 'PropertyValuesApi', 'model' => 'ClientPropertyValue', 'createOptions' => 'ClientPropertyValueCreateOptions', 'docFile' => 'properties.md', 'note' => 'Attribut-Werte (/client-property-values); Definitionen siehe einstellungen/kunden-attribute.'], + 'lieferadressen' => ['api' => 'ClientDeliveryAddressesApi', 'model' => 'ClientDeliveryAddress', + 'createOptions' => 'ClientDeliveryAddressCreateOptions', 'updateOptions' => 'ClientDeliveryAddressUpdateOptions', + 'docFile' => 'client-delivery-addresses.md'], 'kunden/kontakte' => ['api' => 'ContactsApi', 'model' => 'Contact', 'createOptions' => 'ContactCreateOptions', 'updateOptions' => 'ContactUpdateOptions', 'docFile' => 'contacts.md'], @@ -471,6 +474,7 @@ function filterParentIds(array $fieldNames, string $slug): array 'zahlungen' => ['invoice_id', 'credit_note_id', 'incoming_id'], 'empfaenger' => ['recurring_id'], 'kontakte' => ['client_id'], + 'lieferadressen' => ['client_id'], 'attribute' => ['client_id', 'article_id', 'supplier_id', 'incoming_id'], ]; diff --git a/tools/codegen/definitions/client-delivery-addresses.php b/tools/codegen/definitions/client-delivery-addresses.php new file mode 100644 index 00000000..3f4c9955 --- /dev/null +++ b/tools/codegen/definitions/client-delivery-addresses.php @@ -0,0 +1,81 @@ + 'lieferadressen', + 'docUrl' => 'https://www.billomat.com/api/lieferadressen/', + 'experimental' => 'Billomat stellt die Lieferadressen noch fertig; laut Doku gelten die Endpunkte erst ab dem 01.01.2027 verbindlich. Bis dahin kann sich die Klasse auch in einem Minor-Release ändern (siehe docs/concepts/backward-compatibility.md).', + + 'model' => [ + 'class' => 'ClientDeliveryAddress', + 'doc' => [ + 'Lieferadresse (Client Delivery Address) eines Kunden.', + '', + 'Dieses Model bildet die Struktur von GET /client-delivery-addresses bzw. GET /client-delivery-addresses/{id} ab.', + 'Es ist als Read-Model gedacht: Die Erstellung erfolgt über ClientDeliveryAddressCreateOptions.', + ], + ], + + 'createOptions' => [ + 'class' => 'ClientDeliveryAddressCreateOptions', + 'endpoint' => 'POST /api/client-delivery-addresses', + 'boolAsInt' => true, + 'doc' => [ + 'Typisierter Payload für POST /client-delivery-addresses gemäß Billomat-API.', + '', + 'Null-Werte bedeuten "nicht gesetzt" und werden beim Serialisieren ignoriert.', + ], + ], + + 'updateOptions' => [ + 'class' => 'ClientDeliveryAddressUpdateOptions', + 'endpoint' => 'PUT /api/client-delivery-addresses/{id}', + 'boolAsInt' => true, + 'doc' => [ + 'Typisierter Payload für PUT /client-delivery-addresses/{id} gemäß Billomat-API.', + '', + 'Nur gesetzte (nicht-null) Felder werden serialisiert (Partial Update).', + 'Der Kunde einer Lieferadresse lässt sich nicht ändern.', + ], + ], + + 'fields' => [ + 'id' => ['type' => 'int', 'readOnly' => true, 'model' => ['required' => true], 'doc' => 'Interne Billomat-ID der Lieferadresse.'], + // Die Kunden-ID übergibt `ClientDeliveryAddressesApi::create()` als eigenes Argument; ändern lässt sie sich nicht. + 'client_id' => [ + 'type' => 'int', + 'readOnly' => true, + 'doc' => 'ID des Kunden, zu dem die Lieferadresse gehört.', + 'model' => ['required' => true], + ], + 'created' => ['type' => 'datetime', 'readOnly' => true, 'doc' => 'Erstellungszeitpunkt der Lieferadresse.'], + 'updated' => ['type' => 'datetime', 'readOnly' => true, 'doc' => 'Zeitpunkt der letzten Änderung.'], + 'label' => ['type' => 'string', 'writable' => true, 'doc' => 'Bezeichnung der Lieferadresse.', 'details' => ['Beispiel: "Lager Berlin"']], + 'name' => ['doc' => 'Firmenname.'], + 'salutation' => ['doc' => 'Anrede.'], + 'first_name' => ['doc' => 'Vorname.'], + 'last_name' => ['doc' => 'Nachname.'], + 'street' => ['doc' => 'Straße.'], + 'address_line_2' => ['type' => 'string', 'writable' => true, 'doc' => 'Adresszusatz (Zeile 2).'], + 'address_line_3' => ['type' => 'string', 'writable' => true, 'doc' => 'Adresszusatz (Zeile 3).'], + 'zip' => ['doc' => 'Postleitzahl.'], + 'city' => ['doc' => 'Ort.'], + 'state' => ['doc' => 'Bundesland / Bezirk / Region.'], + 'country_code' => ['doc' => 'Ländercode (ISO 3166-1 Alpha-2).', 'details' => ['Beispiel: "DE", "AT", "CH"']], + 'is_default' => ['type' => 'bool', 'writable' => true, 'doc' => 'Standard-Lieferadresse des Kunden?'], + ], +]; diff --git a/tools/codegen/definitions/clients.php b/tools/codegen/definitions/clients.php index 5d980d95..256fe686 100644 --- a/tools/codegen/definitions/clients.php +++ b/tools/codegen/definitions/clients.php @@ -48,6 +48,8 @@ * entsteht nur das Read-Model; 'specEndpoint' nennt dann den Endpunkt für den Drift-Abgleich. * Ohne 'specResource' (Ressource fehlt in der Billomat-Doku) entfällt der Drift-Abgleich; * jedes Feld braucht dann 'type' und 'readOnly' oder 'writable'. + * 'experimental' => '' setzt @experimental an Model und Options (Endpunkte, die Billomat + * noch als vorläufig bezeichnet; siehe docs/concepts/backward-compatibility.md). * Eine Definitionsdatei darf statt einer Definition eine Liste von Definitionen zurückgeben. * 'boolAsInt' => true an 'model' oder an den Options gibt Bool-Felder in toArray() als 1/0 aus. * 'filterNulls' => true an 'model' lässt Null-Felder in toArray() des Read-Models weg. diff --git a/tools/codegen/definitions/invoices.php b/tools/codegen/definitions/invoices.php index 9f66f04a..3f3fab9c 100644 --- a/tools/codegen/definitions/invoices.php +++ b/tools/codegen/definitions/invoices.php @@ -12,7 +12,7 @@ $optionsOrder = static fn (string ...$swap): array => [ - 'client_id', 'contact_id', 'address', 'number_pre', 'number', 'number_length', 'date', 'supply_date', 'supply_date_type', + 'client_id', 'contact_id', 'client_delivery_address_id', 'address', 'number_pre', 'number', 'number_length', 'date', 'supply_date', 'supply_date_type', 'due_days', 'due_date', 'discount_rate', 'discount_days', 'discount_date', 'title', 'label', 'intro', 'note', 'reduction', ...$swap, 'quote', 'payment_types', 'invoice_id', 'offer_id', 'confirmation_id', 'recurring_id', 'free_text_id', 'template_id', @@ -136,5 +136,10 @@ 'total_reduction' => ['type' => 'float', 'readOnly' => true, 'doc' => 'Summe der Rabatte.'], 'dig_proceeded' => ['type' => 'bool', 'readOnly' => true, 'doc' => 'Wurde die Rechnung digital weiterverarbeitet?'], 'free_text_id' => ['optionsOnly' => true, 'doc' => 'ID des Freitextes zur Belegung von title, label, intro und note.'], + // Am Ende statt hinter contact_id: Konstruktor-Positionen der bestehenden Felder bleiben stabil. + 'client_delivery_address_id' => [ + 'doc' => 'ID der Lieferadresse des Kunden.', + 'details' => ['Siehe ClientDeliveryAddressesApi ($billomat->clients->deliveryAddresses).'], + ], ], ]; diff --git a/tools/codegen/definitions/recurrings.php b/tools/codegen/definitions/recurrings.php index 38900529..9645d4c3 100644 --- a/tools/codegen/definitions/recurrings.php +++ b/tools/codegen/definitions/recurrings.php @@ -12,7 +12,7 @@ $optionsOrder = [ - 'client_id', 'contact_id', 'address', 'number_pre', 'supply_date', 'supply_date_type', 'due_days', 'discount_rate', + 'client_id', 'contact_id', 'client_delivery_address_id', 'address', 'number_pre', 'supply_date', 'supply_date_type', 'due_days', 'discount_rate', 'discount_days', 'name', 'title', 'label', 'intro', 'note', 'reduction', 'currency_code', 'net_gross', 'quote', 'payment_types', 'action', 'cycle_number', 'cycle', 'hour', 'start_date', 'end_date', 'iterations', 'email_sender', 'email_subject', 'email_message', 'email_template_id', 'free_text_id', 'template_id', 'next_creation_date', @@ -147,5 +147,10 @@ 'letter_paper_weight' => ['doc' => 'Papiergewicht des Briefs in g/m².'], 'offer_id' => ['doc' => 'ID des Quell-Angebots.'], 'confirmation_id' => ['doc' => 'ID der Quell-Auftragsbestätigung.'], + // Am Ende statt hinter contact_id: Konstruktor-Positionen der bestehenden Felder bleiben stabil. + 'client_delivery_address_id' => [ + 'doc' => 'ID der Lieferadresse des Kunden.', + 'details' => ['Siehe ClientDeliveryAddressesApi ($billomat->clients->deliveryAddresses).'], + ], ], ]; diff --git a/tools/extract-billomat-spec.php b/tools/extract-billomat-spec.php index 29526ca2..cb9ae19a 100644 --- a/tools/extract-billomat-spec.php +++ b/tools/extract-billomat-spec.php @@ -409,7 +409,8 @@ function parseEndpoints(array $nodes): array $line = trim(textContent($node)); if (preg_match('/^(GET|POST|PUT|DELETE|PATCH)\s+(\S+)/', $line, $m)) { $current['method'] = $m[1]; - $current['path'] = $m[2]; + // Billomat schreibt manche Pfade ohne führenden Slash ("api/client-delivery-addresses"). + $current['path'] = '/' . ltrim($m[2], '/'); } } // XML-Beispiele werden absichtlich nicht extrahiert diff --git a/tools/generate-json-examples.php b/tools/generate-json-examples.php index 451fe8c6..ace36e80 100644 --- a/tools/generate-json-examples.php +++ b/tools/generate-json-examples.php @@ -30,6 +30,7 @@ use Justpilot\Billomat\Api\ClientTagCreateOptions; use Justpilot\Billomat\Api\ConfirmationCreateOptions; use Justpilot\Billomat\Api\ConfirmationItemCreateOptions; +use Justpilot\Billomat\Api\ClientDeliveryAddressCreateOptions; use Justpilot\Billomat\Api\ContactCreateOptions; use Justpilot\Billomat\Api\CountryTaxCreateOptions; use Justpilot\Billomat\Api\CreditNoteCreateOptions; @@ -128,6 +129,14 @@ function requests(): array lastName: 'Mustermann', email: 'erika@example.com', )), + 'client-delivery-addresses.create' => static fn (BillomatClient $b): object => $b->clients->deliveryAddresses->create(1001, new ClientDeliveryAddressCreateOptions( + label: 'Warehouse Berlin', + street: 'Lagerweg 5', + zip: '10115', + city: 'Berlin', + countryCode: 'DE', + isDefault: true, + )), 'suppliers.create' => static fn (BillomatClient $b): object => $b->suppliers->create(new SupplierCreateOptions( name: 'Office Supplies AG', countryCode: 'DE', @@ -277,6 +286,7 @@ function requests(): array const PAGES = [ 'clients' => ['clients.create', 'clients/get', 'clients/list'], 'contacts' => ['contacts.create', 'contacts/get', 'contacts/list'], + 'client-delivery-addresses' => ['client-delivery-addresses.create', 'client-delivery-addresses/get', 'client-delivery-addresses/list'], 'suppliers' => ['suppliers.create', 'suppliers/get', 'suppliers/list'], 'articles' => ['articles.create', 'articles/get', 'articles/list'], 'client-tags' => ['client-tags.create', 'client-tags/list'], @@ -328,7 +338,7 @@ function capture(Closure $call): array // Minimale Antwort mit allen Pflichtfeldern, damit die Hydration des Rückgabewerts klappt. $slug = explode('/', $path)[1] ?? ''; - $key = 'settings' === $slug ? 'settings' : (string) preg_replace(['/ies$/', '/(x)es$/', '/s$/'], ['y', '$1', ''], $slug); + $key = 'settings' === $slug ? 'settings' : (string) preg_replace(['/ies$/', '/(x|ss)es$/', '/(? [...RequiredFields::ANY, 'id' => '1', 'mime_type' => 'x', 'created' => '2026-11-02T00:00:00+01:00']])); }); diff --git a/tools/generate.php b/tools/generate.php index fe3c052f..a3fc30c5 100644 --- a/tools/generate.php +++ b/tools/generate.php @@ -302,7 +302,7 @@ function renderModel(array $definition, array $fields, string $source): string $out .= "\nuse const DATE_ATOM;\n"; } - $out .= "\n" . classDoc($definition['model']['doc'], $definition['docUrl'], $source, 'Dokumentation:'); + $out .= "\n" . classDoc($definition['model']['doc'], $definition['docUrl'], $source, 'Dokumentation:', $definition['experimental'] ?? null); $out .= 'final readonly class ' . $definition['model']['class'] . "\n{\n"; // Listen-Felder brauchen den Element-Typ als @param am Konstruktor. // Alle Billomat-Felder, die das Model abbildet; der Rest landet in `extra`. @@ -613,7 +613,7 @@ function renderOptions(array $definition, array $options, array $fields, string if ([] !== $imports) { $out .= "\n"; } - $out .= classDoc($options['doc'], $definition['docUrl'], $source, 'Doku:'); + $out .= classDoc($options['doc'], $definition['docUrl'], $source, 'Doku:', $definition['experimental'] ?? null); $out .= 'final readonly class ' . $options['class'] . " implements WriteOptions\n{\n"; // Pflichtfelder beim Anlegen stehen vorne im Konstruktor, danach alle optionalen Felder. @@ -854,7 +854,7 @@ function renderFilter(array $definition, array $filter, array $endpoints, string 'Nicht gesetzte Felder (null bzw. leere Liste) fehlen im Query; Mehrfachwerte', 'werden kommasepariert gesendet und von Billomat ODER-verknüpft. Weitere', 'Query-Parameter (z. B. benutzerdefinierte Attribute) gehen über `extra`.', - ], $definition['docUrl'], $source, 'Doku:'); + ], $definition['docUrl'], $source, 'Doku:', $definition['experimental'] ?? null); $out .= 'final readonly class ' . $filter['class'] . " implements ListFilter\n{\n"; $out .= " public function __construct(\n"; @@ -1128,8 +1128,9 @@ function optionsDocLines(array $field, bool $isCreate): array /** * @param list $doc + * @param string|null $experimental Begründung für `@experimental` (Definition-Schlüssel 'experimental'), null = stabil */ -function classDoc(array $doc, string $docUrl, string $source, string $urlLabel): string +function classDoc(array $doc, string $docUrl, string $source, string $urlLabel, ?string $experimental = null): string { return docBlock([ ...$doc, @@ -1139,6 +1140,7 @@ function classDoc(array $doc, string $docUrl, string $source, string $urlLabel): '', 'Generiert aus ' . $source . ' – nicht von Hand bearbeiten,', 'sondern die Definition anpassen und `composer generate` ausführen.', + ...(null === $experimental ? [] : ['', '@experimental ' . $experimental]), ], ''); } diff --git a/tools/record-fixtures.php b/tools/record-fixtures.php index ece6add8..a36012da 100644 --- a/tools/record-fixtures.php +++ b/tools/record-fixtures.php @@ -54,7 +54,7 @@ * `list: false` = Endpunkt liefert ein einzelnes Objekt (Settings). */ const RESOURCES = [ - 'clients' => ['key' => 'client', 'get' => true, 'children' => ['contacts' => 'contact', 'client-tags' => 'tag']], + 'clients' => ['key' => 'client', 'get' => true, 'children' => ['contacts' => 'contact', 'client-delivery-addresses' => 'client-delivery-address', 'client-tags' => 'tag']], 'client-properties' => ['key' => 'client-property', 'get' => true], 'client-property-values' => ['key' => 'client-property-value', 'get' => true], 'suppliers' => ['key' => 'supplier', 'get' => true, 'children' => ['supplier-tags' => 'tag']], @@ -129,7 +129,7 @@ 'email' => 'email', 'bcc_addresses' => 'email', 'sender' => 'email', 'sender_email' => 'email', 'reply_to' => 'email', 'email_bcc' => 'email', 'email_sender' => 'email', 'bcc' => 'email', 'phone' => 'phone', 'fax' => 'phone', 'mobile' => 'phone', - 'street' => 'street', 'zip' => 'zip', 'city' => 'city', 'state' => 'state', 'address' => 'address', + 'street' => 'street', 'address_line_2' => 'address_line', 'address_line_3' => 'address_line', 'zip' => 'zip', 'city' => 'city', 'state' => 'state', 'address' => 'address', 'www' => 'url', 'url' => 'url', 'website' => 'url', 'avatar' => 'url', 'public_url' => 'url', 'bank_name' => 'bank_name', 'bank_iban' => 'iban', 'iban' => 'iban', 'bank_swift' => 'bic', 'bic' => 'bic', 'swift' => 'bic', 'bank_account_number' => 'digits', 'bank_number' => 'digits', 'creditor_identifier' => 'creditor_id', 'sepa_mandate' => 'text', @@ -477,6 +477,7 @@ private function fake(string $kind, string $original): string 'sender' => "Firma {$n} GmbH ", 'phone' => \sprintf('+49 30 %07d', $i), 'street' => "Musterstraße {$n}", + 'address_line' => "Adresszusatz {$n}", 'zip' => \sprintf('%05d', 10000 + $i), 'city' => "Musterstadt {$n}", 'state' => "Bundesland {$n}", From f10a66fa71379410f1e156cb67f6286b3f8d4b4b Mon Sep 17 00:00:00 2001 From: Dimitri Dovgan Date: Sun, 22 Nov 2026 21:30:25 +0100 Subject: [PATCH 2/4] chore: accept constructor position shifts of $extra/$items in the BC check Generated models and options append new fields before their last parameter ($extra on models, $items on create options). Roave compares parameters by position and reports this as a type change; constructor parameter order is not part of the BC promise (named arguments). --- .roave-backward-compatibility-check.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.roave-backward-compatibility-check.xml b/.roave-backward-compatibility-check.xml index 5622df51..6657aad4 100644 --- a/.roave-backward-compatibility-check.xml +++ b/.roave-backward-compatibility-check.xml @@ -4,5 +4,11 @@ #"Rector\\Rector\\AbstractRector" could not be found in the located source# + + #\[BC\] CHANGED: (Default parameter value for parameter|The parameter) \$(extra|items) of Justpilot\\Billomat\\(Model|Api)\\\w+\#__construct\(\) changed from array# From 992ae4c5c8cfc02c5cc3579115fb46d3f4dd7da1 Mon Sep 17 00:00:00 2001 From: Dimitri Dovgan Date: Sun, 22 Nov 2026 21:33:14 +0100 Subject: [PATCH 3/4] test: cover the delivery address options in OptionsWithersTest Infection runs with strict coverage; the reflection-based wither test touched the new options classes without a CoversClass attribute. --- tests/Api/Options/OptionsWithersTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/Api/Options/OptionsWithersTest.php b/tests/Api/Options/OptionsWithersTest.php index d60d4879..6820ae7a 100644 --- a/tests/Api/Options/OptionsWithersTest.php +++ b/tests/Api/Options/OptionsWithersTest.php @@ -21,6 +21,8 @@ use Justpilot\Billomat\Api\ConfirmationItemUpdateOptions; use Justpilot\Billomat\Api\ConfirmationTagCreateOptions; use Justpilot\Billomat\Api\ConfirmationUpdateOptions; +use Justpilot\Billomat\Api\ClientDeliveryAddressCreateOptions; +use Justpilot\Billomat\Api\ClientDeliveryAddressUpdateOptions; use Justpilot\Billomat\Api\ContactCreateOptions; use Justpilot\Billomat\Api\ContactUpdateOptions; use Justpilot\Billomat\Api\CountryTaxCreateOptions; @@ -136,6 +138,8 @@ #[CoversClass(ConfirmationItemUpdateOptions::class)] #[CoversClass(ConfirmationTagCreateOptions::class)] #[CoversClass(ConfirmationUpdateOptions::class)] +#[CoversClass(ClientDeliveryAddressCreateOptions::class)] +#[CoversClass(ClientDeliveryAddressUpdateOptions::class)] #[CoversClass(ContactCreateOptions::class)] #[CoversClass(ContactUpdateOptions::class)] #[CoversClass(CountryTaxCreateOptions::class)] From f5f3b4620647dc86652f7d9e4ceadb33b3fe0698 Mon Sep 17 00:00:00 2001 From: Dimitri Dovgan Date: Sun, 22 Nov 2026 21:36:33 +0100 Subject: [PATCH 4/4] test: declare pagination and HTTP namespaces in the delivery address API test Fixes import order in OptionsWithersTest and lets listPage() and the error paths run under Infection's strict coverage. --- tests/Api/ClientDeliveryAddressesApiTest.php | 11 +++++------ tests/Api/Options/OptionsWithersTest.php | 4 ++-- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/tests/Api/ClientDeliveryAddressesApiTest.php b/tests/Api/ClientDeliveryAddressesApiTest.php index 95128a77..a9798e30 100644 --- a/tests/Api/ClientDeliveryAddressesApiTest.php +++ b/tests/Api/ClientDeliveryAddressesApiTest.php @@ -17,7 +17,6 @@ use Justpilot\Billomat\Exception\NotFoundException; use Justpilot\Billomat\Exception\ValidationException; use Justpilot\Billomat\Http\BillomatHttpClient; -use Justpilot\Billomat\Internal\ScalarCaster; use Justpilot\Billomat\Model\ClientDeliveryAddress; use Justpilot\Billomat\Tests\Support\CapturedRequest; use PHPUnit\Framework\Attributes\CoversClass; @@ -33,15 +32,15 @@ #[CoversClass(ClientDeliveryAddressCreateOptions::class)] #[CoversClass(ClientDeliveryAddressUpdateOptions::class)] #[CoversClass(ClientDeliveryAddress::class)] -#[UsesClass(BillomatConfig::class)] #[UsesClass(BillomatClient::class)] #[UsesClass(ClientsApi::class)] #[UsesClass(OrderBy::class)] #[UsesClass(SubResourceFilter::class)] -#[UsesClass(RetryPolicy::class)] -#[UsesClass(BillomatHttpClient::class)] -#[UsesClass(ScalarCaster::class)] -#[UsesNamespace('Justpilot\Billomat\Exception')] +#[UsesNamespace('Justpilot\\Billomat\\Config')] +#[UsesNamespace('Justpilot\\Billomat\\Exception')] +#[UsesNamespace('Justpilot\\Billomat\\Http')] +#[UsesNamespace('Justpilot\\Billomat\\Internal')] +#[UsesNamespace('Justpilot\\Billomat\\Pagination')] final class ClientDeliveryAddressesApiTest extends TestCase { /** diff --git a/tests/Api/Options/OptionsWithersTest.php b/tests/Api/Options/OptionsWithersTest.php index 6820ae7a..5abc05ca 100644 --- a/tests/Api/Options/OptionsWithersTest.php +++ b/tests/Api/Options/OptionsWithersTest.php @@ -12,6 +12,8 @@ use Justpilot\Billomat\Api\ArticleUpdateOptions; use Justpilot\Billomat\Api\Clear; use Justpilot\Billomat\Api\ClientCreateOptions; +use Justpilot\Billomat\Api\ClientDeliveryAddressCreateOptions; +use Justpilot\Billomat\Api\ClientDeliveryAddressUpdateOptions; use Justpilot\Billomat\Api\ClientPropertyValueCreateOptions; use Justpilot\Billomat\Api\ClientTagCreateOptions; use Justpilot\Billomat\Api\ClientUpdateOptions; @@ -21,8 +23,6 @@ use Justpilot\Billomat\Api\ConfirmationItemUpdateOptions; use Justpilot\Billomat\Api\ConfirmationTagCreateOptions; use Justpilot\Billomat\Api\ConfirmationUpdateOptions; -use Justpilot\Billomat\Api\ClientDeliveryAddressCreateOptions; -use Justpilot\Billomat\Api\ClientDeliveryAddressUpdateOptions; use Justpilot\Billomat\Api\ContactCreateOptions; use Justpilot\Billomat\Api\ContactUpdateOptions; use Justpilot\Billomat\Api\CountryTaxCreateOptions;